Library / Blogs

Marc Brooker's Blog

An AWS distinguished engineer's short essays on distributed systems, databases and performance.

By Marc Brooker · brooker.co.za · Added 2026-10-12

Open original source

All content belongs to Marc Brooker / brooker.co.za. We only link to it and give credit. Report a problem

Learn this article

About 37 min left. Your work is saved as you go.

What you are about to study

brooker.co.za wrote this to explain how they thought about a problem. It assumes you are comfortable with distributed systems.

Ideas you will meet

Distributed Systems
Consensus, time, failure and the fundamentals of scale-out.
Resilience
Timeouts, retries, circuit breakers, bulkheads and load shedding.

What we already know about this

Our own lessons on these ideas. Read them here before you start, so it makes sense.

  • Advanced Distributed Systems · 13 minResilience: timeouts, retries, bulkheads, backpressure and circuit breakersHow to stop one slow or failing dependency from taking everything down: the patterns, how they fit together and where each one goes wrong.Read here

    The core problem

    In a system of many services, slowness is more dangerous than failure. A dependency that fails fast is easy to handle. One that responds in 30 seconds makes callers hold threads, connections and memory until they too stop responding: a cascading failure. Resilience patterns limit how far a problem can spread.

    The toolbox

    Figure SDA-ADS-06-1 · Resilience layers around a call · © forcsguy.com

    Timeouts

    Every network call needs a timeout, including connect, read and overall. Pick from measured latency (for example slightly above the 99th percentile), not a guess, and make the caller's budget smaller than its own caller's so work is abandoned in an orderly way. Propagate deadlines across calls.

    Retries

    Retry only transient failures and only idempotent operations (or use idempotency keys). Use exponential backoff with jitter (random spread) so clients do not retry in lockstep, cap the attempts, and apply a retry budget (for example no more than 10 percent extra traffic). Retry at one layer, not at every layer, or attempts multiply.

    Circuit breaker

    A breaker watches failures or slow calls. Closed: normal. After too many failures it opens: calls fail immediately (or use the fallback) so the dependency can recover and callers stop wasting resources. After a cool-down it goes half-open: a few trial calls decide whether to close again.

    Figure SDA-ADS-06-2 · Circuit breaker states · © forcsguy.com

    Bulkheads

    Partition resources so one dependency cannot consume them all: separate thread pools or connection pools per dependency, separate queues per tenant or per priority, or separate instances for critical paths. A slow recommendation service then cannot starve checkout.

    Backpressure and load shedding

    If producers outpace consumers, work piles up. Without limits the buffer grows until memory is exhausted or latency becomes huge. Options:

    • Bounded queues that reject or block when full.
    • Signalling upstream to slow down (credit-based flow in streaming systems, TCP windows, reactive streams).
    • Load shedding: deliberately drop low-priority work early (return 429 or 503 quickly) to protect the rest.
    • Rate limiting at the edge (see the rate-limiter lesson).

    Failing fast and visibly under overload is better than accepting everything and failing slowly.

    Fallbacks and graceful degradation

    Return something useful when a dependency fails: cached data, a default, a simpler algorithm, or hide a non-essential section. Decide which features are essential before an incident, and test the degraded mode.

    How they interact

    • A timeout is the minimum; without it nothing else works.
    • Retries inside a breaker inside a bulkhead is the usual nesting.
    • Everything needs metrics: breaker state, rejected calls, queue depth, timeout counts. Alert on them.
    • Test it: inject latency and failures (chaos experiments) to confirm the patterns work before production does it for you.

    Common mistakes

    Retries with no backoff; timeouts longer than the caller's; unbounded queues; a shared thread pool for everything; breakers that never close; fallbacks that call the same failing service; and testing only the happy path.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Real-World Systems · 11 minDesign an email system (Gmail)How a message travels between providers over SMTP, how spam and spoofing are filtered, and how a mailbox is stored and searched at huge scale.Read here

    The problem

    An email system receives and sends messages for billions of mailboxes, stores them for years, keeps spam out, and lets users search and organise (labels, threads).

    Requirements

    • Reliable delivery: a message is never silently lost.
    • Interoperability with every other mail provider.
    • Spam, phishing and virus filtering.
    • Large attachments, fast search, and strong privacy.

    How email moves between providers

    Email uses SMTP to send between servers. The key ideas:

    • MX records in DNS tell you which servers accept mail for a domain.
    • Delivery is store-and-forward: a server accepts a message, persists it, and passes it on, retrying if the next hop is down.
    • Clients usually read mail through IMAP (or POP3) or through a provider's web and mobile API.

    Figure SDA-RWS-02-1 · Servers talk SMTP to each other; readers fetch with IMAP or POP · © forcsguy.com

    A post sorting office: email servers also accept, sort and forward messages between providersImage: Tim Sheerman-Chase · CC BY 2.0 · Source · Wikimedia Commons: Old Post Sorting Office, Portsmouth

    Architecture

    Figure SDA-RWS-02-2 · Email delivery architecture · © forcsguy.com

    Sending

    1. The client sends the message to its provider's submission server (with authentication).
    2. The message is saved and put on an outbound queue, so slow recipients never slow the sender.
    3. A worker finds the recipient domain's MX hosts, connects with SMTP, and delivers. The worker signs the message (DKIM).
    4. Temporary failures are retried with backoff for days; permanent failures generate a bounce message.

    Receiving

    1. The incoming server accepts the connection and verifies the sender with SPF, DKIM and DMARC.
    2. Filters score the message for spam, phishing and malware (rules, reputation, and machine learning).
    3. The message is written to the user's mailbox: metadata in a scalable database, bodies and attachments in object storage, and an entry in the search index.
    4. Clients are told (push, IMAP IDLE) that new mail arrived.

    Figure SDA-RWS-02-3 · Where a received message is stored and how readers are told · © forcsguy.com

    Fighting spam and spoofing

    MechanismWhat it does
    SPFThe domain lists which servers may send for it
    DKIMThe sender signs the message; receivers check the signature
    DMARCThe domain says what to do when SPF or DKIM fail, and gets reports
    ReputationTrack sending behaviour per IP and domain; rate-limit new senders
    Content filtersSpam classifiers, link and attachment scanning

    Storage design

    • A mailbox is append-heavy and read by recent items. Partition by user id, so one user's mail sits together.
    • Keep metadata (labels, flags, thread id, snippet) separate from large bodies and attachments.
    • Threads group messages by headers (References, In-Reply-To) and subject.
    • Search uses an inverted index per user, updated as mail arrives.
    • Deduplicate identical large attachments with content hashes.
    • Keep multiple replicas and backups: email is people's records.

    Scale and reliability

    • Queues absorb bursts, for example newsletter sends.
    • Rate-limit outgoing mail per account to stop compromised accounts spamming.
    • Spread incoming servers across regions; MX records can list several with priorities.
    • Privacy: encrypt in transit (TLS between servers) and at rest, and control internal access carefully.

    Real-world reading

    Open this lesson with its quiz and exercise

  • Low-Level Design Practice · 11 minFood deliveryRestaurants, menus, orders and couriers: an order lifecycle with three parties, and how to keep their views consistent.Read here

    The problem

    Customers browse restaurants, build an order from a menu, pay and track delivery. Restaurants accept and prepare orders. Couriers pick up and deliver them.

    Entities

    Figure SDA-LLD-09-1 · Food delivery classes · © forcsguy.com

    OrderItem copies the name and price at purchase time. Later menu edits must not change old orders.

    The order lifecycle

    Figure SDA-LLD-09-2 · Order status · © forcsguy.com

    Each party may trigger only some transitions: the restaurant accepts and marks ready, the courier marks picked up and delivered, the customer may cancel early. Keep the allowed-transition table in one place.

    const next: Record<string, Record<string, string>> = {
      PLACED:    { restaurantAccepts: "ACCEPTED", restaurantRejects: "CANCELLED", customerCancels: "CANCELLED" },
      ACCEPTED:  { startPreparing: "PREPARING" },
      PREPARING: { courierPicksUp: "PICKED_UP" },
      PICKED_UP: { courierDelivers: "DELIVERED" },
    };
    function apply(order: Order, event: string) {
      const to = next[order.status]?.[event];
      if (!to) throw new Error(`${event} not allowed in ${order.status}`);
      order.status = to; order.notifyAll();      // observers: customer, restaurant, courier apps
    }
    

    Assigning a courier

    Figure SDA-LLD-09-3 · Courier assignment · © forcsguy.com

    Matching (nearest, fastest, fairest) is a strategy, as in the cab-booking lesson. Batching two orders for one courier is an extension with its own route check.

    Design notes

    • Price calculation (items, taxes, fees, discount) lives in one service used by cart, checkout and invoice.
    • Menu availability: items can sell out; check at add-to-cart and again at placement.
    • Idempotent placement: a double tap must not create two orders; use a client-generated order key.
    • Notifications use the Observer pattern on status changes.
    • Failures: payment fails (do not place), restaurant unresponsive (timeout and refund), courier cancels (reassign).

    Real-world reading

    Open this lesson with its quiz and exercise

Go deeper on this

A path through videos, articles, other case studies and code on the same ideas as Marc Brooker's Blog.

  1. Warm upGet the vocabulary first.

  2. WatchHow others solve the same problem, on video.

    Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)

  3. ReadEngineers explain it in their own words.

  4. See it in another companyThe same ideas, a different system.

  5. Read the codeSee how it looks when it is real.

Keep learning

Loading community…