Rana Maninder Singh
Lesson 3 of 12Solution Architecture & System Design

Lesson 03 — Architecture Patterns & Design Principles

Course: Solution Architecture & System Design (sad) | Group: Data Engineering | Lesson ID: sad3


Lesson opener

In one line: Architecture patterns are reusable shapes; the skill is choosing among them with explicit trade-offs, not collecting fashionable labels.

Why it matters: Choosing microservices or a monolith without a trade-off table creates thrash that no amount of code quality can fix.

Before this lesson: Introduction to Solution Architecture and Requirements Analysis & System Thinking. Helpful: Introduction to APIs, Kafka architecture.

Workplace scenario — Northline Consumer Goods: You have documented requirements for three new systems: a Supplier Portal (moderate traffic, CRUD-heavy, external users), a real-time Pricing Engine (high throughput, low latency, 1.5M calculations/hour at peak), and an Inventory Alert System (many downstream consumers, asynchronous fan-out). You need to recommend an architectural pattern for each and defend the recommendation with a trade-off analysis.

What You Will Be Able to Do

By the end of this lesson you will be able to:

Deliverable: A Trade-off Analysis Matrix for the three Northline Consumer Goods systems, with a pattern recommendation and an ADR for each.


Prerequisites

TopicWhere to review
Architecture lifecycle and ADRsIntroduction to Solution Architecture
Functional and non-functional requirementsRequirements Analysis & System Thinking
REST API fundamentalsIntroduction to APIs
Event streaming fundamentals (Kafka)Real-time Data Engineering — Kafka

Plain English: Architectural Patterns

Pattern 1 — Layered (N-Tier) Architecture

The layered pattern organises a system into horizontal layers, each with a distinct and non-overlapping responsibility. The classic three-layer model:

┌─────────────────────────────────────────────┐
│  Presentation Layer  (UI, REST/GraphQL API)  │
├─────────────────────────────────────────────┤
│  Business Logic Layer (domain rules, flows) │
├─────────────────────────────────────────────┤
│  Data Access Layer   (DB, external APIs)    │
└─────────────────────────────────────────────┘

Each layer communicates only with the layer directly below it in strict layering, or with any lower layer in relaxed layering. The invariant is: upper layers depend on lower layers; lower layers are never aware of upper layers.

Strengths:

Weaknesses:

When to use: Internal tools, admin dashboards, CRUD-heavy applications with moderate and predictable traffic, portals with well-defined user workflows. The Northline Supplier Portal is a good candidate.

Pattern 2 — Client-Server

Client-server is the foundational model of networked computing: one or more clients make requests; one or more servers fulfil them. Every web application is client-server at the macro level. In architecture conversations this pattern matters because of where responsibilities are divided:

VariantClient responsibilityServer responsibilityTrade-off
Thin client (server-rendered HTML)Render HTML, handle user eventsAll logic, template renderingSimpler client; easier to secure; less dynamic UX
Thick client / SPAUI rendering, state managementData API onlyRicher UX; CORS and auth complexity increases
Service-to-serviceCall server APIsProcess business logicThe basis of microservices communication

When to use: Client-server is not a pattern to "choose" so much as a frame that applies to almost everything. The architectural question is always: where does logic live, and what protocol mediates the conversation?

Pattern 3 — Modular Monolith

A monolith is a single deployable unit containing all of an application's features. The term has acquired unfair negative connotations, largely from experiences with poorly designed ("big ball of mud") monoliths. A modular monolith — one with enforced internal boundaries between modules — is often the correct architecture for a growing organisation.

┌──────────────────────────────────────────────────────┐
│                 Monolith Process                      │
│  ┌────────────┐  ┌────────────┐  ┌────────────────┐  │
│  │   Orders   │  │ Inventory  │  │    Pricing     │  │
│  │   Module   │  │   Module   │  │    Module      │  │
│  └────────────┘  └────────────┘  └────────────────┘  │
│               Shared PostgreSQL Database              │
└──────────────────────────────────────────────────────┘

Strengths:

Weaknesses:

When to use: Early-stage products, small teams (< 6–8 engineers), systems where bounded contexts are not yet clear. Internal module boundaries (no cross-module direct database access, only public module APIs) extend the modular monolith's useful life significantly and make extraction to microservices straightforward later.

Pattern 4 — Microservices

Microservices decompose a system into small, independently deployable services, each owning a single bounded context and its own data store.

  ┌───────────────┐    HTTP/gRPC    ┌───────────────┐
  │  Orders Svc   │───────────────▶│ Inventory Svc │
  │  (Postgres)   │                │  (Postgres)   │
  └───────────────┘                └───────────────┘
         │                                │
         └──────────────┬─────────────────┘
                        ▼
              API Gateway / BFF
                        │
                    Clients

Strengths:

Weaknesses:

When to use: Large teams (typically > 10 engineers) where team autonomy and independent deployment velocity justify the operational cost. Mature bounded contexts where service responsibilities are clear and unlikely to change. Systems with modules that have genuinely divergent scaling requirements. Microservices are a destination reached when a monolith's limitations are being felt — not a starting architecture.

Pattern 5 — Event-Driven Architecture (EDA)

In event-driven architecture, components communicate by emitting and consuming events through a broker. Producers do not know who consumes their events. Consumers do not know who produced them. The coupling is through a shared event schema, not a direct API call.

                     ┌───────────────────────┐
                     │    Event Broker        │
                     │  (managed queue or     │
                     │   Kafka cluster)       │
┌───────────────┐    │                       │    ┌───────────────────┐
│ Order Service ├───▶│   order.received      ├───▶│ Notification Svc  │
└───────────────┘    │   inventory.low       │    └───────────────────┘
                     │                       │    ┌───────────────────┐
                     │                       ├───▶│  Inventory Svc    │
                     └───────────────────────┘    └───────────────────┘

For Kafka mechanics (partitions, consumer groups, offset management) see Real-time Data Engineering — Kafka. This lesson focuses on the architectural pattern and when to apply it.

Strengths:

Weaknesses:

When to use: Asynchronous processing where a response is not needed immediately. Fan-out patterns where one event must reach multiple independent consumers. Decoupling systems with different reliability profiles or deployment schedules. Audit logging. Systems where producers and consumers need to evolve independently.


Architectural Design Principles

These principles apply across all patterns. They are the guardrails that prevent a well-chosen pattern from decaying into a big ball of mud.

Separation of Concerns (SoC): Every component has one clearly defined responsibility. A module that manages UI rendering, applies business rules, and directly executes SQL queries is violating SoC — and will be hard to test, change, and reason about.

Single Responsibility Principle (SRP — the S of SOLID): A service or class should have exactly one reason to change. If your Order service also sends emails, processes refunds, and manages inventory, it has too many reasons to change — and changes to any one of them risk breaking the others.

Open/Closed Principle: Components should be open for extension and closed for modification. Add a new promotion type by adding a new rule class; do not modify the existing rules engine. This limits the blast radius of change.

Dependency Inversion: High-level modules should not depend on low-level modules; both should depend on abstractions. Your Pricing service should depend on a PriceRulesRepository interface, not on a PostgreSQL-specific implementation. This enables testing (inject a mock), and future migration (swap the PostgreSQL implementation for a different store without touching business logic).

Don't Repeat Yourself (DRY): Shared logic belongs in a shared library, not copied across services. Caveat for microservices: shared libraries create deployment coupling. Apply DRY strictly within a service boundary; accept some controlled duplication across service boundaries rather than creating a shared library that couples independent services.

Design for failure: Assume every external dependency will fail at some point — and design for that assumption explicitly. Tools: timeouts (don't wait forever), retries with exponential back-off (handle transient failures), circuit breakers (stop calling a failing service and let it recover), bulkheads (limit one component's failure to a bounded area of the system).

Design for observability: You cannot manage what you cannot measure. Every service should emit structured logs (so queries can filter by field), metrics (counts, latencies, error rates), and distributed traces (so a request's journey can be reconstructed across services). Observability is an architectural concern, not an operational afterthought.


Teacher Walkthrough: Choosing a Pattern

Apply this framework when selecting a pattern for a new system:

  1. Map requirements to quality attributes. Which NFRs dominate? High throughput and independent scalability → consider dedicated service or EDA. Low latency with CRUD → layered or modular monolith. Fan-out to many consumers → EDA.
  2. Assess team size and maturity. Microservices require a mature DevOps platform. A team of three engineers operating fifteen microservices spends more time on infrastructure than on features.
  3. Assess domain maturity. If bounded contexts are unclear, start with a modular monolith. Extract services when service boundaries become stable and the cost of coupling outweighs the cost of distribution.
  4. Evaluate the operational cost honestly. Every pattern has an operational cost. Be specific: "operating a Kafka cluster requires on-call expertise in consumer group management and offset handling."
  5. Document the decision in an ADR. A pattern recommendation without a documented rationale is just an opinion.

Trade-off Analysis Matrix — Northline Consumer Goods

SystemDominant NFRsPattern recommendationKey rationale
Supplier PortalModerate traffic; CRUD; external users; data isolationLayered (3-tier) web applicationSimple operational model; clean security boundary; no independent scaling requirement
Pricing Engine1.5M req/hr; P95 ≤ 200 ms; fallback requiredDedicated service with in-memory rules cacheIndependent scaling without full microservices complexity; cache absorbs most load; clean fallback path
Inventory Alert SystemFan-out to 3+ independent consumers; asynchronous; consumers have different latency requirementsEvent-driven (message broker)Producer/consumer independence; new consumers without producer change; resilience to consumer lag

Worked Example 1 — Northline Consumer Goods: Pricing Engine Pattern Decision

Requirements relevant to pattern selection

Options evaluated

Option A — Inline module in the checkout monolith

The Pricing module runs inside the same process as checkout.

Pros: No network hop; lowest achievable latency; no additional infrastructure.

Cons: Pricing scales only by scaling the entire checkout; a crash in the pricing module crashes checkout; shared deployment means a Pricing change requires a checkout deployment.

Option B — Dedicated Pricing service with Redis rules cache

Checkout calls a dedicated Pricing service over HTTP. Pricing rules are pre-loaded into Redis (TTL 5 minutes, invalidated on rules-change events). Fallback path returns base price from a local reference table if Redis and the DB are both unavailable.

Pros: Independent scaling; clean fallback path; failure in Pricing does not crash Checkout (with circuit breaker); rules cache absorbs the majority of load, keeping DB queries low.

Cons: One additional service to operate; Redis adds infrastructure cost and a potential availability dependency.

Option C — Serverless function (e.g., AWS Lambda) per calculation request

Pros: No server management; scales automatically.

Cons: Cold-start latency (50–500 ms depending on runtime and memory allocation) conflicts with the 200 ms P95 target. Warm pool provisioning partially mitigates this but adds cost. Not recommended without benchmarking — pricing environment-dependent.

Decision: Option B

ADR-002: Dedicated Pricing Engine service with Redis rules cache
Status:  Accepted
Context: Pricing must handle 1.5M req/hr at P95 ≤ 200 ms, independently of the
         checkout service. A crash or deployment in Pricing must not affect checkout.
Decision: Deploy Pricing Engine as an independent service.
          Load promotion rules into Redis (TTL = 5 min, refreshed on rule-change event).
          Circuit breaker in checkout: if Pricing is unavailable, return base price (FR-004).
Consequences:
  + Independent scaling of pricing capacity.
  + Clean fallback path protects checkout from Pricing outages.
  - Additional Redis infrastructure and operational cost (environment-dependent).
  - Cache invalidation logic required; stale rules risk of ≤ 5 minutes after a change.
Rejected: Option A (checkout coupling); Option C (cold-start latency risk).
Risk: Redis single-point-of-failure → mitigate with Redis Cluster (minimum 3 nodes)
      or Redis Sentinel failover; document in runbook.

Pseudocode — pricing with fallback

import redis
from decimal import Decimal

def get_price(customer_segment: str, product_id: str, quantity: int) -> Decimal:
    cache_key = f"price:{customer_segment}:{product_id}:{quantity}"

    # 1. Try cache
    cached = redis_client.get(cache_key)
    if cached:
        return Decimal(cached)

    # 2. Try rules engine (DB-backed)
    try:
        rules = rules_repository.get_rules(customer_segment, product_id)
        price = apply_rules(rules, base_price_for(product_id), quantity)
        redis_client.setex(cache_key, 300, str(price))  # 5-minute TTL
        audit_log.record(customer_segment, product_id, price, rules)
        return price
    except RulesEngineUnavailable:
        # 3. FR-004 fallback — never block checkout
        return base_price_for(product_id)

No third-party libraries are used above beyond the Redis client; the pattern applies regardless of the specific Redis client library version.


Worked Example 2 — Northline Financial: Loan Origination Architecture Pattern Decision

Northline Financial is replacing its Access-database loan origination process. Team size: 4 engineers. Volume: 300 applications/day. Primary NFRs: full audit trail, data integrity, loan-officer UX, 99.5% availability.

Pattern evaluation

PatternFitReasoning
Layered modular monolithHighSmall team; well-understood domain; workflow is CRUD with state-machine transitions; audit trail via DB triggers
MicroservicesLowTeam of 4 cannot sustainably operate distributed services; domain bounded contexts not yet clear
Event-driven (full)PartialOverkill for the main application workflow; useful for the async credit-check integration

Recommendation: Modular monolith with async credit-check worker

The main workflow is a layered web application. The credit-check integration to Equifax API v3.0 is extracted as an asynchronous background worker — not because of scalability requirements, but because Equifax's P99 SLA of up to 5 seconds would create an unacceptable loan-officer experience if placed on the synchronous path.

┌────────────────────────────────────────────────────┐
│              Loan Origination Monolith              │
│  ┌──────────────┐ ┌──────────────┐ ┌────────────┐  │
│  │  Application │ │    Audit     │ │  Document  │  │
│  │    Module    │ │    Module    │ │   Module   │  │
│  └──────────────┘ └──────────────┘ └────────────┘  │
│                PostgreSQL 16                        │
└─────────────────────┬──────────────────────────────┘
                      │  async job queue
                      ▼
             ┌──────────────────────┐
             │  Credit Check Worker │──────▶ Equifax API v3.0
             └──────────────────────┘
ADR-003: Modular monolith with async credit-check worker
Status:  Accepted
Context: Team of 4; 300 applications/day; domain boundaries not yet stable.
         Equifax API adds 2–5 s latency — unacceptable on synchronous UI path.
Decision: Loan origination as a modular monolith. Credit check extracted to an async
          background worker; loan officer sees "credit check in progress" status.
Consequences:
  + Simple deployment and debugging for a small team.
  + Credit-check latency removed from UX-critical path.
  - Monolith must be broken up if team grows beyond ~8 engineers or if scaling
    requirements diverge (trigger documented in ADR).
  - Background worker failure must be monitored; retries and DLQ required.
Rejected: Microservices (team size and operational maturity insufficient).

Failure Case: Premature Microservices Decomposition

Symptoms

A Northline Financial technology initiative in an adjacent squad decomposes a new loan-comparison tool into eleven microservices before the first feature is live. After two months:

Root-cause diagnosis

Microservices were chosen because the engineering lead had used them successfully at a previous employer with a 40-person platform team. The team of 5 did not have the DevOps platform maturity to operate distributed services. The domain was new — bounded contexts were guesses, not informed by production behaviour — so several service boundaries were wrong and required cross-service transactions that the architecture had not designed for.

Correction

  1. Merge nine of the eleven services into a modular monolith, preserving clean internal module boundaries.
  2. Retain two genuine services with clear bounded contexts: the document storage service (different scaling and retention profile) and the credit bureau integration worker (async, different failure model).
  3. Establish a documented extraction criterion: "A service is extracted from the monolith only when (a) its scaling requirements demonstrably diverge from the monolith's, or (b) its team ownership and deployment cadence are genuinely independent, or (c) the monolith's deployment coupling is causing measurable delivery delays."

Validation after correction

P95 page-load drops to 350 ms. Deployment is a single artefact; coordination overhead eliminated. On-call alerts reduced by 70% in the first month.

Preventive controls


Guided Practice

Scenario

Northline Consumer Goods is building an Inventory Alert System: when stock of any SKU falls below a configurable threshold, three downstream systems must be notified — the replenishment team (email/Slack), the D2C website (show "low stock" badge), and the promotions engine (pause promotions for that SKU).

Stage 1 — List the NFRs most relevant to pattern selection (attempt before hints).

Hint: Think about fan-out, whether all consumers need immediate notification, and what happens if one consumer is slow or temporarily unavailable.

Stage 2 — Recommend a pattern and justify in three sentences (attempt before hints).

Hint: Three independent consumers that must react to the same event, each at their own pace.

Stage 3 — Write an ADR for your recommendation.

Hint: Follow the structure: Status, Context, Decision, Consequences, Rejected alternatives, Risks.

Full Guided Solution

Relevant NFRs:

Pattern recommendation: Event-driven architecture with a managed message broker.

Rationale: Three independent consumers must react to the same event, each with different latency requirements and failure profiles. Synchronous calls from the inventory monitor to each consumer would mean one slow or unavailable consumer blocks others. A message broker decouples producer and consumers, so each processes at its own pace. The inventory monitor publishes one event; consumer count is invisible to the producer — new consumers are addable with no producer change.

ADR:

ADR-004: Event-driven architecture for Inventory Alert System
Status:  Accepted
Context: Three consumers (replenishment, website, promotions) must react to stock-threshold
         events. They have different latency requirements and must not block each other.
Decision: Inventory monitor publishes inventory.threshold.breached events to a managed
          message broker. Each consumer subscribes independently. Consumers must handle
          at-least-once delivery idempotently (event includes SKU + threshold timestamp).
Consequences:
  + Producer/consumer independence; adding consumers requires no producer change.
  + Resilience to consumer downtime — events queue up and are processed on recovery.
  - Eventual consistency: consumers may see the threshold breach at different times.
  - Message broker infrastructure required; managed service recommended for a small team.
  - Consumers must be designed for idempotent processing (duplicate events possible).
Rejected: Synchronous fan-out (one slow consumer delays all others).
Risk: Message broker outage → threshold alerts not delivered → mitigate with a managed
      service with a documented availability SLA and DLQ for unprocessable messages.

Independent Practice

Design the architecture for a Northline Financial Notifications System: loan applicants receive email and SMS notifications at every loan application state change (Submitted → Under Review → Decision Made → Funds Disbursed). The notifications team is 2 engineers. Volume: 300 applications/day; up to 4 notifications per application.

Acceptance criteria / rubric:

CriterionPass
Pattern identifiedNamed correctly with a definition matching the lesson content
Trade-off analysisAt least 2 alternatives considered; decision justified against named NFRs and team size
ADR writtenStatus, Context, Decision, Consequences, Rejected alternatives, at least 1 Risk
Failure mode identifiedAt least one failure mode with a mitigation strategy
Operational cost assessedTeam size of 2 explicitly factored into the recommendation

Common Mistakes

  1. Choosing microservices for a small team. Microservices require a DevOps platform (CI/CD per service, service mesh or API gateway, centralised logging, distributed tracing) that takes months to build. A team of 3–5 engineers should start with a modular monolith.
  2. Placing non-deterministic external calls on the synchronous user path. Credit checks, carrier APIs, and payment gateways are slow and unreliable. Move them to an async worker to protect the user experience.
  3. Ignoring eventual consistency in event-driven systems. Between the time an event is published and the time all consumers have processed it, the system is in an inconsistent state. This must be explicitly designed for — user-facing states must handle "processing" or "pending" states gracefully.
  4. Treating patterns as mutually exclusive. Most real systems combine patterns: a layered monolith for the main application, an event broker for async fan-out, a dedicated service for a high-throughput calculation. The pattern is per subsystem, not per organisation.
  5. Pattern cargo-culting. "Everyone uses microservices" is not a reason. The reason must trace to a specific NFR or organisational constraint that the pattern genuinely addresses.

Five Quick Checks

Q1. A team of 4 engineers is building a new internal loan origination system. Volume: 300 applications/day. Which pattern — modular monolith or microservices — is more appropriate, and why?

A: Modular monolith. The volume does not create independent scaling requirements between modules. A team of 4 lacks the DevOps maturity to operate distributed services without spending most of their time on infrastructure. The domain is new and bounded contexts may not yet be stable — wrong service boundaries in microservices are expensive to correct.

Q2. What is the key architectural advantage of event-driven architecture over synchronous service-to-service calls when you have multiple consumers?

A: Consumer independence. Each consumer processes events at its own pace. A slow or temporarily unavailable consumer does not block other consumers or the producer. New consumers can subscribe without any change to the producer.

Q3. What does "design for failure" mean in concrete architectural terms?

A: Implement: timeouts (so a call to a failing service eventually terminates rather than hanging indefinitely), retries with exponential back-off (to handle transient failures without overwhelming a recovering service), circuit breakers (to stop calling a service that is consistently failing and allow it to recover), and bulkheads (to isolate a failure to one part of the system so it doesn't cascade).

Q4. What is the Dependency Inversion Principle, and why does it matter for testability?

A: High-level modules should not depend on low-level modules; both should depend on abstractions (interfaces). Practically: the Pricing service depends on a PriceRulesRepository interface; the PostgreSQL implementation is injected at runtime. In tests, a mock repository is injected instead. This makes unit tests fast and deterministic — no real database required.

Q5. A junior engineer says "we should split the Inventory and Orders modules into separate microservices." What question should you ask first?

A: "What specific problem would that solve?" — i.e., what NFR or operational constraint is not being met by the current modular monolith that microservice separation would address? If no specific pain is being felt, extraction is premature.


Quiz Alignment Note

Quizzes for sad3 will test: the named characteristics and trade-offs of each of the five architectural patterns; the monolith-vs-microservices selection criteria; synchronous vs asynchronous communication and when each is appropriate; at least two SOLID / design principles applied to an architecture scenario; ADR structure and what it must contain; and pattern selection given a scenario with specified NFRs and team size.


Key Takeaways

  • Five patterns: layered (horizontal responsibility separation), client-server (request/response division), modular monolith (single deployable, bounded internal modules), microservices (independently deployable bounded contexts with own data), event-driven (producer/consumer decoupling through an event broker). Each has genuine strengths and genuine costs.
  • Modular monolith is not a compromise — it is often the correct architecture for a growing team. Extract microservices when you feel the specific pain that extraction solves, not before.
  • Event-driven architecture is the right choice for fan-out, asynchronous processing, and decoupling systems with different reliability profiles. Its costs are eventual consistency and the need for idempotent consumers.
  • Design principles — SoC, SRP, Open/Closed, Dependency Inversion, DRY, design for failure, design for observability — apply regardless of which pattern you choose. They are the quality guardrails within a pattern.
  • Pattern choice must be documented in an ADR that includes rejected alternatives. "We considered X and rejected it because Y" is as important as the decision itself.

Next Lesson

Lesson 04 — Data Architecture & Storage Design applies architecture thinking to the data layer: when to use a transactional database, a data warehouse, a data lake, or a lakehouse — and how those decisions connect to the governance, compliance, and operational patterns you have built in this lesson.