System Design Fundamentals
This chapter begins with requirements and estimates, then develops scaling, consistency, replication, caching, sagas, outbox delivery, CQRS, event sourcing, rate limits, and five complete reference designs.
- Explain Scalability & CAP theorem by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Distributed patterns by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Rate limiting algorithms by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain 5 system design problems solved by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Consistency & connection scaling by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For System Design Fundamentals, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the architecture learning arc appropriate to this subject.
The problem this chapter solves
This chapter begins with requirements and estimates, then develops scaling, consistency, replication, caching, sagas, outbox delivery, CQRS, event sourcing, rate limits, and five complete reference designs.
Distributed systems fail partially and operate under finite latency, throughput, cost, and team capacity. Explicit trade-offs prevent accidental architectures.
Learning outcomes
- Explain Scalability & CAP theorem by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Distributed patterns by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Rate limiting algorithms by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain 5 system design problems solved by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Consistency & connection scaling by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
Every remote call crosses a failure boundary. Replication creates ordering and consistency questions; queues separate production from consumption; caches create invalidation questions; partitioning creates routing and hotspot questions. Good designs make ownership and retry semantics visible. In System Design Fundamentals, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The caller validates the request and attaches a stable operation identity.
- The owning service applies the authoritative invariant and commits durable state before advertising success.
- An outbox or versioned response communicates the result across process boundaries under explicit ordering and retry semantics.
- Downstream consumers update derived state idempotently and reconcile gaps or duplicates.
- Load, failure, security, and recovery tests verify the SLO and every critical state transition.
Memory and performance lens
Capacity planning considers working sets, cache hit rate, queue backlog, connection pools, fan-out, and per-request amplification. A small per-request allocation or extra query becomes material at high concurrency. For System Design Fundamentals, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning System Design Fundamentals, measure capacity per critical path, tail latency, availability/error budget, consistency lag, recovery objectives, cost per outcome, and evaluation quality rather than optimizing from source-code appearance.
1. Scalability & CAP theorem
The Scalability & CAP theorem unit begins with vertical vs horizontal scaling limits: Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Scalability & CAP theorem
| Concept | Meaning | Engineering decision |
|---|---|---|
| vertical vs horizontal scaling limits | Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
| load balancing: Round Robin/LeastConn/Consistent Hashing | Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
| CDN + cache invalidation strategies | Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
| CAP theorem: CP (PostgreSQL) vs AP (Cassandra) systems | Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
| eventual consistency + conflict resolution | Scalability increases useful throughput under load; CAP states that during a network partition a distributed system cannot guarantee both linearizable availability and consistency for the same operation. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
Critical path and failure behavior: Scalability & CAP theorem
vertical vs horizontal scaling limits. Load balancers distribute requests, caches shorten data paths, replication creates copies, and partition routing selects an owner. Consistency choices are operation-specific, not a label for an entire product.
load balancing: Round Robin/LeastConn/Consistent Hashing. Load balancers distribute requests, caches shorten data paths, replication creates copies, and partition routing selects an owner. Consistency choices are operation-specific, not a label for an entire product.
CDN + cache invalidation strategies. Load balancers distribute requests, caches shorten data paths, replication creates copies, and partition routing selects an owner. Consistency choices are operation-specific, not a label for an entire product.
CAP theorem: CP (PostgreSQL) vs AP (Cassandra) systems. Load balancers distribute requests, caches shorten data paths, replication creates copies, and partition routing selects an owner. Consistency choices are operation-specific, not a label for an entire product.
eventual consistency + conflict resolution. Load balancers distribute requests, caches shorten data paths, replication creates copies, and partition routing selects an owner. Consistency choices are operation-specific, not a label for an entire product.
Read these as one system: vertical vs horizontal scaling limits establishes the starting contract, load balancing: Round Robin/LeastConn/Consistent Hashing changes how that contract is executed or represented, and eventual consistency + conflict resolution exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: Scalability & CAP theorem
| Risk | Why it matters |
|---|---|
| vertical vs horizontal scaling limits | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. |
| load balancing: Round Robin/LeastConn/Consistent Hashing | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. |
| CDN + cache invalidation strategies | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. |
| CAP theorem: CP (PostgreSQL) vs AP (Cassandra) systems | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. |
| eventual consistency + conflict resolution | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. |
Design review exercise: Scalability & CAP theorem
- Foundation: implement or demonstrate vertical vs horizontal scaling limits with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine vertical vs horizontal scaling limits with load balancing: Round Robin/LeastConn/Consistent Hashing. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for eventual consistency + conflict resolution. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Distributed patterns
The Distributed patterns unit begins with Saga pattern: choreography vs orchestration: Distributed patterns coordinate state without pretending several services share one local transaction. Use stable command/event IDs and design reconciliation paths. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Distributed patterns
| Concept | Meaning | Engineering decision |
|---|---|---|
| Saga pattern: choreography vs orchestration | Distributed patterns coordinate state without pretending several services share one local transaction. | Use stable command/event IDs and design reconciliation paths. |
| Outbox pattern for reliable event publishing | Distributed patterns coordinate state without pretending several services share one local transaction. | Use stable command/event IDs and design reconciliation paths. |
| CQRS: separate read/write models | Distributed patterns coordinate state without pretending several services share one local transaction. | Use stable command/event IDs and design reconciliation paths. |
| Event sourcing: event log as source of truth | Distributed patterns coordinate state without pretending several services share one local transaction. | Use stable command/event IDs and design reconciliation paths. |
| 2PC and why it's avoided | Distributed patterns coordinate state without pretending several services share one local transaction. | Use stable command/event IDs and design reconciliation paths. |
Critical path and failure behavior: Distributed patterns
Saga pattern: choreography vs orchestration. A saga commits local steps and compensates later; an outbox commits domain state and an event row together; CQRS separates write and read models; event sourcing derives state from an append-only history.
Outbox pattern for reliable event publishing. A saga commits local steps and compensates later; an outbox commits domain state and an event row together; CQRS separates write and read models; event sourcing derives state from an append-only history.
CQRS: separate read/write models. A saga commits local steps and compensates later; an outbox commits domain state and an event row together; CQRS separates write and read models; event sourcing derives state from an append-only history.
Event sourcing: event log as source of truth. A saga commits local steps and compensates later; an outbox commits domain state and an event row together; CQRS separates write and read models; event sourcing derives state from an append-only history.
2PC and why it's avoided. A saga commits local steps and compensates later; an outbox commits domain state and an event row together; CQRS separates write and read models; event sourcing derives state from an append-only history.
Read these as one system: Saga pattern: choreography vs orchestration establishes the starting contract, Outbox pattern for reliable event publishing changes how that contract is executed or represented, and 2PC and why it's avoided exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Distributed patterns
1BEGIN; UPDATE aggregate ...; INSERT INTO outbox(event_id, payload) ...; COMMIT;This Distributed patterns slice makes Saga pattern: choreography vs orchestration observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward 2PC and why it's avoided, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Distributed patterns
| Risk | Why it matters |
|---|---|
| Saga pattern: choreography vs orchestration | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. |
| Outbox pattern for reliable event publishing | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. |
| CQRS: separate read/write models | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. |
| Event sourcing: event log as source of truth | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. |
| 2PC and why it's avoided | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. |
Design review exercise: Distributed patterns
- Foundation: implement or demonstrate Saga pattern: choreography vs orchestration with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Saga pattern: choreography vs orchestration with Outbox pattern for reliable event publishing. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for 2PC and why it's avoided. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Rate limiting algorithms
The Rate limiting algorithms unit begins with token bucket: burst handling: Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. Use deterministic unique ordering and return retry metadata. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Rate limiting algorithms
| Concept | Meaning | Engineering decision |
|---|---|---|
| token bucket: burst handling | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| leaky bucket: smooth output | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| fixed window: boundary problem | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| sliding window log: accurate | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| sliding window counter: efficient | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| Redis distributed rate limiting | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
Critical path and failure behavior: Rate limiting algorithms
token bucket: burst handling. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
leaky bucket: smooth output. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
fixed window: boundary problem. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
sliding window log: accurate. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
sliding window counter: efficient. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
Redis distributed rate limiting. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
Read these as one system: token bucket: burst handling establishes the starting contract, leaky bucket: smooth output changes how that contract is executed or represented, and Redis distributed rate limiting exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Rate limiting algorithms
1allowed = min(capacity, tokens + elapsed * refill_rate) >= costThis Rate limiting algorithms slice makes token bucket: burst handling observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward Redis distributed rate limiting, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Rate limiting algorithms
| Risk | Why it matters |
|---|---|
| token bucket: burst handling | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| leaky bucket: smooth output | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| fixed window: boundary problem | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| sliding window log: accurate | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| sliding window counter: efficient | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| Redis distributed rate limiting | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
Design review exercise: Rate limiting algorithms
- Foundation: implement or demonstrate token bucket: burst handling with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine token bucket: burst handling with leaky bucket: smooth output. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Redis distributed rate limiting. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. 5 system design problems solved
The 5 system design problems solved unit begins with URL shortener (base62, DB sharding): A complete design ties APIs and data models to estimates, state ownership, critical paths, background flows, and failure recovery. State SLOs and identify the first bottleneck before adding components. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: 5 system design problems solved
| Concept | Meaning | Engineering decision |
|---|---|---|
| URL shortener (base62, DB sharding) | A complete design ties APIs and data models to estimates, state ownership, critical paths, background flows, and failure recovery. | State SLOs and identify the first bottleneck before adding components. |
| Chat system (WebSocket, message storage, presence) | A complete design ties APIs and data models to estimates, state ownership, critical paths, background flows, and failure recovery. | State SLOs and identify the first bottleneck before adding components. |
| Notification service (fan-out, APNs/FCM) | A complete design ties APIs and data models to estimates, state ownership, critical paths, background flows, and failure recovery. | State SLOs and identify the first bottleneck before adding components. |
| Rate limiter (Redis sliding window counter) | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| Job queue system (Kafka + workers + retry) | A complete design ties APIs and data models to estimates, state ownership, critical paths, background flows, and failure recovery. | State SLOs and identify the first bottleneck before adding components. |
Critical path and failure behavior: 5 system design problems solved
URL shortener (base62, DB sharding). The write path establishes durable truth; derived indexes, caches, feeds, and notifications update synchronously or from logs according to latency and consistency needs.
Chat system (WebSocket, message storage, presence). The write path establishes durable truth; derived indexes, caches, feeds, and notifications update synchronously or from logs according to latency and consistency needs.
Notification service (fan-out, APNs/FCM). The write path establishes durable truth; derived indexes, caches, feeds, and notifications update synchronously or from logs according to latency and consistency needs.
Rate limiter (Redis sliding window counter). Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
Job queue system (Kafka + workers + retry). The write path establishes durable truth; derived indexes, caches, feeds, and notifications update synchronously or from logs according to latency and consistency needs.
Read these as one system: URL shortener (base62, DB sharding) establishes the starting contract, Chat system (WebSocket, message storage, presence) changes how that contract is executed or represented, and Job queue system (Kafka + workers + retry) exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: 5 system design problems solved
| Risk | Why it matters |
|---|---|
| URL shortener (base62, DB sharding) | Architecture diagrams without capacity, failure, and migration reasoning are decorative rather than actionable. |
| Chat system (WebSocket, message storage, presence) | Architecture diagrams without capacity, failure, and migration reasoning are decorative rather than actionable. |
| Notification service (fan-out, APNs/FCM) | Architecture diagrams without capacity, failure, and migration reasoning are decorative rather than actionable. |
| Rate limiter (Redis sliding window counter) | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| Job queue system (Kafka + workers + retry) | Architecture diagrams without capacity, failure, and migration reasoning are decorative rather than actionable. |
Design review exercise: 5 system design problems solved
- Foundation: implement or demonstrate URL shortener (base62, DB sharding) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine URL shortener (base62, DB sharding) with Chat system (WebSocket, message storage, presence). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for Job queue system (Kafka + workers + retry). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Consistency & connection scaling
The Consistency & connection scaling unit begins with stateless vs stateful service instances: A stateless service instance can handle a request using external durable/shared state, while a stateful instance owns local identity or data whose placement and recovery affect correctness. Keep request-serving processes stateless when practical, externalize sessions carefully, and use stateful placement only when locality or ownership is part of the design. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Consistency & connection scaling
| Concept | Meaning | Engineering decision |
|---|---|---|
| stateless vs stateful service instances | A stateless service instance can handle a request using external durable/shared state, while a stateful instance owns local identity or data whose placement and recovery affect correctness. | Keep request-serving processes stateless when practical, externalize sessions carefully, and use stateful placement only when locality or ownership is part of the design. |
| PgBouncer session/transaction/statement pooling | Linearizability is a real-time guarantee for individual operations; serializability makes a transaction history equivalent to some serial order. Session guarantees such as read-your-writes address user experience on replicas. | State the exact operation guarantee, use primary/sticky reads after writes where required, and size connection pools across every service instance. |
| linearizability vs serializability | Linearizability is a real-time guarantee for individual operations; serializability makes a transaction history equivalent to some serial order. Session guarantees such as read-your-writes address user experience on replicas. | State the exact operation guarantee, use primary/sticky reads after writes where required, and size connection pools across every service instance. |
| read-your-writes and monotonic-read session guarantees | Linearizability is a real-time guarantee for individual operations; serializability makes a transaction history equivalent to some serial order. Session guarantees such as read-your-writes address user experience on replicas. | State the exact operation guarantee, use primary/sticky reads after writes where required, and size connection pools across every service instance. |
| replication lag and conflict resolution | Linearizability is a real-time guarantee for individual operations; serializability makes a transaction history equivalent to some serial order. Session guarantees such as read-your-writes address user experience on replicas. | State the exact operation guarantee, use primary/sticky reads after writes where required, and size connection pools across every service instance. |
Critical path and failure behavior: Consistency & connection scaling
stateless vs stateful service instances. Load balancers can send independent stateless requests to any healthy replica. Stateful workloads require stable identity, attached/replicated storage, leader or partition ownership, and an explicit transfer/recovery protocol.
PgBouncer session/transaction/statement pooling. PgBouncer transaction pooling reuses server connections after each transaction but cannot safely preserve arbitrary session state. Replicas apply changes later, so routing or version tokens may be needed for fresh reads.
linearizability vs serializability. PgBouncer transaction pooling reuses server connections after each transaction but cannot safely preserve arbitrary session state. Replicas apply changes later, so routing or version tokens may be needed for fresh reads.
read-your-writes and monotonic-read session guarantees. PgBouncer transaction pooling reuses server connections after each transaction but cannot safely preserve arbitrary session state. Replicas apply changes later, so routing or version tokens may be needed for fresh reads.
replication lag and conflict resolution. PgBouncer transaction pooling reuses server connections after each transaction but cannot safely preserve arbitrary session state. Replicas apply changes later, so routing or version tokens may be needed for fresh reads.
Read these as one system: stateless vs stateful service instances establishes the starting contract, PgBouncer session/transaction/statement pooling changes how that contract is executed or represented, and replication lag and conflict resolution exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: Consistency & connection scaling
| Risk | Why it matters |
|---|---|
| stateless vs stateful service instances | Calling a service stateless while keeping sessions, queues, or files only in process memory creates lost state and load-balancing inconsistencies. |
| PgBouncer session/transaction/statement pooling | Calling a database 'strongly consistent' without isolation, replica-routing, and transaction scope is incomplete. |
| linearizability vs serializability | Calling a database 'strongly consistent' without isolation, replica-routing, and transaction scope is incomplete. |
| read-your-writes and monotonic-read session guarantees | Calling a database 'strongly consistent' without isolation, replica-routing, and transaction scope is incomplete. |
| replication lag and conflict resolution | Calling a database 'strongly consistent' without isolation, replica-routing, and transaction scope is incomplete. |
Design review exercise: Consistency & connection scaling
- Foundation: implement or demonstrate stateless vs stateful service instances with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine stateless vs stateful service instances with PgBouncer session/transaction/statement pooling. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for replication lag and conflict resolution. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1# Atomic Redis token-bucket decision (conceptual Python wrapper)2def allow(subject: str, now_ms: int, capacity: int, refill_per_ms: float, cost: int = 1):3 # Lua receives the key, current time, capacity, rate, cost, and TTL.4 allowed, remaining, retry_after_ms = redis.evalsha(5 TOKEN_BUCKET_SHA, 1, f"rate:{subject}", now_ms, capacity, refill_per_ms, cost, 120_0006 )7 return {8 "allowed": bool(allowed),9 "remaining": int(remaining),10 "retry_after_ms": int(retry_after_ms),11 }Expected result
1The distributed decision is atomic and returns enough metadata for 429 and Retry-After behavior.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | # Atomic Redis token-bucket decision (conceptual Python wrapper) | Implements the next python statement in the example's data flow. |
| 2 | def allow(subject: str, now_ms: int, capacity: int, refill_per_ms: float, cost: int = 1): | Defines a function; its parameters form the explicit input boundary. |
| 3 | # Lua receives the key, current time, capacity, rate, cost, and TTL. | Implements the next python statement in the example's data flow. |
| 4 | allowed, remaining, retry_after_ms = redis.evalsha( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 5 | TOKEN_BUCKET_SHA, 1, f"rate:{subject}", now_ms, capacity, refill_per_ms, cost, 120_000 | Implements the next python statement in the example's data flow. |
| 6 | ) | Implements the next python statement in the example's data flow. |
| 7 | return { | Returns the observable result to the caller and ends this invocation. |
| 8 | "allowed": bool(allowed), | Implements the next python statement in the example's data flow. |
| 9 | "remaining": int(remaining), | Implements the next python statement in the example's data flow. |
| 10 | "retry_after_ms": int(retry_after_ms), | Implements the next python statement in the example's data flow. |
| 11 | } | Implements the next python statement in the example's data flow. |
Step-by-step execution
- The caller validates the request and attaches a stable operation identity.
- The owning service applies the authoritative invariant and commits durable state before advertising success.
- An outbox or versioned response communicates the result across process boundaries under explicit ordering and retry semantics.
- Downstream consumers update derived state idempotently and reconcile gaps or duplicates.
- Load, failure, security, and recovery tests verify the SLO and every critical state transition.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Scalability & CAP theorem | PostgreSQL is not universally 'CP' and Cassandra is not universally 'AP'; configuration and operation semantics matter. | Begin with estimates, make services stateless where practical, and define stale/read-your-writes expectations. |
| Distributed patterns | Compensation is a new business action, not a magical rollback, and outbox publication remains at-least-once. | Use stable command/event IDs and design reconciliation paths. |
| Rate limiting algorithms | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. | Use deterministic unique ordering and return retry metadata. |
| 5 system design problems solved | Architecture diagrams without capacity, failure, and migration reasoning are decorative rather than actionable. | State SLOs and identify the first bottleneck before adding components. |
| Consistency & connection scaling | Calling a service stateless while keeping sessions, queues, or files only in process memory creates lost state and load-balancing inconsistencies. | Keep request-serving processes stateless when practical, externalize sessions carefully, and use stateful placement only when locality or ownership is part of the design. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the System Design Portfolio Doc project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Scalability & CAP theorem: vertical vs horizontal scaling limits
- To do: Scalability & CAP theorem: load balancing: Round Robin/LeastConn/Consistent Hashing
- To do: Scalability & CAP theorem: CDN + cache invalidation strategies
- To do: Scalability & CAP theorem: CAP theorem: CP (PostgreSQL) vs AP (Cassandra) systems
- To do: Scalability & CAP theorem: eventual consistency + conflict resolution
- To do: Distributed patterns: Saga pattern: choreography vs orchestration
- To do: Distributed patterns: Outbox pattern for reliable event publishing
- To do: Distributed patterns: CQRS: separate read/write models
- To do: Distributed patterns: Event sourcing: event log as source of truth
- To do: Distributed patterns: 2PC and why it's avoided
- To do: Rate limiting algorithms: token bucket: burst handling
- To do: Rate limiting algorithms: leaky bucket: smooth output
- To do: Rate limiting algorithms: fixed window: boundary problem
- To do: Rate limiting algorithms: sliding window log: accurate
- To do: Rate limiting algorithms: sliding window counter: efficient
- To do: Rate limiting algorithms: Redis distributed rate limiting
- To do: 5 system design problems solved: URL shortener (base62, DB sharding)
- To do: 5 system design problems solved: Chat system (WebSocket, message storage, presence)
- To do: 5 system design problems solved: Notification service (fan-out, APNs/FCM)
- To do: 5 system design problems solved: Rate limiter (Redis sliding window counter)
- To do: 5 system design problems solved: Job queue system (Kafka + workers + retry)
- To do: Consistency & connection scaling: stateless vs stateful service instances
- To do: Consistency & connection scaling: PgBouncer session/transaction/statement pooling
- To do: Consistency & connection scaling: linearizability vs serializability
- To do: Consistency & connection scaling: read-your-writes and monotonic-read session guarantees
- To do: Consistency & connection scaling: replication lag and conflict resolution
Quick revision
- Scalability & CAP theorem: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Distributed patterns: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Rate limiting algorithms: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- 5 system design problems solved: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Consistency & connection scaling: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?