Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

System design you can reason about

From a user need to data, scale, failure handling, and a tested design.

A practical guide to requirements, estimation, APIs, databases, caching, queues, replication, partitioning, security, operations, and a complete local URL-service capstone.

14 chapters9 diagrams28 practice tasks

Before you begin

How to use this guide

For developers who can write a small program and now want to explain how several components work together. No cloud subscription or distributed cluster is required for the core exercises.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

Start with the operation and its promises

Replace a vague architecture request with a small set of behaviours that can be tested.

By the end of this chapter
  • Separate functional behaviour from quality goals
  • Name assumptions and exclusions
  • Write an invariant and a failure story

A design begins with a user doing something

“Design a learning platform” is too broad to evaluate. Choose an operation such as saving a learner’s lesson completion. Describe who may call it, what data it accepts, the durable result, and what a successful response promises. Then describe reading that result. A system can accept a write quickly and still disappoint the learner if the next page immediately forgets it.

Functional requirements describe behaviour, while quality goals describe properties such as latency, availability, security, recoverability, and cost under stated conditions. They influence one another. A requirement to preserve an acknowledged answer through a machine loss changes storage and replication decisions. A desire for low latency alone does not explain whether stale progress is acceptable.

Go deeper: [3] Service level objectives · [1] HTTP semantics RFC 9110

Write a contract that exposes disagreement

An invariant is a condition that must remain true, such as “one learner cannot read another learner’s private progress.” It is stronger and more testable than a feature label like “secure accounts.” For every important invariant, identify where it is enforced and what happens when two operations race or a dependency fails.

Record assumptions beside the design: expected traffic, data retention, supported clients, team size, and the kinds of failures being considered. Explicitly exclude features that would change the problem, such as worldwide write availability or anonymous public uploads. Exclusions are not excuses; they prevent a reasonable small design from being judged against a different, unstated system.

Worked example · A first progress-save contract

  1. Caller: an authenticated learner. Input: an existing lesson identifier and a completion request.
  2. Effect: record completion once for that learner and lesson. The response reflects the committed result under the chosen write contract.
  3. Failures: reject invalid or unauthorized input; after a timeout the caller may not know whether the effect committed, so repeated requests need a defined meaning.

Result: You can now evaluate an API, schema, and retry strategy against the same promise.

Go deeper: [9] PostgreSQL 18 constraints · [7] Data integrity

Keep these ideas

  • Start with an observable operation and its promises.
  • State invariants and exclusions before choosing components.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

Rewrite “the system should be reliable and secure” as two concrete requirements for progress saving.

Hint: Name the operation, actor, measurement, and boundary.

Read the worked solution

1.2 · Practice task

A reviewer asks for global active-active writes after you propose a single-Region service. What should change in the discussion?

Hint: Treat it as a changed requirement, not a missing logo.

Read the worked solution

Chapter 02

Estimate load storage and latency with units

Use rough calculations to find the decision that deserves measurement.

By the end of this chapter
  • Convert daily traffic into rates
  • Estimate bandwidth and in-flight work
  • Distinguish averages from tails and peaks

Use a worksheet rather than impressive numbers

Suppose an imaginary service handles 864,000 reads per day. Dividing by 86,400 seconds gives an average of ten reads per second. A busy hour, retry burst, or popular course launch may be much higher. Record an assumed peak multiplier and then replace it with measured demand when possible. The multiplier is not a law of internet traffic.

Storage estimates need a record count, record size, retention policy, and overhead model. A 200-byte logical record does not imply exactly 200 bytes of disk use after indexes, encoding, metadata, replicas, and backups. Keep the raw-data estimate separate from those multipliers. This makes a later correction transparent instead of hiding everything inside one unexplained final number.

A hypothetical workload worksheet Python
reads_per_day = 864_000
average_rps = reads_per_day / 86_400
assumed_peak_rps = average_rps * 12
payload_bytes = 2_000
print(average_rps)
print(assumed_peak_rps)
print(assumed_peak_rps * payload_bytes)
Expected result
10.0
120.0
240000.0

Worked example · Interpret the bandwidth estimate

  1. The computed 240,000 bytes per second is payload only under the chosen peak-rate assumption.
  2. Headers, retransmissions, encryption framing, and request traffic add overhead. A cache can change the origin traffic without changing total user delivery.
  3. Measure the actual bytes and request distribution before treating the estimate as an infrastructure requirement.

Result: The arithmetic identifies assumptions to inspect, not a precise network bill.

Go deeper: [5] Handling overload · [3] Service level objectives

Latency is a distribution and a path

If a request makes three sequential calls, their durations contribute along the critical path. Parallel calls may overlap, but the request can still wait for the slowest required branch. Include connection setup, queue wait, lock wait, and retries where they occur. Measuring only application CPU time leaves much of a real request unexplained.

Average concurrency under stable conditions is approximately arrival rate multiplied by average time in the system. If 100 requests per second spend 0.3 seconds on average inside a boundary, about 30 requests are in flight there. This does not bound a burst or predict a percentile. A slow dependency can increase in-flight work until a pool or memory limit is reached. Tail latency and resource pressure should be investigated together.

A latency budget follows the required pathA request spends time waiting and executing across several stages. A budget must include every required stage and leave room for variation rather than allocating the entire target to one function.EntryConnection handling, admission, authentication, and routing.ApplicationValidation and domain work, including internal queue waits.Data accessConnection acquisition, locks, query execution, and transfer.ResponseFormatting and returning the result to the client.
A latency budget follows the required path. A request spends time waiting and executing across several stages. A budget must include every required stage and leave room for variation rather than allocating the entire target to one function.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [4] Monitoring distributed systems · [5] Handling overload

Keep these ideas

  • Units and assumptions make estimates reviewable.
  • Averages are useful but cannot substitute for a tail-latency or peak-load model.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

An assumed 4,320,000 requests arrive in a day. What is the daily average rate and an assumed 8× peak rate?

Hint: Use seconds per day and label the peak assumption.

Read the worked solution

2.2 · Practice task

A dashboard shows mean latency of 100 ms. Does that prove 99% of learners wait less than 200 ms?

Hint: One average does not specify a distribution.

Read the worked solution

Chapter 03

Design an API that can be used safely twice

Specify meaning, authorization, errors, and repeated requests before writing handlers.

By the end of this chapter
  • Distinguish resource identity from request identity
  • Define validation and ownership
  • Explain what a timeout does and does not reveal

The endpoint is a contract with its caller

An API contract describes more than a URL and JSON shape. It states how the caller is identified, what fields are accepted, whether missing and null mean different things, what limits apply, which errors are retriable, and what a successful response guarantees. Keep input and output bounded so that an otherwise valid request cannot consume unlimited memory or work.

Resource identity identifies a thing, such as a completion record or short link. A request identity can identify one intended operation across retries. Two requests that use the same idempotency key but ask for different effects should not silently become equivalent. Document the scope and lifetime of the key and the response on a conflicting reuse.

Illustrative progress API contract, not an executable HTTP server text
PUT /v1/me/completions/python-loops
Authorization: authenticated session
Content-Type: application/json

{"completed": true}

Success: committed current completion state
Invalid lesson: controlled client error
Other learner identity in body: never trusted as ownership
Repeated identical intent: same intended completion effect

Go deeper: [1] HTTP semantics RFC 9110 · [24] OWASP API Security Project

Errors communicate what the caller can do next

A timeout says the caller did not receive a result within its waiting deadline. It does not say the server performed no work. A committed response can be lost in transit. Retrying a non-repeat-safe operation without a contract can create duplicate effects, while refusing every retry can leave useful operations permanently uncertain.

Use status and error categories consistently, but do not make the client guess important business state from a generic message. Distinguish invalid input, unauthorized access, conflict with current state, temporary overload, and unexpected server failure. Avoid revealing private object existence to a caller who has no right to know it. Observability can retain an approved internal reason without exposing secrets or implementation details in the public response.

Worked example · A lost creation response

  1. A client requests a short link with a stable request ID. The server stores the link and commits.
  2. The response disappears. The client retries using the same ID and same destination.
  3. The service recognizes the prior intent and returns the existing link rather than creating a second independent result.

Result: The stable intent and its durable result must be coordinated, not merely remembered in a worker’s temporary dictionary.

Go deeper: [1] HTTP semantics RFC 9110 · [13] Making retries safe with idempotent APIs

Keep these ideas

  • Specify repeated and conflicting requests as part of the API.
  • A timeout creates uncertainty; it does not prove absence of effects.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

3.1 · Practice task

Why should an endpoint prefer a verified account identity over a body field named learner_id?

Hint: The caller controls request contents.

Read the worked solution

3.2 · Practice task

A client reuses request ID R with a different destination URL. What should a repeat-safe creation API do?

Hint: Same key does not necessarily mean same intent.

Read the worked solution

Chapter 04

Model data and protect the rules in the database

Use keys constraints transactions and indexes to make correctness less dependent on perfect timing.

By the end of this chapter
  • Choose a useful key and uniqueness rule
  • Recognize a read-modify-write race
  • Explain what an index changes

A schema expresses relationships and invariants

For a short-link service, separate the public alias from the destination URL, owner, and expiry time. The alias must be unique. A completion table instead has a useful compound key of learner and lesson. These choices express which facts can exist once and which relationships are allowed. State the meaning of a missing or expired record before designing its storage representation.

A transaction groups changes under the database’s documented guarantees. It does not magically serialize every part of the application, especially external network calls or code outside the transaction. Read the actual isolation level and retry requirements. A “check that no row exists, then insert” sequence can race unless a database constraint or appropriate concurrency control resolves the conflict.

An illustrative short-link table with an explicit key SQL
CREATE TABLE links (
    alias TEXT PRIMARY KEY,
    destination TEXT NOT NULL,
    owner_id TEXT NOT NULL,
    expires_at INTEGER NOT NULL
);

Worked example · Two requests choose the same alias

  1. Both requests observe that the alias is absent. Their application checks are individually true at that moment.
  2. Both try to insert. The unique key permits only the state allowed by the schema.
  3. Handle the conflict by choosing a new alias or returning the documented conflict response, rather than treating it as an impossible server crash.

Result: The database resolves the invariant at the point where concurrent effects meet.

Go deeper: [9] PostgreSQL 18 constraints · [8] PostgreSQL 18 transaction isolation

Indexes trade work in one place for work in another

An index is an additional access structure that can help the database locate rows for suitable queries. It consumes storage and needs maintenance when indexed data changes. A query about aliases and a query listing one owner’s recently created links may need different access paths. Start with real access patterns and inspect query plans and measured latency instead of indexing every column.

Keep hot transactions small and avoid holding locks while waiting on unrelated remote work. If a transaction reads a value, computes a new one, and writes it back, another transaction can interfere under some isolation choices. Prefer an appropriate atomic update, constraint, or locking strategy and test concurrent clients. The exact behaviour depends on the selected engine, schema, and transaction mode.

Go deeper: [10] PostgreSQL 18 indexes introduction · [11] PostgreSQL 18 explicit locking

Keep these ideas

  • Use constraints where concurrent effects meet.
  • Transactions and indexes have documented scope and costs.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

Two workers read counter=4, each computes 5, and each writes 5. What happened, and how could the design change?

Hint: Distinguish two increments from two assignments.

Read the worked solution

4.2 · Practice task

An index improves alias lookup but writes become slower. Is that automatically a database defect?

Hint: An extra access structure must be maintained.

Read the worked solution

Chapter 05

Build a request path with bounded concurrency

Explain the jobs of routing load balancing workers pools and deadlines.

By the end of this chapter
  • Draw the critical path
  • Keep queues and pools bounded
  • Recognize a slow dependency before scaling the wrong layer

Every component needs an explicit job

Begin with one application process and one database. Add a load balancer when you need traffic distribution, health-aware routing, or an operational boundary that justifies it. Add more application instances when they can independently serve requests and their shared dependencies can support the resulting demand. Moving from one instance to ten does not multiply a saturated database’s write capacity by ten.

A useful request-path diagram shows where authentication occurs, where state becomes durable, and which response depends on which work. Include hidden queues: connection pools, thread pools, operating-system accept queues, and database lock waits. “The application spent only 5 ms computing” can be true while a learner waits several seconds in a pool.

The path and the waiting roomsA load-balanced request can wait at admission, in an application pool, and at a database. Bound and measure those waits so a slow dependency does not consume every caller resource.AdmissionApply request limits and reject work that cannot be served usefully.RoutingChoose an appropriate healthy target for the request.Application poolRun bounded work and acquire downstream capacity deliberately.DatabaseExecute the required operation under its concurrency contract.ResponseReturn the documented result within the remaining deadline.
The path and the waiting rooms. A load-balanced request can wait at admission, in an application pool, and at a database. Bound and measure those waits so a slow dependency does not consume every caller resource.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [1] HTTP semantics RFC 9110 · [5] Handling overload

A deadline coordinates the whole operation

A timeout usually bounds a particular wait. A deadline describes when the whole operation stops being useful. If the total budget is one second and the first stage consumes 800 ms, giving the next stage a fresh one-second timeout can exceed the caller’s original need. Propagate remaining time or otherwise coordinate stage budgets.

Bounded pools protect a finite resource but create another queueing decision. Too small a pool can underuse capacity; too large a pool can overload the dependency and increase memory pressure. Measure wait time and service time separately. When demand exceeds useful capacity, a controlled rejection with an appropriate retry contract can preserve service better than accepting unlimited work that will miss every deadline.

A teaching admission bound; not a complete server Python
capacity = 3
active = 2
incoming = 4
accepted = min(incoming, max(0, capacity - active))
rejected = incoming - accepted
print(accepted, rejected)
Expected result
1 3

Worked example · The wrong scaling response

  1. Database queries slow down. The application opens more concurrent connections to avoid waiting.
  2. The database now competes over more work and may become even slower.
  3. Inspect the query, locks, and downstream capacity. Bound admission and concurrency while testing a targeted repair.

Result: Scale the limiting resource or reduce required work; do not simply multiply pressure.

Go deeper: [14] Timeouts retries and backoff with jitter · [16] Using load shedding to avoid overload

Keep these ideas

  • Make hidden waits visible in the request path.
  • Coordinate deadlines and bound downstream pressure.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

A 1,000 ms request budget has 750 ms already consumed. Why is a new 1,000 ms downstream timeout misleading?

Hint: Compare stage timeout with remaining end-to-end time.

Read the worked solution

5.2 · Practice task

A connection pool is full and requests wait. Name evidence needed before increasing its size.

Hint: Ask whether the dependency is slow or the pool is simply undersized.

Read the worked solution

Chapter 06

Use caches without losing the meaning of the data

Design keys freshness invalidation and overload behaviour together.

By the end of this chapter
  • Identify the authoritative copy
  • Choose a cache key from response variation
  • Handle miss storms and stale data deliberately

A cache is a performance tool with a consistency story

A cache keeps a reusable result so that a later request can avoid some work. First name the authoritative source and the maximum staleness acceptable for the operation. An old public course description may be tolerable for a short period; an old authorization decision or an available seat count may not be. “Cache everything” hides important differences in correctness needs.

The cache key must represent the inputs that change the reusable result. Language, format, relevant parameters, and an appropriate privacy boundary may matter. Do not reuse a personalized response for an unrelated caller. Conversely, including meaningless request variation in every key fragments the cache and reduces useful reuse. Test two requests that should share a result and two that must not.

A simple cache-aside readThe application checks a cache first, loads from the authoritative store on a miss, then stores a reusable result under a deliberate key. Write and invalidation behaviour need a separate contract.RequestDetermine the permitted data and the correct cache key.Cache lookupReturn a suitably fresh cached result when allowed.Authoritative read on missLoad the source record and handle absence or failure.Cache fillStore the result with the chosen freshness and size limits.
A simple cache-aside read. The application checks a cache first, loads from the authoritative store on a miss, then stores a reusable result under a deliberate key. Write and invalidation behaviour need a separate contract.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [15] Caching challenges and strategies · [2] HTTP caching RFC 9111

Misses and expiry can become a load event

If many popular entries expire together, a large group of requests can hit the backing store at once. A single-flight or coalescing approach lets suitable concurrent requests share one refresh. Expiry jitter can spread refresh timing. Serving an older value while refreshing can help when the contract permits it, but stale data is a product decision, not an invisible optimization.

A cache failure should have a defined behaviour. Falling back to the database is reasonable only if that database can tolerate the resulting demand. A cold start, cache eviction wave, or invalidation bug can produce the same pressure. Test both a warm cache and a cold cache, and bound refresh work. Do not claim a design scales based solely on a high hit ratio observed after a careful warm-up.

Trace hit and miss behaviour locally Python
source = {"course:python": "revision-3"}
cache = {}
source_reads = 0
def read(key):
    global source_reads
    if key not in cache:
        source_reads += 1
        cache[key] = source[key]
    return cache[key]
assert read("course:python") == "revision-3"
assert read("course:python") == "revision-3"
print(source_reads)
Expected result
1

Worked example · Change the source and predict the read

  1. After the sample fills the cache, change the source value to revision-4.
  2. Without expiry or invalidation, another read still returns revision-3.
  3. Write a deliberate refresh policy and test what a caller sees immediately after an update.

Result: The small example exposes why faster reads need an explicit freshness contract.

Go deeper: [15] Caching challenges and strategies · [16] Using load shedding to avoid overload

Keep these ideas

  • Choose staleness and privacy rules before adding a cache.
  • Design for a cold cache and coordinated expiry.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

A shared cache uses only /me/progress as its key. Explain the privacy risk and a safer direction.

Hint: Different users can generate the same URL.

Read the worked solution

6.2 · Practice task

Ten thousand requests arrive just after a popular entry expires. Why can adding cache capacity alone fail to fix this?

Hint: The immediate problem is coordinated refresh work.

Read the worked solution

Chapter 07

Queues events and the outbox problem

Move work through time while preserving a meaningful durable result.

By the end of this chapter
  • Explain at-least-once delivery
  • Choose an acknowledgement boundary
  • Recognize a dual-write inconsistency

A queue introduces useful separation and new states

A queue can separate request arrival from processing speed and let a worker retry independent work. It also adds states that the product must explain: accepted but waiting, running, completed, failed, and perhaps awaiting manual review. A successful enqueue is not the same promise as a completed business operation. Tell the caller which event has actually happened.

Under at-least-once delivery, a consumer must tolerate seeing a message again. The worker may commit its effect and then fail before acknowledging. Keep the repeat-safe business effect or durable duplicate check at the correct transactional boundary. A delivery count alone does not reveal whether earlier work committed.

Go deeper: [18] Standard queue delivery semantics · [17] Transactional outbox pattern

The database and message broker are different commit points

Suppose an API stores an order and then publishes an email event. It can crash after the database commit but before publishing, leaving a stored order with no email event. Reversing the steps creates a different failure: the message can be published while the order never commits. Two successful calls in a test do not make these independent writes atomic.

A transactional outbox records the business change and an outgoing event in the same database transaction. A separate relay publishes retained outbox events and marks its progress. The relay can publish twice after an uncertain outcome, so consumers still need the appropriate duplicate handling. The pattern changes the recoverable state; it is not an excuse to declare every downstream effect exactly once.

A durable outbox boundaryThe transaction commits the business row and outgoing event together. A relay may publish repeatedly, so the consumer applies a repeat-safe effect and acknowledges after the required work.Database transactionStore business state and outbox record together.Outbox relayRead pending records and publish under a retry contract.Message deliveryA duplicate or delayed event may reach the consumer.Consumer effectDeduplicate or apply an idempotent operation at its durable boundary.
A durable outbox boundary. The transaction commits the business row and outgoing event together. A relay may publish repeatedly, so the consumer applies a repeat-safe effect and acknowledges after the required work.Scroll horizontally to read the full diagram on a small screen.

Worked example · Crash after publication

  1. The relay publishes event E, then crashes before marking E sent.
  2. After restart it finds E pending and publishes it again.
  3. A consumer that increments a counter blindly can double count. A consumer keyed by logical event intent can recognize the repeat.

Result: The outbox protects one atomic boundary; the consumer has another responsibility.

Go deeper: [17] Transactional outbox pattern · [13] Making retries safe with idempotent APIs

Keep these ideas

  • State exactly what “accepted” means.
  • Treat every commit boundary and acknowledgement gap as a separate failure case.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

Why should a worker not acknowledge a message before the required durable effect exists?

Hint: Crash immediately after acknowledging.

Read the worked solution

7.2 · Practice task

An outbox relay retries after a timeout. Can you now omit consumer duplicate handling?

Hint: The relay may not know whether publication succeeded.

Read the worked solution

Chapter 08

Replication consistency and what a successful write means

Describe which copy can answer which question under ordinary delay and failure.

By the end of this chapter
  • Distinguish replica lag from data loss
  • State a read-after-write requirement
  • Understand the purpose of quorum and consensus at a high level

Several copies do not automatically tell one story

Replication maintains copies according to a protocol. A leader-based design often accepts writes at a designated leader and sends changes to followers. With asynchronous replication, a follower can lag. Reading a follower immediately after a successful write may return an older value even though no storage device is broken. Decide whether the user operation permits that result.

Consistency is about allowed observations of operations, not whether the data looks tidy. A service can provide stronger semantics for one operation and weaker semantics for another. For progress saving, immediate read-your-write behaviour may matter. For an aggregate popularity report, a delayed view may be acceptable. Name the property and scope rather than declaring the entire product simply “consistent.”

A write and a lagging readA committed write at the leader may not yet be visible on an asynchronous follower. Routing the immediate dependent read requires a deliberate consistency decision.WriterRequests an update and receives the chosen commit acknowledgement.LeaderOrders or accepts the authoritative write according to the protocol.FollowerApplies replicated changes after some delay.ReaderMay observe older state if routed to a follower before catch-up.
A write and a lagging read. A committed write at the leader may not yet be visible on an asynchronous follower. Routing the immediate dependent read requires a deliberate consistency decision.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [8] PostgreSQL 18 transaction isolation · [7] Data integrity

Quorums are part of a protocol

A quorum is a sufficiently sized participating set under a particular protocol and failure model. Intersecting read and write sets can be an important ingredient, but a formula such as R + W > N is not by itself a complete proof of linearizability. Version selection, concurrent writes, membership changes, failure assumptions, and the actual implementation matter.

Consensus protocols help nodes agree on an ordered sequence under their stated model. They do not remove latency or make progress possible through every network split. Learn the purpose first: prevent incompatible decisions while tolerating specified failures. Use the protocol’s paper and tested implementations rather than inventing a cluster algorithm from a diagram in an introductory guide.

Worked example · Three voting members

  1. Assume a protocol requires a majority of three voting members. Two can communicate on one side of a network split, while one is isolated.
  2. The two-member side has a majority under that assumption. The one-member side cannot independently form another majority.
  3. This observation alone does not describe every read mode, timeout, or membership rule of a real system.

Result: A majority argument explains one safety ingredient; the full protocol defines the service behaviour.

Go deeper: [19] Raft paper and learning resources · [20] Time Clocks and the Ordering of Events in a Distributed System

Keep these ideas

  • State which observations an operation permits.
  • Read the full protocol before making guarantees from quorum arithmetic.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

A learner saves completion, then reads from a lagging replica and sees “incomplete.” Is this necessarily a failed write?

Hint: Separate the write result from the selected read source.

Read the worked solution

8.2 · Practice task

With five voting members and a majority requirement, how many form a majority? What does the count alone fail to prove?

Hint: A majority is more than half.

Read the worked solution

Chapter 09

Partition data without hiding the difficult key

Use partition boundaries to distribute load while keeping ownership and change understandable.

By the end of this chapter
  • Compare hash and range partitioning
  • Identify hot keys and cross-partition work
  • Plan a recoverable data move

Choose a partition key from the access pattern

Partitioning divides a dataset across ownership boundaries. Hash partitioning can spread many keys across partitions; range partitioning keeps neighbouring keys together and can help range queries. Neither makes an extremely popular single key disappear. A celebrity course, global counter, or timestamp-heavy write pattern can concentrate traffic despite a large total partition count.

For learner progress, a learner-based partition key can keep one learner’s records together and make common reads simple. It can also make an unusually large account or aggregate cross-learner query inconvenient. Write the operations before selecting a key and identify the transactions that cross the boundary. Cross-partition coordination introduces complexity that a per-partition diagram can conceal.

A deterministic teaching partition function Python
import hashlib
def partition(key, count):
    digest = hashlib.sha256(key.encode("utf-8")).digest()
    return int.from_bytes(digest[:8], "big") % count
for key in ["alice", "bob", "alice"]:
    print(partition(key, 4))
Expected result
3
2
3
Partitioning choicesHash partitioning aims to spread key ownership, while range partitioning groups ordered keys. A hot logical key still needs a workload-specific answer.Hash by learnerUseful for many independentlearner lookups; ranges arenot naturally grouped.Range by keyUseful for ordered scans;skewed ranges can concentratetraffic.Hot-key mitigationCache, split compatible work,or redesign the operationwhile preserving its meaning.
Partitioning choices. Hash partitioning aims to spread key ownership, while range partitioning groups ordered keys. A hot logical key still needs a workload-specific answer.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [21] Dynamo design paper · [22] DynamoDB core data components

Moving ownership needs a transition protocol

Changing a simple modulo partition count can move many keys, so ownership changes are not merely a configuration edit. A migration must explain where new reads and writes go while data is copied, how conflicting versions are resolved, how completeness is checked, and how to return safely if the move fails. Consistent hashing can reduce movement under particular changes, but it does not replace this operational protocol.

Begin a move with an inventory and verification plan. Copy a bounded range, compare expected records or checksums under a suitable consistency method, and gradually change routing. Record progress durably so a restarted migration does not guess what finished. A checksum can show that selected bytes match; it does not by itself prove the application preserved every business invariant or that the sample was complete.

Worked example · A single hot counter

  1. One course receives nearly all update traffic to a single exact counter key. More unrelated partitions do not split that one key.
  2. Ask whether the product really needs an exact synchronous total on every request.
  3. If a delayed aggregate is acceptable, independently keyed events and a controlled aggregation path may spread work. Exactness, ordering, and reconciliation still need a contract.

Result: A useful design changes the operation deliberately instead of assuming partition count fixes all skew.

Go deeper: [21] Dynamo design paper · [7] Data integrity

Keep these ideas

  • Partitioning distributes chosen ownership, not every possible workload.
  • Treat repartitioning as a recoverable data operation.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

What does partitioning progress by learner help, and what query might become harder?

Hint: Compare per-learner work with global aggregation.

Read the worked solution

9.2 · Practice task

Why is “copy rows, then change the router” an incomplete migration plan while writes continue?

Hint: A row can change after it was copied.

Read the worked solution

Chapter 10

Design for uncertainty partitions and overload

Preserve useful behaviour when dependencies slow down or communication stops.

By the end of this chapter
  • Separate safety from liveness
  • Use CAP only in its stated failure context
  • Bound retries and shed unusable work

Failure is often partial and ambiguous

A remote call can fail for the caller while the receiver remains healthy. A reply can be lost after the effect commits. A slow dependency can look like a dead one from a deadline-limited client. Design each operation around these uncertain outcomes instead of assuming a clean “everything succeeded” or “nothing happened” switch.

Safety describes preventing bad states or observations, while liveness describes making progress under the stated assumptions. A protocol may refuse a write during a split to preserve its safety property. That refusal can be the designed behaviour rather than an implementation defect. Explain which user operation is unavailable and why, and provide a recovery or retry path consistent with the contract.

Go deeper: [14] Timeouts retries and backoff with jitter · [19] Raft paper and learning resources

Do not amplify a struggling dependency

The CAP result concerns the inability to guarantee both linearizable consistency and the theorem’s availability property during the relevant network partition model. It is not a blanket rule that a healthy database can have only two attractive features. When evaluating a design, state the partition scenario, operation, and permitted response.

For ordinary overload, bound outstanding work and retries. Exponential backoff can reduce synchronized pressure, and jitter helps avoid callers retrying together. Limit attempts and respect the total useful deadline. Admission control and load shedding can reject work early rather than allowing every request to occupy resources until it times out. Test recovery too: a huge retry wave can prevent a repaired dependency from becoming healthy.

An illustrative bounded exponential delay schedule Python
base_seconds = 0.1
cap_seconds = 1.0
attempts = 5
for attempt in range(attempts):
    maximum = min(cap_seconds, base_seconds * 2 ** attempt)
    print(round(maximum, 2))
# A real full-jitter policy samples a delay in [0, maximum].
Expected result
0.1
0.2
0.4
0.8
1.0

Worked example · Retry multiplication

  1. A request crosses three layers and each layer allows three total attempts.
  2. In a worst-case nested retry pattern, downstream calls can multiply to 3 × 3 × 3 = 27 for one top-level request.
  3. Choose the retry owner and budget deliberately, and distinguish total attempts from additional retries in configuration.

Result: Retries are workload. A policy that ignores multiplication can worsen the outage it tries to hide.

Go deeper: [16] Using load shedding to avoid overload · [5] Handling overload · [23] Brewers conjecture and feasibility of consistent available partition-tolerant services

Keep these ideas

  • Uncertainty requires an operation contract.
  • Preserve safety, bound pressure, and test the recovery path.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

A payment-style request times out. Why are both “definitely failed” and “definitely succeeded” unjustified without more evidence?

Hint: The response path can fail independently of commit.

Read the worked solution

10.2 · Practice task

Four layers each allow two total attempts. What worst-case multiplication should you consider, and what would you change?

Hint: Count nested attempts rather than only one layer’s setting.

Read the worked solution

Chapter 11

Make authorization and abuse resistance part of the design

Treat identity ownership input limits and sensitive data as first-class architecture decisions.

By the end of this chapter
  • Separate authentication from object authorization
  • Define trustworthy and untrusted fields
  • Choose a bounded rate-limit model

Follow an actor across the trust boundary

Authentication answers who the caller is under the chosen identity mechanism. Authorization answers whether that caller may perform this operation on this resource. A short-link creator may own one link but not every link with a predictable identifier. Check ownership on reads, updates, deletion, export, and administrative paths. A successful login is not a universal permission.

Mark untrusted inputs on the architecture diagram: URL destinations, uploaded files, query parameters, identifiers, and even headers forwarded by another component. Validate syntax and relevant semantics at the boundary that owns the rule. If a backend fetches a user-provided URL, a simple scheme check alone does not prevent server-side request forgery; internal destinations, DNS changes, redirects, and network access need a fuller design. The local capstone deliberately does not fetch destinations.

Worked example · A short link as a boundary

  1. The public redirect endpoint may resolve a permitted public alias without revealing the owner’s account information.
  2. The owner-management endpoint requires authentication and verifies ownership before changing the destination.
  3. A predictable alias must not become permission to edit or list private account records.

Result: Separate the public lookup contract from the private management contract.

Go deeper: [24] OWASP API Security Project · [1] HTTP semantics RFC 9110

Limits protect useful work

Bound request size, destination length, expansion work, and per-actor activity. A limit should reflect the resource or abuse case you intend to control. A token bucket allows a bounded burst while refilling at a chosen rate. A fixed window can be simpler but permits boundary effects. Distributed enforcement adds coordination and consistency choices; it is not solved merely by naming Redis.

Minimize sensitive data in logs and retention. A trace that captures an entire authorization header creates another secret store. Choose identifiers and context that support diagnosis without copying passwords, tokens, or unnecessary personal information. Decide what happens when the limiting dependency fails: deny, degrade, or permit under a fallback bound according to the risk of the operation.

A deterministic token-bucket trace with caller-supplied time Python
tokens, capacity, refill_per_second = 3.0, 3.0, 1.0
last = 0.0
for now in [0.0, 0.0, 0.0, 0.0, 2.0]:
    tokens = min(capacity, tokens + (now - last) * refill_per_second)
    last = now
    allowed = tokens >= 1
    if allowed:
        tokens -= 1
    print(allowed)
Expected result
True
True
True
False
True

Go deeper: [16] Using load shedding to avoid overload · [24] OWASP API Security Project

Keep these ideas

  • Enforce ownership at the operation that uses the data.
  • Bound resource use and keep secrets out of diagnostic paths.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

Why does allowing only https:// destinations not make a backend URL-fetch feature safe by itself?

Hint: A valid scheme can still point somewhere the service should not contact.

Read the worked solution

11.2 · Practice task

A token bucket starts with five tokens and refills two per second. After five immediate accepted calls, how many tokens can be available after one second, assuming no other calls?

Hint: Apply refill and the capacity cap.

Read the worked solution

Chapter 12

Know whether the design works for users

Connect service objectives observations and failure experiments.

By the end of this chapter
  • Define a useful success indicator
  • Choose logs metrics and traces deliberately
  • Test a fault and verify recovery

Measure the promise rather than the machine alone

A service-level indicator measures an outcome relevant to an operation: for example, the fraction of valid redirect lookups returning the intended result within a target duration. A service-level objective chooses an acceptable target over a stated window. A service-level agreement is a different external commitment and may have its own definitions. Keep these terms separate.

Measure at a boundary that reflects the user experience. A process can be healthy while every lookup fails authorization or returns an expired destination. Combine outcome rate and latency with diagnostic information about causes. Use logs for selected event context, metrics for bounded aggregate measurements, and traces to connect stages. A request identifier helps relate evidence without copying the whole sensitive payload.

Measure diagnose verifyA user outcome identifies the problem. Diagnostic signals narrow the failing stage. A repair is complete only after the outcome and recovery behaviour are checked.Outcome indicatorValid lookups or saves meet the stated result and timing target.Diagnostic evidenceCorrelated logs, metrics, and traces narrow the cause.Controlled changeApply a bounded repair with a clear success condition.VerificationCheck the user operation and the absence of new damage.
Measure diagnose verify. A user outcome identifies the problem. Diagnostic signals narrow the failing stage. A repair is complete only after the outcome and recovery behaviour are checked.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [3] Service level objectives · [4] Monitoring distributed systems

Test more than the happy path

Use unit tests for local rules, integration tests for real component contracts, and controlled failure tests for assumptions about timing and recovery. A mock database is useful for some code paths but cannot establish the actual engine’s isolation or lock behaviour. A local single-process model is useful for invariants but cannot prove a distributed consensus implementation.

Create an experiment table: fault, expected observation, required invariant, recovery action, and evidence. Simulate a lost response, slow dependency, duplicate message, stale read, full pool, and a process restart. Test recovery after removing the fault. Otherwise a design may pass the outage phase yet remain stuck because of retry storms, stale connections, or unprocessed backlog.

Worked example · A lost-response experiment

  1. Commit a creation result, then prevent the client from receiving the response in a controlled test harness.
  2. Retry with the same operation identity and verify that no second logical result is created.
  3. Restore normal communication and confirm that the stored result can be read and diagnosed through approved identifiers.

Result: The test checks both repeat safety and the ability to resolve uncertainty, not just whether an exception was raised.

A simple success-fraction calculation with explicit classification Python
outcomes = ["ok", "ok", "timeout", "invalid-input", "ok"]
valid = [x for x in outcomes if x != "invalid-input"]
successful = sum(x == "ok" for x in valid)
print(successful, len(valid), successful / len(valid))
Expected result
3 4 0.75

Go deeper: [7] Data integrity · [6] Canarying releases

Keep these ideas

  • Measure the user operation and diagnose its stages.
  • A failure test needs an invariant and a recovery check.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Why can a server uptime chart miss a broken redirect service?

Hint: A running process can return the wrong outcome.

Read the worked solution

12.2 · Practice task

Write a test row for a consumer crash after commit but before acknowledgement.

Hint: Name the invariant and the observation after replay.

Read the worked solution

Chapter 13

Evolve the design without losing the ability to recover

Review change compatibility data restoration and cost as architecture concerns.

By the end of this chapter
  • Plan a mixed-version rollout
  • Distinguish RPO from RTO
  • Write a decision record with alternatives

A release changes a running system

A diagram usually shows one version of each component. A deployment can temporarily run several versions, old clients, new workers, and data written under different assumptions. Test that transition explicitly. Adding a nullable field and later making it required can be safer than immediately deleting the representation used by current readers, depending on the application contract.

A canary release exposes a bounded amount of suitable traffic to a change and compares meaningful outcomes before expansion. Its usefulness depends on representative exposure, observability, and stop conditions. A tiny canary that never sees the failing workload proves little. Rollback must include data compatibility; restoring an old binary does not make it understand an incompatible new record.

A compatibility-first migrationExpand support, migrate and verify data, move readers and writers deliberately, then remove old support only when it is safe to do so.ExpandIntroduce a representation that old required readers can still tolerate.MigrateTransform bounded data with resumable progress and checks.SwitchMove traffic and behaviour while observing actual outcomes.ContractRemove obsolete support after dependencies and recovery needs are understood.
A compatibility-first migration. Expand support, migrate and verify data, move readers and writers deliberately, then remove old support only when it is safe to do so.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [6] Canarying releases · [7] Data integrity

Recovery is a timed and tested procedure

The recovery point objective describes the maximum acceptable interval of potential data loss, such as fifteen minutes of recent updates. The recovery time objective describes the intended time to restore the required service. They answer different questions. A backup every fifteen minutes does not itself prove either objective: backup completion, retention, restore speed, and validation still matter.

Write an architecture decision record when a tradeoff matters. State the problem, constraints, chosen option, alternatives, reasons, and consequences. Include operational burden and cost dimensions without pretending that a hypothetical worksheet is a current price quote. A simple design operated well can be a better match than a sophisticated one the team cannot safely change. Revisit the record when its assumptions change rather than defending it as a permanent identity.

Worked example · A recovery exercise

  1. Assume a teaching objective permits losing at most ten minutes of recent events and aims to restore service within one hour.
  2. Restore a known backup plus any retained change history into a separate environment and time the full process.
  3. Validate important records, access controls, and user operations before declaring the exercise successful.

Result: The measured restoration procedure is evidence; a file named backup.zip is not.

Go deeper: [25] Define recovery objectives for downtime and data loss · [7] Data integrity

Keep these ideas

  • Design for the transition between versions.
  • Recovery and simplicity must be justified with concrete procedures and evidence.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

Explain the difference between an RPO of five minutes and an RTO of thirty minutes in a hypothetical service.

Hint: One concerns lost recent history; the other concerns restoration duration.

Read the worked solution

13.2 · Practice task

Write the main consequences of starting a small service with one relational database instead of immediately sharding it.

Hint: Include the benefits and the point where assumptions must be revisited.

Read the worked solution

Chapter 14

Capstone Design and test a short-link service

Bring the contracts data rules and failure reasoning together in a small executable model.

By the end of this chapter
  • Implement a repeat-safe creation operation
  • Test expiry and conflicting request intent
  • Explain the path from a local model to a deployed service

State the useful promise

The local capstone creates a named alias for a destination URL and resolves it before an explicit expiry time. A stable request ID identifies one intended creation. Repeating the same request returns the same alias, while reusing the ID for a different intent is rejected. Alias uniqueness is a database rule, not a hope that callers choose different strings.

The model uses a single in-memory SQLite connection and an explicitly supplied time value. This makes expiry tests deterministic and avoids real-time sleeps. It neither hosts an HTTP server nor follows destination URLs, and it creates no cloud resource. Public destinations use example.org, a documentation domain. In production, ownership checks, abuse handling, real clocks, persistence, concurrency, and operational recovery need additional implementation.

Capstone responsibilitiesCreation validates and stores a repeat-safe intent. Resolution reads an alias and applies expiry. A future HTTP layer must supply real authentication and appropriate response headers without changing these rules.Create requestBound inputs and identify one intended operation.Transactional storeEnforce request identity and unique alias constraints.Resolve requestLook up the alias and compare the supplied time with expiry.API boundaryTranslate domain outcomes into authorized HTTP behaviour and controlled errors.
Capstone responsibilities. Creation validates and stores a repeat-safe intent. Resolution reads an alias and applies expiry. A future HTTP layer must supply real authentication and appropriate response headers without changing these rules.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [1] HTTP semantics RFC 9110 · [12] Python 3.11 sqlite3 reference · [13] Making retries safe with idempotent APIs

Run the complete local model

Save the code as short_links.py and run it with Python 3. It prints one success line only after the included assertions pass. Trace the first insert, the repeated request, the conflict, and the boundary where now equals expires_at. The tests choose that exact equality to make the expiration contract unambiguous.

The boundary checks are part of the model, not a claim that parsing a URL makes it safe to fetch. Request IDs are strings of one through 128 characters. Aliases use one through 32 ASCII letters, digits, underscores, or hyphens. Destinations are bounded HTTP(S) strings without whitespace or embedded credentials. Time values are nonnegative integers within SQLite’s signed 64-bit range; Python booleans are rejected even though bool is an int subclass. The same time scale must be used for expiry and now.

The with block coordinates the successful database changes according to this connection’s transaction behaviour. A unique-alias conflict raises a database integrity error; a real API should translate that into its documented outcome rather than expose an engine traceback. This local program demonstrates a correctness boundary, not a proof about concurrent application instances or replicated databases.

Complete short_links.py model and checks Python
import re
import sqlite3
from urllib.parse import urlsplit

MAX_TIME = 2**63 - 1  # Fits the SQLite INTEGER used by this model.

def valid_time(value):
    return type(value) is int and 0 <= value <= MAX_TIME

class ShortLinks:
    def __init__(self):
        self.db = sqlite3.connect(":memory:")
        self.db.execute("""CREATE TABLE links (
            request_id TEXT PRIMARY KEY,
            alias TEXT UNIQUE NOT NULL,
            destination TEXT NOT NULL,
            expires_at INTEGER NOT NULL
        )""")

    def create(self, request_id, alias, destination, expires_at):
        if not isinstance(request_id, str) or not 1 <= len(request_id) <= 128:
            raise ValueError("request ID must be 1 through 128 characters")
        if (not isinstance(alias, str) or
                re.fullmatch(r"[A-Za-z0-9_-]{1,32}", alias) is None):
            raise ValueError("alias must be 1 through 32 ASCII URL-key characters")
        if (not isinstance(destination, str) or
                not 1 <= len(destination) <= 2048 or
                any(char.isspace() or ord(char) < 32 or ord(char) == 127
                    for char in destination)):
            raise ValueError("destination must be a bounded URL without whitespace")
        if not valid_time(expires_at):
            raise ValueError("expiry must be a nonnegative bounded integer")
        parsed = urlsplit(destination)
        if (parsed.scheme not in {"http", "https"} or not parsed.hostname or
                parsed.username is not None or parsed.password is not None):
            raise ValueError("http(s) destination without embedded credentials required")
        _ = parsed.port  # Reject a malformed or out-of-range explicit port.
        with self.db:
            row = self.db.execute(
                "SELECT alias, destination, expires_at FROM links WHERE request_id=?",
                (request_id,)
            ).fetchone()
            intent = (alias, destination, expires_at)
            if row is not None:
                if row != intent:
                    raise ValueError("request ID conflict")
                return row[0]
            self.db.execute("INSERT INTO links VALUES (?, ?, ?, ?)",
                            (request_id, *intent))
        return alias

    def resolve(self, alias, now):
        if (not isinstance(alias, str) or
                re.fullmatch(r"[A-Za-z0-9_-]{1,32}", alias) is None):
            raise ValueError("invalid alias")
        if not valid_time(now):
            raise ValueError("now must be a nonnegative bounded integer")
        row = self.db.execute(
            "SELECT destination, expires_at FROM links WHERE alias=?", (alias,)
        ).fetchone()
        if row is None or now >= row[1]:
            return None
        return row[0]

service = ShortLinks()
args = ("request-1", "learn", "https://example.org/python", 200)
assert service.create(*args) == "learn"
assert service.create(*args) == "learn"
assert service.resolve("learn", 199) == "https://example.org/python"
assert service.resolve("learn", 200) is None
assert service.resolve("missing", 100) is None
try:
    service.create("request-1", "other", "https://example.org/java", 200)
except ValueError as error:
    assert str(error) == "request ID conflict"
else:
    raise AssertionError("conflicting intent accepted")

# Rejected boundary inputs must not create records.
for bad in [
    (None, "learn", "https://example.org/python", 200),
    ("x" * 129, "learn", "https://example.org/python", 200),
    ("r2", "bad alias", "https://example.org/python", 200),
    ("r2", "x" * 33, "https://example.org/python", 200),
    ("r2", "valid", None, 200),
    ("r2", "valid", "https://example.org/" + "x" * 2048, 200),
    ("r2", "valid", "javascript:alert(1)", 200),
    ("r2", "valid", "https://example.org/\nsecret", 200),
    ("r2", "valid", "https://example.org/python", True),
    ("r2", "valid", "https://example.org/python", 1.5),
    ("r2", "valid", "https://example.org/python", MAX_TIME + 1),
]:
    try:
        service.create(*bad)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid input accepted")
try:
    service.create("request-2", "learn", "https://example.org/java", 200)
except sqlite3.IntegrityError:
    pass
else:
    raise AssertionError("duplicate alias accepted")
try:
    service.resolve("learn", True)
except ValueError:
    pass
else:
    raise AssertionError("boolean time accepted")
assert service.db.execute("SELECT COUNT(*) FROM links").fetchone()[0] == 1
assert service.resolve("learn", 199) == "https://example.org/python"
service.db.close()
print("repeat, expiry, absence, and intent checks passed")
Expected result
repeat, expiry, absence, and intent checks passed

Go deeper: [12] Python 3.11 sqlite3 reference · [9] PostgreSQL 18 constraints

Review the design as a whole

Now draw a deployment version with an entry point, application, database, and optional public cache. Begin with a simple path and explain why each additional component exists. A cache for redirects must respect expiry and updates; a cached entry that outlives the alias can violate the lookup contract. A background cleanup job can reclaim expired records, but correctness should not depend solely on how soon that job runs.

Add an experiment plan: lose a creation response, restart a process, try two concurrent alias claims, fill a connection pool, and make the database temporarily unavailable. Explain the expected client result and preserved invariant for each. A complete first-pass design combines the contract, model, estimates, source references, tests, failure behaviour, and operational plan. It does not end when every fashionable component has appeared in a drawing.

Worked example · A careful extension plan

  1. Persistence: replace the in-memory connection with a deliberate storage and backup configuration, then test restart behaviour.
  2. Identity: add an owner field and verified caller context for management operations; do not trust an arbitrary body field.
  3. Concurrency: run real competing requests against the chosen engine, inspect conflicts, and document retry semantics.

Result: Extend one named assumption at a time and re-run the relevant invariant and failure tests.

Go deeper: [24] OWASP API Security Project · [25] Define recovery objectives for downtime and data loss · [4] Monitoring distributed systems

Keep these ideas

  • An executable small model makes important assumptions visible.
  • A deployable design must preserve its rules while adding real failure and operational behaviour.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

If a link expires at time 200 and a cache refreshes at time 150, what must the cache lifetime respect?

Hint: The cached value cannot outlive the domain rule.

Read the worked solution

14.2 · Practice task

Add a test in which a different request ID claims an already used alias. What behaviour should a real API expose?

Hint: Alias uniqueness and repeated intent are different conflicts.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · Start with the operation and its promises

Solution 1.1

One possible security requirement is that an authenticated learner may read or change only their own private progress, enforced on every API operation. One reliability requirement is that acknowledged completion survives the named failure model and can be read under a defined consistency contract. Add a measured success/latency target over a stated window rather than leaving “reliable” as a slogan.

Return to the task

Solution 1.2

Ask what user need requires writes during a regional partition, what conflicts are acceptable, and what operational cost is available. Revisit data ownership, consistency, routing, recovery, and testing assumptions. The new request may justify a different architecture, but simply adding a second Region to the drawing does not define how conflicting writes are reconciled.

Return to the task

Chapter 2 · Estimate load storage and latency with units

Solution 2.1

The average is 4,320,000 / 86,400 = 50 requests per second. An assumed 8× peak is 400 requests per second. The peak number is a planning scenario, not something derived from the daily total alone. Capture observed time-series demand and include retries and background work before sizing a real service.

Return to the task

Solution 2.2

No. Many different distributions have the same mean, including ones with a small but important group waiting much longer. Measure the relevant percentile or fraction of requests within the target, specify the sample and time window, and examine whether a particular endpoint or user path is slow. Avoid averaging percentiles across hosts as though that reconstructed the global distribution.

Return to the task

Chapter 3 · Design an API that can be used safely twice

Solution 3.1

A caller can alter a body field to name another learner. Derive the acting identity from the verified authentication context and separately authorize the operation on the target resource. A trusted administrator workflow may need delegated access, but that is a distinct permission and audit contract. Hiding the field in the UI does not stop a direct API request.

Return to the task

Solution 3.2

Compare the stored intent with the new request and reject a conflicting reuse according to the documented contract. Returning the old result silently can conceal a client bug, while executing the new request breaks the key’s repeat semantics. Scope keys appropriately, bound retention, and coordinate key storage with the result so a crash cannot leave a misleading completed marker.

Return to the task

Chapter 4 · Model data and protect the rules in the database

Solution 4.1

One increment was lost because each worker based its assignment on the same old value. An atomic database increment or properly coordinated transaction can express the intended operation. Choose the method according to required invariants and engine semantics, and test concurrent updates. Adding an arbitrary sleep or an application check before writing does not create the missing atomicity.

Return to the task

Solution 4.2

No. Maintaining indexes adds write and storage work, which can be a reasonable trade for important reads. Measure the query and write workloads, inspect whether the index is actually used, and consider its key order and selectivity. Remove redundant structures only after understanding other queries and constraints that depend on them.

Return to the task

Chapter 5 · Build a request path with bounded concurrency

Solution 5.1

Only about 250 ms remains in the stated overall budget before accounting for response overhead. A fresh full timeout can keep resources occupied after the caller no longer benefits. The exact cancellation and cleanup semantics depend on the client and service; stopping the wait does not guarantee the downstream effect is cancelled.

Return to the task

Solution 5.2

Measure connection acquisition wait, query execution time, open connection counts, database resource pressure, lock contention, and the arrival/concurrency pattern. Check for leaked or unnecessarily long-lived transactions. Increasing the pool helps only when the dependency can productively handle the added work; otherwise it can turn a bounded wait into broader overload.

Return to the task

Chapter 6 · Use caches without losing the meaning of the data

Solution 6.1

If the stored response contains one learner’s data, another learner can receive it under the same key without the origin performing a fresh authorization check. Avoid shared caching for that private response unless a carefully designed policy explicitly handles identity and authorization. A public static artifact and a personalized account response should not inherit the same caching rules.

Return to the task

Solution 6.2

A larger cache does not by itself stop all callers from observing the same miss and loading the backing store. Coalesce suitable refreshes, bound work, spread expiry, or serve stale values only when permitted. Test the backing store under the miss scenario and decide how excess requests are rejected or delayed. Capacity and refresh coordination solve different parts of the problem.

Return to the task

Chapter 7 · Queues events and the outbox problem

Solution 7.1

The queue may consider the message completed while the business work was never committed, so normal redelivery cannot repair it. Acknowledge according to the chosen protocol only after the required effect is durable or a recoverable state explicitly records what remains. Test the crash before commit, after commit, and after acknowledgement as separate cases.

Return to the task

Solution 7.2

No. The outbox gives a durable record of outgoing intent coordinated with the originating database change. Publication can still be repeated after uncertainty, so the receiving side must preserve its own business contract under duplicate messages. Store and compare event intent where needed, and do not confuse delivery guarantees with the uniqueness of an external effect.

Return to the task

Chapter 8 · Replication consistency and what a successful write means

Solution 8.1

No. Under asynchronous replication, the follower may not yet have applied the successful write. The design must state whether that stale read is allowed and how an immediate dependent read meets the required semantics. Investigate commit evidence and replica position before declaring data loss, and avoid hiding repeated stale results behind an unexplained UI refresh.

Return to the task

Solution 8.2

Three members form a majority. The count alone does not prove all client observations are linearizable or that the system progresses under every failure. You also need the protocol’s ordering, persistence, leader, membership, and read rules. Keep arithmetic examples tied to their assumptions instead of treating the word quorum as a universal correctness guarantee.

Return to the task

Chapter 9 · Partition data without hiding the difficult key

Solution 9.1

Reading or updating one learner’s progress can stay within one ownership boundary. A global report across every learner may require a scan, secondary structure, or separate analytical path. The trade depends on traffic, data size, and freshness requirements. Describe both before choosing the key, and ensure a large or unusually active learner does not violate per-partition assumptions.

Return to the task

Solution 9.2

Concurrent writes can leave the new copy stale or inconsistent with later operations. Define a snapshot or change-capture method, write routing during the transition, conflict resolution, verification, and rollback. Track migration state durably and test interruptions. A one-time copy followed by a switch is safe only under additional assumptions such as an enforced write pause or an appropriate synchronization protocol.

Return to the task

Chapter 10 · Design for uncertainty partitions and overload

Solution 10.1

The receiver may have committed and lost the reply, may still be running, or may have failed before applying the effect. Resolve uncertainty through a stable operation identity, an appropriate status lookup, or a repeat-safe retry contract. Never create another unrelated side effect merely because the caller stopped waiting. The exact business procedure depends on the operation and available durable evidence.

Return to the task

Solution 10.2

A worst-case nesting produces 2^4 = 16 calls at the deepest layer per original request. Centralize or coordinate retry responsibility, use an end-to-end deadline, and limit retriable error categories. Add jitter where appropriate and test a dependency that remains overloaded. More retries are not automatically more reliability when they compete for the same exhausted capacity.

Return to the task

Chapter 11 · Make authorization and abuse resistance part of the design

Solution 11.1

The destination can resolve to internal or otherwise restricted addresses, redirect elsewhere, change through DNS behaviour, or expose privileged network reachability. A real fetcher needs an explicit destination policy, redirect and resolution controls, egress restrictions, resource limits, and tests for the relevant threat model. The capstone only stores and resolves a URL string; it never performs that backend fetch.

Return to the task

Solution 11.2

The bucket is empty after the five calls. One second adds two tokens, below the capacity of five, so two can be available. Clock handling, concurrent updates, and identity selection still need implementation rules. In a multi-node design, test whether independent local buckets unintentionally multiply the intended global allowance.

Return to the task

Chapter 12 · Know whether the design works for users

Solution 12.1

The process may stay alive while requests fail, return incorrect destinations, or exceed useful latency. Define success at the redirect operation and measure the intended result. Use uptime and resource metrics as diagnostic evidence, not as a complete proxy for user success. Also consider whether client-side failures before the server are visible to the selected measurement boundary.

Return to the task

Solution 12.2

Fault: terminate the worker after its durable update but before acknowledging delivery. Expected observation: the message may return. Invariant: the logical effect occurs only according to the repeat-safe contract. Recovery: restart a worker and process the replay. Evidence: inspect the durable state, event identity, and completion records, and verify that logs permit diagnosis without exposing private data.

Return to the task

Chapter 13 · Evolve the design without losing the ability to recover

Solution 13.1

The RPO permits at most a five-minute interval of recent data loss under the stated recovery scenario. The RTO aims to restore the required service within thirty minutes. Meeting one does not imply meeting the other. Test the actual backup and replay procedure, including access, provisioning, data validation, and the user operations required for service restoration.

Return to the task

Solution 13.2

One database can simplify transactions, queries, operations, and recovery for a workload within its capacity. It also defines a scaling and availability boundary that must be managed through the selected configuration and procedures. Measure load and failure requirements; revisit partitioning when concrete constraints justify the added ownership, migration, query, and coordination complexity.

Return to the task

Chapter 14 · Capstone Design and test a short-link service

Solution 14.1

It must not permit a successful resolution at or after the specified expiry under the chosen contract. At time 150, at most fifty time units remain, subject to clock and transport assumptions. A general one-hour cache policy can violate the domain rule. Updates or revocation may require an even stricter invalidation strategy, which must be designed explicitly.

Return to the task

Solution 14.2

The database unique constraint should reject the second alias claim, preserving the first row. A real API should translate the integrity conflict into a controlled documented response, or generate another alias when that matches the product contract. It should not silently replace the destination or reveal unnecessary owner information. Also test that a failed attempt leaves the original request’s resolution unchanged.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. Which is the strongest starting point for a design?

    1. A list of fashionable components
    2. An operation with actor effect and failure contract
    3. The largest available database
    4. A mandatory global cluster
    Check answer and reasoning
  2. 2. What does a daily request total establish by itself?

    1. The exact peak
    2. The p99 latency
    3. Only an average rate after choosing the time unit
    4. The correct pool size
    Check answer and reasoning
  3. 3. A creation response is lost after commit. Which design helps the retry?

    1. Create another unrelated result
    2. Assume timeout means no effect
    3. Trust a process-local flag forever
    4. Use a stable intent ID coordinated with the durable result
    Check answer and reasoning
  4. 4. Two clients both check that an alias is absent. What protects uniqueness when they race?

    1. A database uniqueness constraint with defined conflict handling
    2. A longer UI animation
    3. An arbitrary sleep
    4. Only a comment in the handler
    Check answer and reasoning
  5. 5. A downstream dependency slows down. What can unlimited application concurrency cause?

    1. Guaranteed recovery
    2. More in-flight work and resource exhaustion
    3. A proof of lower tail latency
    4. Automatic database scaling
    Check answer and reasoning
  6. 6. A cache contains revision A after the source changed to B. What is missing from a complete explanation?

    1. Another brand of cache
    2. A larger diagram
    3. The intended freshness and invalidation contract
    4. A second programming language
    Check answer and reasoning
  7. 7. A transactional outbox guarantees which limited property?

    1. Every external effect is exactly once
    2. No consumer can ever see a duplicate
    3. No queue can fail
    4. The originating business change and outgoing intent can share one database commit
    Check answer and reasoning
  8. 8. A stale follower read after a successful write necessarily means:

    1. Nothing by itself beyond the observation; replica lag may explain it
    2. The write never committed
    3. Every replica is corrupted
    4. The network has no latency
    Check answer and reasoning
  9. 9. Why might adding partitions not fix a global counter bottleneck?

    1. Partitioning never distributes anything
    2. One hot logical key may still have one owner
    3. Every counter is a cache
    4. Queries always become faster
    Check answer and reasoning
  10. 10. CAP should be applied by:

    1. Saying choose any two without conditions
    2. Assuming partitions never happen
    3. Naming the operation partition scenario and formal consistency/availability meanings
    4. Declaring every failure a proof of corruption
    Check answer and reasoning
  11. 11. HTTPS plus a successful login permits which assumption?

    1. The caller owns every record
    2. Shared caching of all private responses is safe
    3. Rate limits are unnecessary
    4. The connection and identity still need separate object-level authorization checks
    Check answer and reasoning
  12. 12. Which test most directly checks an acknowledgement gap?

    1. Commit an effect lose the acknowledgement replay and inspect durable state
    2. Only test a warm cache
    3. Count code lines
    4. Rename a service
    Check answer and reasoning
  13. 13. RPO and RTO describe:

    1. The same quantity twice
    2. Potential recent data loss and intended restoration duration
    3. Only processor utilization
    4. A guarantee supplied by any backup file
    Check answer and reasoning
  14. 14. At now equal to expires_at the capstone returns:

    1. The destination forever
    2. A random alias
    3. No valid resolution
    4. A database backup
    Check answer and reasoning

Assessment explanations

1. Answer B

An operation with actor effect and failure contract

A concrete operation and its promises make competing architectures testable against the same requirements.

Revisit the chapter · Return to the question

2. Answer C

Only an average rate after choosing the time unit

A total over time gives an average. Peak shape, latency, and resource use require further assumptions or measurements.

Revisit the chapter · Return to the question

3. Answer D

Use a stable intent ID coordinated with the durable result

Stable operation identity and durable intent/result coordination help resolve uncertain outcomes without repeating a logical effect.

Revisit the chapter · Return to the question

4. Answer A

A database uniqueness constraint with defined conflict handling

The invariant needs enforcement where concurrent effects meet. Both application checks can be true before either insert.

Revisit the chapter · Return to the question

5. Answer B

More in-flight work and resource exhaustion

Longer service time at the same arrival rate increases in-flight work; unbounded pressure can worsen the bottleneck.

Revisit the chapter · Return to the question

6. Answer C

The intended freshness and invalidation contract

The design must define whether the old result is allowed, when it refreshes, and what the user sees after an update.

Revisit the chapter · Return to the question

7. Answer D

The originating business change and outgoing intent can share one database commit

A relay can still publish again after an uncertain outcome, so downstream repeat handling remains necessary.

Revisit the chapter · Return to the question

8. Answer A

Nothing by itself beyond the observation; replica lag may explain it

Under asynchronous replication, visibility can lag. Check the required consistency and actual commit/read evidence.

Revisit the chapter · Return to the question

9. Answer B

One hot logical key may still have one owner

Distribution across many keys does not automatically split one concentrated operation without changing its semantics.

Revisit the chapter · Return to the question

10. Answer C

Naming the operation partition scenario and formal consistency/availability meanings

The theorem concerns precise guarantees under a network partition model, not a slogan about all desirable database properties.

Revisit the chapter · Return to the question

11. Answer D

The connection and identity still need separate object-level authorization checks

Transport protection and authentication do not decide whether this caller may act on this particular record.

Revisit the chapter · Return to the question

12. Answer A

Commit an effect lose the acknowledgement replay and inspect durable state

The experiment tests the actual uncertainty and invariant at the boundary where replay can occur.

Revisit the chapter · Return to the question

13. Answer B

Potential recent data loss and intended restoration duration

They are separate recovery objectives and require a tested procedure to demonstrate whether they can be met.

Revisit the chapter · Return to the question

14. Answer C

No valid resolution

The model explicitly uses now >= expires_at as the invalid boundary, so equality is expired.

Revisit the chapter · Return to the question

Glossary

Acknowledgement
A protocol confirmation that moves delivery state according to the consumer and broker contract. Chapter
Architecture decision record
A record of a design problem, constraints, choice, alternatives, and consequences. Chapter
At-least-once delivery
Delivery semantics under which a message can appear more than once and consumers must handle repeats. Chapter
Authorization
The decision that an identified caller may perform an operation on a particular resource. Chapter
Backpressure
A mechanism that communicates or enforces a limit on upstream production when downstream work cannot keep up. Chapter
Cache key
The identity used to decide which requests can reuse a cached result. Chapter
Cache stampede
A burst of backing-store work caused by many callers refreshing the same or similarly expired data. Chapter
Canary release
A bounded exposure of a change evaluated against meaningful signals before broader rollout. Chapter
Concurrency
Work in flight at the same time, distinct from arrival or completion rate. Chapter
Connection pool
A bounded set of reusable connections with an associated acquisition and lifetime policy. Chapter
Consensus
Agreement on decisions or an ordered log under a protocol’s explicit failure and progress assumptions. Chapter
Deadline
The point after which an operation no longer fits its overall useful time budget. Chapter
Expiry boundary
The explicitly defined time comparison at which an otherwise stored value stops being valid. Chapter
Functional requirement
A statement of observable behaviour the system must provide. Chapter
Hot key
A key receiving enough concentrated work to stress its owning resource despite broader distribution. Chapter
Idempotency key
A stable identifier for an intended operation across repeated requests under a documented contract. Chapter
Index
An additional data-access structure that trades maintenance and storage for suitable lookup efficiency. Chapter
Invariant
A condition that must remain true under all operations and failures included in the system contract. Chapter
Isolation
The database’s rules for interactions and allowed observations among concurrent transactions. Chapter
Jitter
Deliberate variation in retry timing to reduce synchronized bursts. Chapter
Latency
Elapsed time for an operation between defined start and finish points. Chapter
Linearizability
A correctness property that makes completed operations appear to take effect atomically in an order consistent with real-time precedence. Chapter
Liveness
Making progress under the assumptions a protocol requires. Chapter
Network partition
A communication failure separating participants that otherwise may continue running. Chapter
Outbox
A durable outgoing-event record committed with a business change before a relay publishes it. Chapter
Partition key
The data attribute or derived value used to assign a record or operation to an ownership partition. Chapter
Primary key
A database key that identifies a row under the schema’s uniqueness rules. Chapter
Quality goal
A measurable property such as latency, recoverability, or privacy under stated conditions. Chapter
Quorum
A participating set whose size and intersection properties serve a specified protocol. Chapter
Read your writes
A consistency property in which an actor can observe its own successful earlier writes under the stated scope. Chapter
Replica lag
Delay between a change at one copy and its application or visibility at another copy. Chapter
RPO
The maximum acceptable time interval of potential recent data loss for a recovery scenario. Chapter
RTO
The intended time within which the required service should be restored after a recovery scenario begins. Chapter
Safety
Preventing forbidden states or observations under the stated model. Chapter
SLI
Service-level indicator: a precisely defined measurement of a service outcome. Chapter
SLO
Service-level objective: a target for an indicator over a stated measurement window. Chapter
SSRF
Server-side request forgery: abuse of a server’s ability to request attacker-chosen destinations. Chapter
Tail latency
Behaviour near the slow end of a latency distribution, often described by a percentile. Chapter
Throughput
Completed work per time unit at a named system boundary. Chapter
Token bucket
A rate-limiting model with bounded stored admission tokens and a refill rate. Chapter
Transaction
A database unit of changes with documented commit rollback and isolation properties. Chapter
TTL
Time to live: a configured lifetime whose exact expiry semantics depend on the component and contract. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. HTTP semantics RFC 9110

    IETF · docs

    Use the standard to verify method semantics, status meaning, and HTTP contract assumptions.

    https://www.rfc-editor.org/rfc/rfc9110.html
  2. HTTP caching RFC 9111

    IETF · docs

    Review shared/private caching, freshness, validation, and response reuse rules.

    https://www.rfc-editor.org/rfc/rfc9111.html
  3. Service level objectives

    Google SRE · book

    Connect reliability targets to user operations and explicitly defined measurement windows.

    https://sre.google/sre-book/service-level-objectives/
  4. Monitoring distributed systems

    Google SRE · book

    Choose useful user-facing signals and diagnostic measurements instead of alerting on every fluctuation.

    https://sre.google/sre-book/monitoring-distributed-systems/
  5. Handling overload

    Google SRE · book

    Read after the queueing and pool chapter to examine how excess demand harms useful service.

    https://sre.google/sre-book/handling-overload/
  6. Canarying releases

    Google SRE Workbook · book

    Explore representative exposure, evaluation signals, and safe rollout decisions.

    https://sre.google/workbook/canarying-releases/
  7. Data integrity

    Google SRE · book

    Study integrity and restoration as operational responsibilities, not merely storage features.

    https://sre.google/sre-book/data-integrity/
  8. PostgreSQL 18 transaction isolation

    PostgreSQL Global Development Group · docs

    Version-pinned discussion of isolation behaviours and the obligations of concurrent applications.

    https://www.postgresql.org/docs/18/transaction-iso.html
  9. PostgreSQL 18 constraints

    PostgreSQL Global Development Group · docs

    Review primary, unique, foreign-key, and other declarative data rules. Adapt syntax for a different engine.

    https://www.postgresql.org/docs/18/ddl-constraints.html
  10. PostgreSQL 18 indexes introduction

    PostgreSQL Global Development Group · docs

    Understand access-path benefits and maintenance costs before tuning actual queries.

    https://www.postgresql.org/docs/18/indexes-intro.html
  11. PostgreSQL 18 explicit locking

    PostgreSQL Global Development Group · docs

    Explore lock modes and deadlock considerations after understanding the application invariant.

    https://www.postgresql.org/docs/18/explicit-locking.html
  12. Python 3.11 sqlite3 reference

    Python Software Foundation · docs

    Verify parameter binding and transaction-context behaviour in the executable local model.

    https://docs.python.org/3.11/library/sqlite3.html
  13. Making retries safe with idempotent APIs

    Amazon Builders Library · paper

    Read the argument about caller intent, stable request identities, and durable coordination.

    https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/
  14. Timeouts retries and backoff with jitter

    Amazon Builders Library · paper

    Understand uncertain outcomes, retry budgets, backoff, and jitter in real service interactions.

    https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
  15. Caching challenges and strategies

    Amazon Builders Library · paper

    Use after tracing the simple cache example to examine cold starts, refresh pressure, and fallback behaviour.

    https://aws.amazon.com/builders-library/caching-challenges-and-strategies/
  16. Using load shedding to avoid overload

    Amazon Builders Library · paper

    Explore controlled rejection and the protection of useful service under excess demand.

    https://aws.amazon.com/builders-library/using-load-shedding-to-avoid-overload/
  17. Transactional outbox pattern

    AWS Prescriptive Guidance · docs

    Study the database-and-message dual-write problem and the remaining need for consumer idempotency.

    https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html
  18. Standard queue delivery semantics

    AWS · docs

    A concrete service example of at-least-once and possible out-of-order delivery. Other systems have different contracts.

    https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html
  19. Raft paper and learning resources

    Diego Ongaro and John Ousterhout · paper

    Read the original consensus design and visual resources rather than inferring a protocol from quorum arithmetic.

    https://raft.github.io/
  20. Time Clocks and the Ordering of Events in a Distributed System

    Leslie Lamport · paper

    Historical original paper explaining event order and logical clocks. It is not a universal wall-clock synchronization mechanism.

    https://lamport.azurewebsites.net/pubs/time-clocks.pdf
  21. Dynamo design paper

    Amazon research authors · paper

    Historical distributed-storage design covering partitioning and failure tradeoffs. Do not assume every current DynamoDB feature follows this original system.

    https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf
  22. DynamoDB core data components

    AWS · docs

    A current product reference for keys and item modeling, kept separate from the historical Dynamo paper.

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html
  23. Brewers conjecture and feasibility of consistent available partition-tolerant services

    Seth Gilbert and Nancy Lynch · paper

    Use the formal failure model and definitions when interpreting CAP; the popular choose-two slogan omits essential conditions.

    https://www.comp.nus.edu.sg/~gilbert/pubs/BrewersConjecture-SigAct.pdf
  24. OWASP API Security Project

    OWASP · docs

    Review object authorization, resource limits, and related risks before exposing the local model as a network API.

    https://owasp.org/projects/api-security-project
  25. Define recovery objectives for downtime and data loss

    AWS Well-Architected · docs

    Distinguish acceptable recent data loss from the time allowed to restore service, then test the proposed procedure.

    https://docs.aws.amazon.com/wellarchitected/latest/framework/rel13-bp01.html
  26. MIT 6.824 Spring 2020: Lecture 1, Introduction

    MIT 6.824: Distributed Systems · Watch / course

    Optional introductory lecture from the official Spring 2020 course channel. Continue with its distributed-systems recordings after this first-pass guide; the material assumes additional programming background.

    https://www.youtube.com/watch?v=cQP8WApzIQQ

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.