All posts
System Design Mastermind · F04
  • System design
  • Interview prep
  • API design
  • Real-time

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Foundations F04. The contract between client and server: REST and HTTP semantics, when to pick GraphQL or gRPC, cursor pagination, idempotency keys and backoff, versioning, polling vs SSE vs WebSockets, webhooks, and holding millions of open connections. Each idea is told as a story you'll remember, with a lab that prices poll against push.

22 Oct 2026 · 22 min read · interactive

Share

Start here

Every design has a contract between the client and the server: what you can ask for, what comes back, what happens when you ask twice, and how the server tells you something without being asked. In the interview this is the "API" step, usually five minutes, but the choices made there (which style, how lists page, how retries stay safe, how live updates arrive) shape the rest of the design.

This page covers the eight ideas that come up again and again: REST and HTTP semantics, choosing between REST, GraphQL and gRPC, pagination, idempotent retries, versioning, the four ways to get live updates, webhooks, and holding millions of open connections. Each is told as a story first.

The one story for this page

One biryani order at 9 pm

You order biryani on a food-delivery app. Watch how many contracts one order touches:

  • The menu loads: a plain read, GET /restaurants/42/menu, cacheable because reading changes nothing. (REST)
  • You scroll through restaurants; new ones keep opening while you scroll, yet you never see the same one twice. (pagination)
  • You tap Pay in the lift, the signal drops, and the app retries. You are charged once. (idempotency)
  • You haven't updated the app in months, and it still works. (versioning)
  • Inside, the order service asks the restaurant service and the rider service, in a few milliseconds each. (gRPC)
  • The payment company tells the app's server "payment succeeded" by calling it back. (webhooks)
  • The rider's bike moves on your map every few seconds. (real-time push)
  • At 9 pm, a few million people are watching their own riders at the same moment. (connections at scale)

Each concept below is one line of this order.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

REST and HTTP: nouns, verbs and status codes

Name things (resources) in the URL, act on them with standard HTTP methods whose safety and idempotency are defined by the spec, and answer with status codes that tell the client whether retrying can help.

The story · remember it like this

The district library

Every book in the library has a fixed shelf address: Hall B, rack 12, number 7. You don't ask the librarian to "doTheBorrowingOfBook"; you bring a book and a slip with one of a few standard actions: look at it, add a new one, replace it, remove it.

The replies are standard too: "here it is", "no such book", "your card doesn't allow that", "come back later". Anyone who has used one library can use any library. That is REST: addresses for things, a small fixed set of verbs, and replies everyone understands.

What it really is
  • Resources are nouns with stable URLs: /orders/9812, /users/me/addresses. Plural collections, ids inside.
  • Methods carry meaning defined in the HTTP spec (RFC 9110). GET, HEAD and OPTIONS are safe (they don't change anything), so they can be cached and prefetched. PUT and DELETE are idempotent: sending the same request twice leaves the same result as once. POST and PATCH are neither by default.
  • Status codes: 2xx done; 4xx your request is wrong (400 bad input, 401 who are you, 403 not allowed, 404 not found, 409 conflict, 429 slow down), so retrying the same request won't help, except 408 and 429; 5xx the server failed, so a retry might.
  • Stateless: each request carries its own auth (a token), so any server behind the load balancer can answer.

The spec allows clients to retry idempotent requests automatically after a network failure. That's the practical reason to care which method you pick.

In a real system ✅ Seen · Stripe docs

Stripe's public API is resource-oriented: POST /v1/customers creates a customer, GET /v1/customers/{id} reads one. Because a create is a POST and therefore not idempotent, Stripe adds an Idempotency-Key header to make retries safe (see "Retries" below), and documents that GET and DELETE don't need one because they are idempotent by definition.

In an interview, four to six endpoints are enough: POST /orders, GET /orders/{id}, GET /orders?cursor=…, and whatever the core flow needs.

Trade-offs
  • REST maps well onto HTTP caching, proxies and tooling; actions that aren't CRUD ("cancel", "assign rider") are modelled as sub-resources or state changes (POST /orders/9812/cancel is fine and widely used).
  • Many small resources can mean many round trips for a screen that needs several of them; that's where GraphQL or a backend-for-frontend endpoint helps.
Say it in the interview

I'll keep the public API RESTful: nouns in the path, the user taken from the auth token, POST with an idempotency key for creates, cursor pagination for lists.

Trap

Putting the user id in the request body (POST /orders {userId: 7}) and trusting it. The caller's identity comes from the auth token, never from a field they can edit.

REST, GraphQL or gRPC: choosing a style

REST for public and simple APIs, GraphQL when many clients need different shapes of the same data, gRPC for fast typed calls between your own services.

The story · remember it like this

Thali, à la carte and the kitchen intercom

A thali is a fixed plate: quick to serve and the same for everyone, but you get the karela you'll leave, and if you want extra rotis you place a second order. That's REST: fixed responses per endpoint, sometimes too much (over-fetching), sometimes too little (another call).

À la carte lets you write exactly what you want on one slip. Lovely for you, but the kitchen must stop the table that orders 400 dishes in one go. That's GraphQL: the client picks fields, the server must limit query cost.

Behind the counter, the cooks shout "T4, two paneer, one jeera" over the intercom. Short codes, no menu cards, because everyone shares the same code book. That's gRPC: compact binary messages defined in a shared .proto file.

What it really is
  • REST + JSON: readable, cacheable by URL, works everywhere. Default for public APIs and in interviews.
  • GraphQL: one endpoint, the client sends a query naming the fields and nested objects it needs. Great for many screens and clients with different needs. Costs: caching by URL no longer works (queries are usually POSTs), and the server must cap query size and depth.
  • gRPC: you define services and messages in Protocol Buffers; code is generated for each language; calls run over HTTP/2 with binary payloads. Supports unary calls and server, client and bidirectional streaming. Browsers can't speak it directly: gRPC-Web needs a proxy (such as Envoy) and supports only unary and server streaming.

A common shape: REST or GraphQL at the edge for apps, gRPC between internal services.

In a real system ✅ Seen · GitHub docs

GitHub's GraphQL API protects itself with a points budget: 5,000 points per hour per user, every connection must ask for first or last 1–100 items, a single call may touch at most 500,000 nodes, and a request taking more than 10 seconds is cut off. That's the "kitchen limit" made concrete.

Netflix engineers described "wide usage of gRPC in the backend" (2021) and borrowed GraphQL's idea of asking only for the fields you need, using Protobuf FieldMask.

Trade-offs
  • GraphQL moves complexity to the server: resolvers can trigger N+1 database calls unless you batch (the DataLoader pattern).
  • gRPC's binary format and generated clients are fast and type-safe, but harder to debug by eye and need schema discipline.
  • Choosing GraphQL for a single client with fixed screens adds machinery for little gain.
Say it in the interview

Public API in REST for reach and caching; internal calls in gRPC for typed contracts and lower overhead. I'd add GraphQL only if several clients need different shapes of the same data.

Trap

Saying "GraphQL is faster". It saves round trips for the client but can cost the server more; without query cost limits one request can do a lot of damage.

Pagination: offsets slip, cursors hold

Never return an unbounded list; page it, and prefer a cursor ("start after this item") over an offset ("skip 40") when the list is large or changing.

The story · remember it like this

The results notice board

Exam results go up on the college notice board, newest names pinned at the top. You read the first 20, step out for chai, and come back to "skip the first 20 and read on". Meanwhile five new names were pinned on top. Skipping 20 now lands you five names back: you read five people twice.

Your friend did it differently. She remembered "I stopped after roll number 1043" and carried on from there. New names on top didn't matter. That's a cursor.

What it really is
  • Offset pagination: LIMIT 20 OFFSET 40. Easy, and lets you jump to page 37. But the database still walks past all skipped rows, so deep pages get slow, and inserts or deletes shift the window (duplicates or gaps).
  • Cursor (keyset) pagination: WHERE (created_at, id) < (last_seen) ORDER BY created_at DESC, id DESC LIMIT 20. An index jumps straight to the spot, so page 1,000 is as fast as page 1, and changes elsewhere in the list don't shift it.
  • Return the cursor as an opaque string (often base64) plus has_more; the server can change what's inside without breaking clients.
  • The sort key must be unique and stable: add the id as a tie-breaker to a timestamp.
In a real system ✅ Seen · Slack, 2017

Slack moved its Web API to cursor pagination (2017) because some endpoints designed for a few hundred records were returning hundreds of thousands. Offsets were slow (the database reads offset + count rows) and unreliable while new messages arrived. Their cursor is base64: dXNlcjpXMDdRQ1JQQTQ= decodes to user:W07QCRPA4, the id to start after, and they fetch count + 1 rows to know whether another page exists.

Stripe's list endpoints work the same way: starting_after=<last object id>, a limit of 1–100, and has_more in the response.

Trade-offs
  • Cursors can't jump to an arbitrary page or show "page 7 of 52"; for admin tables where that matters and data is small, offsets are fine.
  • Total counts are expensive on big tables; return has_more instead, or an approximate count.
Say it in the interview

Every list endpoint is paginated with an opaque cursor over (created_at, id), with a limit capped at, say, 100, so deep pages stay fast and new items don't shift results.

Trap

Using OFFSET on a feed or chat history. It gets slower with every page and shows duplicates as new items arrive, exactly the case interviewers ask about.

Retries without double charges: idempotency keys and backoff

Networks fail after the server did the work, so clients must retry; make retries safe with a client-generated idempotency key, and make them gentle with exponential backoff, jitter and a cap.

The story · remember it like this

The UPI payment in the lift

You tap Pay ₹450 just as the lift doors close. The spinner turns, then "Something went wrong". Did the money go? You can't tell: maybe the request never reached the bank, maybe it did and only the reply got lost.

If you tap Pay again and the bank treats it as a new payment, you pay twice. If the bank instead sees "this is the same payment you already processed, here is its receipt", one tap or five, you pay once. The payment carries an id the app made before the first try; that id is the idempotency key.

What it really is
  • The client generates a unique key (a UUID) per operation, sends it in a header (Idempotency-Key), and reuses the same key on every retry of that operation.
  • The server stores key → result. On a repeat it returns the stored result instead of doing the work again. Same key with a different body is an error. A repeat that arrives while the first is still running gets a conflict (409) and retries later.
  • Store the key in the same transaction as the effect (the order row), or with a unique constraint, so a crash between the two can't double-apply.
  • Retry policy: only retry what can help (timeouts, 5xx, 429), wait longer each time (exponential backoff), add randomness (jitter) so thousands of clients don't retry in lockstep, cap the attempts, and honour Retry-After on 429 and 503.

Idempotency makes a retried request safe; it doesn't make a whole multi-step workflow exactly-once. That's the later page on sagas.

In a real system ✅ Seen · Stripe docs

Stripe: keys up to 255 characters, V4 UUIDs suggested; the first response is saved (even a 500) and returned for retries; keys can be pruned after 24 hours; reusing a key with different parameters is rejected. An IETF draft (version 07, October 2025, not yet a standard) proposes the same Idempotency-Key header, with 409 for a concurrent retry and 422 for a reused key with a different payload.

AWS's analysis of backoff (2015) found that exponential backoff without jitter was "the clear loser": more total work and slower completion than adding randomness. "Full jitter" sleeps a random time between 0 and min(cap, base × 2^attempt).

Trade-offs
  • Keys cost storage and a lookup on every write; keep them for a bounded window (hours to days) that covers realistic retries.
  • Retries multiply load during an outage; use a retry budget or circuit breaker so they don't turn a slowdown into a collapse.
Say it in the interview

Create-order is a POST with an Idempotency-Key the app generates once; the server stores key and result in the same transaction, and clients retry with capped exponential backoff and jitter.

Trap

Generating a new key on each retry, or on the server. Then every retry looks new and you double-charge, which is exactly what the key was meant to prevent.

Versioning: change the API without breaking old apps

Add, don't change: new optional fields and new endpoints are safe; renaming, removing or changing the meaning of anything is a breaking change that needs a new version and a long goodbye.

The story · remember it like this

Renumbering the city buses

Imagine the city renumbers bus 500D to 512 overnight. Regular commuters stand at the stop waiting for a bus that no longer exists.

A sensible transport department keeps 500D running, adds 512 alongside, puts up notices for months, and only then retires the old number. New stops can be added any time without notice, because nobody's trip breaks when a bus stops somewhere extra.

What it really is
  • Safe (additive): new endpoints, new optional request fields, new response fields. Clients must ignore fields they don't know (the "tolerant reader").
  • Breaking: removing or renaming a field, changing its type or meaning, making an optional input required, changing an error code clients branch on.
  • Mobile apps are the hard case: old versions stay installed for years, so an API serves many client versions at once.
  • Ways to version: in the path (/v1/orders, simplest to explain), a header, or dated versions pinned per account. In Protocol Buffers, compatibility comes from field numbers: never reuse one, and mark deleted ones reserved.
In a real system ✅ Seen · Stripe, 2017

Stripe (2017) names versions by date (e.g. 2017-05-24) and pins each account to the version current at its first API call. Internally, responses are built for the newest version and then passed backwards through "version change" modules until they match the caller's version. Stripe said it had kept every version since 2011 working through almost a hundred backward-incompatible changes in six years.

Protobuf's guide: adding and removing fields are wire-safe as long as removed numbers are never reused; unknown fields are kept when parsing.

Trade-offs
  • Every live version is code you test and maintain; dated, transform-based versioning keeps the core clean but needs tooling.
  • A big-bang /v2 is easy to explain but forces every client to migrate at once.
Say it in the interview

I'd only make additive changes within a version, ask clients to ignore unknown fields, and introduce /v2 only for a real break, running both while we track who still calls v1.

Trap

Assuming clients upgrade when you deploy. The server ships in minutes; app users update over months, so the old contract must keep working.

Getting updates: polling, long polling, SSE or WebSockets

Polling asks on a timer, long polling waits for an answer, SSE streams server-to-client over one HTTP response, WebSockets talk both ways; pick by direction, how often updates come, and how fast users must see them.

The story · remember it like this

The food-court token screen

At a mall food court you've ordered dosa and got token 57.

  • Polling: you walk to the counter every two minutes and ask "57 ready?". Mostly "no". The counter staff spend their evening answering you.
  • Long polling: you stand at the counter until they hand it over. Instant, but you block a spot at the counter.
  • SSE: the token screen on the wall flashes each number as it's ready. One screen, everyone watches, nobody asks.
  • WebSocket: the counter gives you a walkie-talkie. They can say "57 ready", and you can say "make it without onion". Both ways, any time.
What it really is
  • Short polling: a GET every N seconds. Stateless and simple; average delay is N/2, and most responses are empty when updates are rare.
  • Long polling: the server holds the GET until there's news or a timeout (say 30 s), then the client asks again. Near-instant, but each update still costs a full request.
  • Server-Sent Events: one HTTP response that stays open; the server writes text events. Each event can carry an id; on reconnect the browser sends Last-Event-ID so you can resume, and a comment line every ~30 s keeps proxies from closing it. Over HTTP/1.1 browsers allow only 6 connections per domain across all tabs, so serve it over HTTP/2 or later.
  • WebSocket (RFC 6455): starts as an HTTP request that is "upgraded", then carries small frames (2–14 header bytes) both ways. You build heartbeats (ping/pong), reconnects and resume yourself.

None of these guarantees delivery by itself: a connection can drop with messages in flight, so add sequence numbers and acks when it matters.

In a real system ✅ Seen · Slack, 2023

Slack (2023) keeps a WebSocket per client for real-time events such as typing indicators and presence, but sends chat messages through its normal Web API. Writes get the REST benefits (auth, idempotency, retries); the socket is for receiving.

LLM APIs stream tokens with SSE: Anthropic's Messages API with "stream": true sends message_start, content_block_delta … message_stop events, plus ping events. One-way, text, resumable: exactly SSE's shape.

Trade-offs
  • Polling is cheap to build, cache and scale; it gets expensive when many users poll often for rare updates (the lab shows how much).
  • Open connections make servers stateful: deploys, load balancing and failover all have to deal with long-lived sessions.
Say it in the interview

Server-to-client updates where seconds matter: SSE over HTTP/2. Chat or games where the client also sends a lot: WebSockets. Rare updates: poll slowly, or send a mobile push.

Trap

Picking WebSockets for everything. For one-way updates SSE is simpler and reconnects by itself; for an update every 20 minutes a slow poll is cheaper than a million idle sockets.

Try it: Poll or push? One million phones waiting for news

Pick a feature and see what each technique costs: HTTP requests per second, empty answers, delay, open connections, memory and servers. Change how often updates happen and watch the cheapest choice flip.

Start from

5M fans watching a match page; a ball is bowled roughly every 30–40 s, so about 2 updates a minute. Server → client only.

Who talks
What we're sizingNumberHow we got itSo we decide
1 · Ask again and again
Short pollingNothing is held open, so servers stay stateless and any of them can answer. You pay in wasted requests and a delay of half the interval.1.0M req/s · 2.5 s delay
5.0M users ÷ 5 s = 1.0M requests/s
empty answers: e^(−0.033 × 5) = 85% carry nothing new
headers: 1.0M × 800 B × 8 = 6.40 Gbit/s
average delay ≈ half the interval = 2.5 s
servers ≈ max(1.0M req/s ÷ 10K, 50K open ÷ 100K) = 100
85% of requests are wasted. Fine only if updates are rare and nobody waits on them; otherwise push.
Long pollingNear-instant like push, but every update still costs a full HTTP request, and every user holds a connection anyway.264K req/s · ~50 ms
each request ends at the first update or after 30 s: average 19.0 s
5.0M ÷ that = 264K requests/s; 37% end with "nothing new"
headers: 1.69 Gbit/s
5.0M open × 30.0 KB = 150 GB of memory
servers ≈ max(264K req/s ÷ 10K, 5.0M open ÷ 100K) = 50
A fallback when SSE and WebSockets are blocked (old proxies), not a first choice.
2 · Keep one line open and push
Server-Sent Events · our pick5.0M open · ~50 msOne HTTP response that never ends. Server → client only; the browser reconnects by itself and sends Last-Event-ID so you can resume.
WebSocketBoth sides can send any time over one connection. You own reconnects, resume and heartbeats yourself.5.0M open · ~50 ms
167K updates/s × ~6 B frame header + ping/pong every 30 s
overhead: 40.0 Mbit/s
5.0M open × 30.0 KB = 150 GB of memory
servers ≈ 5.0M open ÷ 100K per server = 50
Use when the client also sends often: chat, multiplayer, collaborative editing.
3 · Verdict for these numbers
Our pickServer-Sent EventsUpdates flow server → client and users notice delay, so push over an open connection. SSE is the simplest (plain HTTP, built-in reconnect with Last-Event-ID); a WebSocket costs the same and is fine if you already run one.

Try: on Live cricket score, polling needs about 1.0M requests a second and most of them return nothing; SSE holds 5.0M connections instead. Then pick Report is ready: updates are so rare that slow polling wins. Constants are rounded, typical teaching values: 800 B of headers per poll, 30.0 KB per open connection, 10K requests/s or 100K connections per server. Tuned servers hold far more (WhatsApp reported over 2 million on one box in 2012).

Webhooks: when another company calls you back

A webhook is an HTTP POST from another system to your URL when something happens; treat it as at-least-once, possibly out of order, and from a sender you must verify.

The story · remember it like this

The tailor's phone call

You've given cloth to the tailor for a kurta. You could visit every day to ask if it's ready (polling). Instead he says, "I'll call you."

Three things follow. You check it's really your tailor calling, not someone pretending (verify the sender). If you don't pick up, he tries again later, and sometimes he calls twice to be sure (retries, duplicates). And when he calls, you say "thanks, coming" and hang up, instead of keeping him on the line while you find your wallet (reply fast, work later).

What it really is
  • The provider (payments, GitHub, a courier) POSTs a JSON event to an HTTPS endpoint you registered.
  • Verify every call: the provider signs the body (usually HMAC-SHA256 with a shared secret, plus a timestamp to stop replays); reject anything that doesn't verify.
  • Reply 2xx quickly, then process asynchronously: put the event on a queue and acknowledge. Slow handlers cause timeouts, timeouts cause retries, retries cause duplicates.
  • Deduplicate by event id and make the handler idempotent; don't assume order. When in doubt, fetch the current state from the provider's API.
  • Plan for missed events: a reconciliation job that lists recent events through the API catches what never arrived.
In a real system ✅ Seen · Stripe docs

Stripe automatically resends undelivered events for up to three days, and its docs show handlers that check "already processing or processed?" by event id before acting, because manual reprocessing and automatic retries can overlap. Its events API returns the last 30 days for reconciliation.

GitHub, by contrast, says it "does not automatically redeliver failed deliveries"; you redeliver from the UI or API. Same idea, different guarantee, so read each provider's rules.

Trade-offs
  • Webhooks save polling a partner's API, but your endpoint becomes public infrastructure: it needs authentication by signature, rate limits and monitoring.
  • For your own internal services, a queue or event stream usually beats HTTP callbacks: durable, replayable, and the consumer controls the pace.
Say it in the interview

The payment webhook handler verifies the signature, writes the event id to a dedupe table and a queue in one step, returns 200, and a worker updates the order idempotently; a nightly job reconciles against the provider's events API.

Trap

Doing the real work (sending emails, updating five tables) before returning 200. The provider times out, retries, and your handler runs twice.

Millions of open connections: gateways, fan-out and fallbacks

Put open connections on a thin, stateful gateway tier, keep business logic in stateless services behind it, route messages to the right gateway through pub/sub, resume with sequence numbers, and fall back to mobile push when the app is closed.

The story · remember it like this

Announcements at a big wedding

A wedding with 2,000 guests spread over four halls. The organiser doesn't walk up to each guest. Each hall has an announcer with a mic, and the organiser tells the announcers; they tell their halls (gateways and fan-out).

Each announcer knows who is in their hall (subscriptions). If a hall's speaker dies, guests walk to the next hall and ask, "what did I miss since the haldi announcement?" (reconnect and resume). Guests who've gone home get an SMS instead (mobile push). The organiser never cares which hall a guest is in; the announcers do.

What it really is
  • Gateway tier: servers that only hold connections, authenticate at connect time, send heartbeats and forward messages. Keep them thin so they can be restarted and scaled on their own.
  • Routing: when an event for user 7 happens, something must know which gateway holds user 7. Common answers: each gateway subscribes to the topics or channels its users need (pub/sub such as Redis or Kafka), or a hash ring maps channels to servers.
  • Resume: give every message in a stream a sequence number; on reconnect the client sends the last one it saw and the server replays the gap.
  • Reconnect storms: when a gateway restarts, all its clients reconnect at once. Use jittered backoff on reconnect and drain connections slowly during deploys.
  • App closed: the phone's OS keeps one connection to Apple (APNs) or Google (FCM) for all apps; your server sends to that service, which delivers when the device is online.
In a real system ✅ Seen · Slack, 2023

Slack (2023): gateway servers in several regions hold the WebSockets and subscriptions; channel servers own channels by consistent hashing; tens of millions of clients are connected and messages reach users worldwide in about 500 ms. A failed channel server is replaced in under 20 seconds.

WhatsApp (2012) reported over 2 million TCP connections on a single FreeBSD server with about 100 GB of RAM (96 GiB): roughly 45 KB of memory per connection at most. Connections are mostly a memory and tuning problem, not a CPU one.

Trade-offs
  • Sticky, stateful gateways complicate deploys and autoscaling; that's why they're kept small and dumb.
  • Pub/sub fan-out per message is cheap for small groups; a channel with a million members needs batching or a pull model instead.
Say it in the interview

Clients hold a WebSocket to a gateway tier; gateways subscribe to the channels their users are in; every message has a sequence number for resume; if the user is offline, we hand it to APNs or FCM.

Trap

Treating an open socket as guaranteed delivery. Messages in flight are lost when a connection drops; without sequence numbers and acks the user silently misses them.

Remember it

One line per idea. Read this the night before.

  1. The library: nouns in URLs, standard verbs, status codes. GET is safe, PUT and DELETE are idempotent, POST isn't. The user comes from the token.
  2. Thali, à la carte, intercom: REST at the edge, GraphQL for many differing clients (with cost limits), gRPC between services.
  3. The notice board: cursor ("after roll 1043") beats offset ("skip 20") for big or changing lists.
  4. UPI in the lift: an idempotency key made once by the client, stored with the result; retries with backoff, jitter and a cap.
  5. Bus 500D: add, don't change; old apps live for years; never reuse a protobuf field number.
  6. The token screen: poll for rare updates, SSE for one-way live, WebSockets for both ways.
  7. The tailor's call: webhooks are at-least-once and unordered; verify, reply fast, dedupe, reconcile.
  8. Wedding announcers: thin gateways, pub/sub to find them, sequence numbers to resume, APNs/FCM when the app is closed.

Check yourself

Answer out loud, then open.

Design the API to place an order. What makes a retry safe?

A POST /orders with an Idempotency-Key header that the app generates once per checkout and reuses on every retry.

  • Server: insert the key with a unique constraint in the same transaction as the order; on a repeat, return the stored response.
  • Same key, different body → 422; first request still running → 409, client retries later.
  • Client: retry only timeouts, 5xx and 429, with capped exponential backoff and jitter.

Say it The key makes the POST idempotent; backoff with jitter keeps retries from becoming a stampede.

Is PUT idempotent? Is PATCH? Why does it matter?

PUT is idempotent by the HTTP spec (RFC 9110): sending the same full replacement twice gives the same state. PATCH isn't guaranteed to be (an "increment by 1" patch applied twice differs from once), though a particular PATCH can be designed to be.

It matters because clients, proxies and libraries may retry idempotent requests automatically after a network failure. Anything else needs an idempotency key or must not be retried blindly.

A chat history endpoint uses LIMIT/OFFSET and users report duplicate messages when scrolling. Why, and what's the fix?

New messages arrive while the user scrolls, shifting every offset: "skip 40" now lands on items already seen. Deep offsets are also slow because the database walks past every skipped row.

  • Fix: keyset pagination with an opaque cursor over (created_at, id).
  • WHERE (created_at, id) < cursor ORDER BY created_at DESC, id DESC LIMIT 50, served by an index.
  • Return next_cursor and has_more; fetch limit + 1 rows to know if there's more.
Live cricket scores for 5 million viewers. Polling, SSE or WebSockets?

SSE (over HTTP/2), with a CDN-friendly fallback.

  • Updates are one-way and every few seconds; viewers notice delay.
  • Polling every 5 s would be about 1 million requests a second, most of them returning nothing new.
  • SSE holds 5 million connections instead (a gateway fleet), resumes with Last-Event-ID, and needs no client-to-server channel.
  • WebSockets would work but add nothing here.

Say it One-way, frequent, latency-sensitive: SSE. I'd size the gateway fleet by connections, not requests.

Your payment webhook sometimes marks orders paid twice and sometimes never. What's going on?

Webhooks are at-least-once and can be missed entirely.

  • Twice: the handler is slow, the provider times out and retries, and the handler isn't idempotent. Fix: verify the signature, record the event id (unique), enqueue, return 200; the worker updates the order only if not already done.
  • Never: your endpoint was down beyond the retry window, or the provider doesn't retry (GitHub doesn't). Fix: a reconciliation job that lists recent events or payments from the provider's API.
When would you choose gRPC over REST, and what's the catch?

Between your own services: typed contracts from .proto files, generated clients, binary payloads over HTTP/2, and streaming in both directions.

Catches: browsers can't call it directly (gRPC-Web needs a proxy and supports only unary and server streaming), payloads aren't human-readable, and you need schema discipline: never reuse field numbers, only add optional fields.

A gateway server holding 200,000 WebSockets is restarted for a deploy. What can go wrong and how do you avoid it?

All 200,000 clients reconnect at once and can overload the remaining gateways and the auth service (a reconnect storm); messages sent during the gap are lost unless clients can resume.

  • Drain gradually: stop accepting new connections, then close existing ones in batches.
  • Clients reconnect with jittered exponential backoff.
  • Every message carries a sequence number; on reconnect the client sends its last one and the server replays the gap.
  • Users who stay offline get the message through APNs or FCM.

Where you'll use this in the series

  • How a request travels · the network path under every API call, and the first look at polling vs push
  • Uber: from tap to pickup · the ride API, idempotent requests and the push platform
  • WhatsApp: chat and delivery receipts · WebSocket gateways, sequence numbers and acks (coming)
  • Notification system · webhooks, retries and mobile push via APNs and FCM (coming)
  • Payment system (Stripe) · idempotency keys and webhook reconciliation (coming)
  • Idempotency, exactly-once and sagas · beyond one request: workflows that must not run twice
  • LLM serving platform (ChatGPT-style) · streaming tokens with server-sent events (coming)

Sources

Checked October 2026. Protocol behaviour comes from RFCs and official docs; company figures are as published on the dates shown (WhatsApp 2012, Stripe and Slack 2017, Slack 2023) and may have changed since. The Idempotency-Key header is still an IETF draft. Lab constants (header bytes, memory per connection, requests and connections per server) are rounded, typical teaching values.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

You're reading this Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts