FullStack AI Hub
Studio
System Design · 09. Whole Systems
9 min
10 steps
Beginner

HLD & LLD

Zoom seamlessly from distributed boxes and SLAs down to class boundaries, state machines, and concurrency guards.

System Design09. Whole SystemsLesson 1 of 4
9 minBeginner10 steps

HLD & LLD

Zoom seamlessly from distributed boxes and SLAs down to class boundaries, state machines, and concurrency guards.

DAILY USERS
500K
P95 TARGET
< 200 ms
CONSISTENCY
Strict ACID
AVAILABILITY
99.95%
500K DAUAPI Contract24%p95 < 200msCheckoutDomain28%ACID OrdersOrders DB22%Zero lost ordersCheckout Scope MatrixFunctionalCreate, pay & track ordersNon-Functional99.95% up · P95 < 200msHard RuleZero double charges
read / API call
stateful write / commit
fast reply / receipt
cross-service / async event
rejected / illegal transition
In This LessonStep 1 of 10
What You Will Master
  • ✓Separate functional requirements from non-functional SLAs and convert daily traffic into read/write QPS
  • ✓Design clean High-Level Design service tiers, private data ownership, and async decoupling
  • ✓Zoom inside a service to structure controllers, domain services, state machines, and repository interfaces
  • ✓Connect LLD guards (idempotency keys, Strategy plug-ins, Transactional Outbox) back to HLD resilience

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
High-Level Design (HLD)Macro topology: traffic math, bounded services, caching, queues, and fault isolation across networksHides class coupling, edge-case race conditions, and domain state invariants
Low-Level Design (LLD)Inside one service: layered interfaces, entities, state machines, and unit-testable business rulesCannot rescue a flawed HLD bottleneck, missing cache, or unsharded hot database
Finite State Machine (FSM)Orders, payments, rides, and bookings where out-of-order webhooks could corrupt lifecycle stateRequires explicit transition-table updates and migrations when adding new workflow states
Strategy + Transactional OutboxSwappable payment rails (Open/Closed) and atomic DB-plus-event publishing without dual-write lossAdds thin interface indirection and an outbox relay poller to operate

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for HLD & LLD.

STEP 01 · SETUPJump to step →

Start with scope: functional vs non-functional SLAs

Every great design starts by shrinking a vague prompt ("Build e-commerce checkout") into **Functional Requirements** (create, pay, track orders) and **Non-Functional SLAs** (`99.95%` uptime, `P95 < 200 ms`, zero double charges).

Functional specs shape your APIs and domain entities (`LLD`), while non-functional targets decide your caching, queues, and replication topology (`HLD`).

idea:Never draw boxes before locking SLAs—a 10-rps internal tool and a 50K-rps flash-sale checkout need completely different HLDs.

Functional vs Non-FunctionalSLA TargetsScope Bounding
STEP 02 · TECHNIQUEJump to step →

Back-of-the-envelope QPS & storage math

Convert daily product numbers into concrete engineering constraints: `100M catalog views/day` is `~1,150 read QPS` (`~3,500 peak`), while `200K orders/day` is only `~2.3 write QPS` (`~140 peak`).

That **25:1 read-to-write asymmetry** immediately proves why you should split a cache-backed `Read Path` from an ACID-protected `Write Path`.

good:Mental shortcut: 1 day = 86,400 seconds ≈ 100,000. Divide daily events by 100K for average QPS, then multiply by 3× for peak.

Back-of-the-Envelope MathRead/Write RatioStorage Estimation
STEP 03 · SOLUTIONJump to step →

High-Level Design: boxes, flows & data stores

In **High-Level Design (HLD)**, we zoom out to the network topology: clients enter via an **API Gateway**, which routes to stateless services (`Catalog`, `Orders`, `Payments`) aligned on one clean tier.

Synchronous paths stay minimal (`Orders → SQL`), while slow side effects like receipt emails and warehouse fulfillment flow through an async **Event Queue**.

idea:HLD answers "What runs where across machines?"—focus on traffic paths, caching, storage engines, async queues, and failure domains.

High-Level DesignAPI GatewayAsync Decoupling
STEP 04 · PROBLEMJump to step →

Clean boundaries vs shared-database coupling

Letting `Payments Svc` query `Orders DB` tables directly turns your microservices into a brittle **distributed monolith**—any schema migration in Orders breaks Payments overnight.

Enforce strict **Database-per-Service** ownership and communicate across bounded contexts exclusively via versioned API contracts (`ChargeContract v2`) or domain events.

watch:Never share raw database tables across teams. Versioned API contracts are the exact handoff seam between HLD and LLD.

Bounded ContextDatabase per ServiceAPI Contracts
STEP 05 · TECHNIQUEJump to step →

Zoom inside Orders Svc: Controller → Domain → Repo

Now crack open the `Orders Svc` box from our HLD! Inside clean **Low-Level Design (LLD)**, code separates into three crisp layers instead of one giant 2,000-line controller.

`OrderController` validates HTTP DTOs, `OrderService` enforces pure business rules (`Order`, `LineItem`, `Money`), and `IOrderRepository` hides Postgres behind a swappable port interface.

good:Dependency Inversion (Hexagonal LLD): the Domain defines `IOrderRepository`, and Postgres implements it—so 100% of business rules unit-test in 12 ms without a DB.

Hexagonal ArchitectureRepository InterfaceDomain Entities
STEP 06 · SOLUTIONJump to step →

Guard illegal transitions with a Finite State Machine

Without a **Finite State Machine (FSM)**, delayed webhooks or double-clicks can ship a `CANCELLED` order or refund a `CREATED` cart. Scattered `if (status === ...)` checks inevitably miss corner cases.

Encoding one explicit transition table inside `Order.transitionTo(next)` guarantees only legal lifecycle arcs—`CREATED → PAID → PACKED → SHIPPED`—can ever commit.

idea:Make illegal states unrepresentable: one immutable transition table blocks every race condition and out-of-order webhook atomically.

Finite State MachineDomain InvariantsTerminal States
STEP 07 · PROBLEMJump to step →

Stop double charges: Idempotency & Optimistic Locks

On flaky mobile networks, shoppers double-tap "Pay" and HLD gateways retry after timeouts. Without LLD concurrency control, both requests hit the card processor and **double-charge** the customer.

Pair a unique `Idempotency-Key` table with an optimistic `version` check (`UPDATE orders SET status=PAID, version=version+1 WHERE id=? AND version=1`) so retries safely replay the original receipt.

watch:HLD retries guarantee at-least-once delivery—true exactly-once checkout effects happen only when LLD deduplicates by Idempotency-Key.

Idempotency-KeyOptimistic Locking (CAS)Safe Retries
STEP 08 · TECHNIQUEJump to step →

Extensibility via Strategy Pattern (Open/Closed)

Product needs `Card`, `UPI`, and `Apple Pay` today—and `BNPL` next quarter. Cramming every gateway into one giant `switch (method)` inside `OrderService` invites regressions on every release.

Define a crisp `IPaymentStrategy` interface (`authorize()`, `capture()`, `refund()`) and resolve aligned concrete adapters via a `PaymentRegistry`. Adding a new rail requires **zero edits** to core checkout logic.

good:Open/Closed Principle in practice: Strategy isolates volatile external payment SDKs behind a tiny uniform interface.

Strategy PatternOpen/Closed PrincipleAdapter Isolation
STEP 09 · TRADE-OFFJump to step →

How LLD timeouts & Outbox protect HLD resilience

HLD and LLD reinforce each other under failure. If an LLD HTTP client omits a `2s timeout`, one hung dependency exhausts every HLD thread.

Likewise, writing `Order` and an `Outbox` row inside one atomic local SQL transaction guarantees the HLD `Event Broker` never loses an event if the server crashes right after commit.

watch:Dual writes (`DB.commit()` then `Kafka.publish()`) lose events on crashes. Transactional Outbox turns LLD ACID into HLD at-least-once reliability.

Transactional OutboxDual-Write HazardDead-Letter Queue
STEP 10 · RECAPJump to step →

The complete two-altitude engineering blueprint

In interviews and production design reviews alike, move smoothly across both altitudes: open with **Requirements & QPS Math**, sketch an aligned **HLD** of gateways, caches, private DBs, and queues, then zoom inside your core service to lock down **LLD** interfaces, FSM invariants, idempotency, strategies, and Outbox.

good:Two-Altitude Checklist: HLD (SLAs, QPS math, bounded services, cache, async queues) + LLD (Hexagonal layers, FSM, Idempotency-Key + CAS, Strategy, Outbox).

HLD + LLD MasteryBounded ContextsResilient Checkout

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.