Every design is the same seven steps; what differs is which number binds. Requirements give the load, the estimate turns it into per-second rates and bytes, and the one quantity that crosses a single machine's limit (storage, open connections, a shared counter, a burst, or money) is the part you design; everything else stays the simplest thing that works.
You need: the parent root's method and constants (Topic: swe-and-system-design, Step 6 and Numbers to know). Each building block is taught on its owner and only applied here: partitioning, replication, leases (Distributed systems fundamentals); delivery semantics and idempotent consumers (Queues, streams and async work); retries, breakers, rate-limit algorithms (Reliability engineering); Little's law and caching (Capacity planning and performance); HTTP, cursors, idempotency keys (Service APIs).
Top: the seven steps, widths to scale with the minutes the Design drill's 45-minute clock gives each (5, 5, 3, 3, 9, 15, 5), after Alex Xu's ranges. Below: the number in each design that crossed a single machine's capacity, grouped by kind of constraint; the deep dives (15 minutes, the widest step) go there. Numbers from this page's estimates (src/recompute.py).
| Design | What the numbers say is hard | The key move | Who built it for real |
|---|---|---|---|
| 1. URL shortener | Reads outnumber writes 10 to 1; 36 billion links after five years do not fit 6 characters | Unique IDs without coordination, base62, a cache in front of the database | Bitly (2014), Twitter Snowflake (2010), Flickr (2010) |
| 2. Rate limiter | Many servers must agree on one counter in under a millisecond | An atomic check-and-increment in a shared store; fail open | Stripe (2017), Cloudflare (2017), GitHub (2021) |
| 3. Chat | 10 million open connections; presence heartbeats outnumber messages 7 to 1 | Persistent connections, a routing layer from user to connection, storage partitioned by channel and time | Discord (2017, 2023), Slack (2023), WhatsApp (2012) |
| 4. News feed | 60 reads per write; one celebrity post means 31 million deliveries | Fan-out on write, except for celebrities (merge them at read time) | Twitter (2012 to 2023), Facebook Multifeed (2015) |
| 5. LLM gateway | Throughput is tiny (18 requests a second); money, keys and personal data are the problem | One front door: virtual keys, budgets in tokens, redaction, fallbacks, usage events | Uber (2024), Wealthsimple (2023) |
| 6. RAG service | 215 GB of vectors; permissions; freshness; knowing whether answers are right | An ingestion pipeline, hybrid retrieval, permission filters, an evaluation set | Anthropic (2024), LinkedIn (2024), Uber (2025), DoorDash (2024) |
| 7. Job scheduler | 125,000 jobs due in the same second at the top of the hour; a crash must not run a job twice | Separate "decide what is due" from "do the work"; leases, jitter, idempotent jobs | Google cron (2015), Dropbox ATF (2020), Slack (2020) |
Each design has a live estimate (try "10× the traffic": a row turns red when it crosses one machine's capacity) and a 3D build-up from the naive version through each bottleneck and fix (its steps written out on the left, played as you scroll to it). Two results were measured for this page on PostgreSQL 16.2 on a laptop (src/lab/measure_pg.py, about 2 minutes): the rate limiter race and fan-out on read against on write. To practise, the Design drill tab runs the method on twelve prompts against a clock.
What each step sounds like in a 45-minute interview (Alex Xu's ranges, quoted on the root: scope 3 to 10 minutes, high-level design 10 to 15, deep dive 10 to 25, wrap-up 3 to 5; ByteByteGo). At work the same steps become a design document, the written proposal a team reviews before building.
| Step | What you do | What it sounds like |
|---|---|---|
| 1. Requirements | Functional and non-functional; agree what is out of scope. | "Before I draw anything: who uses this, how many, and what happens if a click is lost or counted twice?" |
| 2. Estimate | Users to requests a second, to storage, to machines. Round hard; keep one significant figure. | "600 million new links a month is about 230 a second, so writes are easy. 6 billion clicks is 2,300 a second; doubled for the peak, under 5,000." |
| 3. API | The calls clients make, with method, path, body and errors (Service APIs). | "POST /links returns the code; the redirect is a GET that answers 302." |
| 4. Data model | Tables or keys, and how each read finds its row (which index, which partition key). | "One table keyed by code; the redirect is a primary-key lookup." |
| 5. High-level design | The boxes and arrows, each justified by a requirement or a number. | "Stateless app servers behind a load balancer, a cache, one database." |
| 6. Deep dives | The two or three parts the estimate flagged. Let the interviewer steer. | "The interesting parts are ID generation and the cache; which would you like first?" |
| 7. Bottlenecks and failure | What breaks at 10×, what happens when each box dies, what each choice cost. | "If the cache dies, 4,600 reads a second land on the database: within one machine's capacity, so we survive degraded." |
Every estimate here uses the parent root's Numbers to know constants, so the topic stays consistent (recompute.py asserts they match):
"36 billion links do not fit in 6 base62 characters" changes the code length; "18 TB" changes whether you shard; "333,000 presence heartbeats a second" changes what you optimise first in chat. If a number would not change any box, skip it and say so.
The warm-up: small enough to finish, and it still touches IDs, caching, HTTP and storage. A URL shortener turns a long address into a short one (sho.rt/aZ3kQ9x); visiting the short one redirects: the server answers "go here instead" and the browser follows.
What the numbers say. Writes are 230 a second and redirects under 5,000 a second at peak: both within one database (about 17,500 a second at our half-benchmark planning figure), so the cache is about latency and headroom, not survival. Two numbers do change the design: 36 billion links after five years fill 63% of the 6-character code space, so random 6-character codes would collide on most attempts and 7 characters are needed; and 18 TB of rows is more than one comfortable database server, so storage must be split later. The app tier needs about a dozen servers, the order Bitly reported: "~30 servers handle all incoming traffic from the outside world including shortens, redirects, api requests, web ui, etc." (same source).
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
Base62 writes a number with 62 symbols (0 to 9, a to z, A to Z): 6 characters give 626 = 56.8 billion codes, 7 give 3.52 trillion. Three schemes:
aZ3kQ9x, aZ3kQ9y, ...). Chosen, with both costs removed: each app server leases a block of 10,000 numbers from an ID range service (one row incremented in a database), so a create needs no network call, and a fixed reversible scramble (a permutation of the 7-character space) makes neighbouring numbers give unrelated codes.Three smaller decisions finish the design: answer 302, not a cacheable 301, so every click still reaches you (analytics, takedowns); put a cache in front and send each click to a queue instead of updating the row, so the redirect writes nothing; and pick the shard key (the code) now but split the database only when storage demands it. Each is argued in the closed block below.
Status codes, the Idempotency-Key header (a client-chosen ID that lets the server recognise a retried request and return the first answer instead of creating a second link) and error bodies are taught in Service APIs, sections 2 and 4.
Both redirect; the difference is caching. RFC 9110 says "A 301 response is heuristically cacheable", meaning a browser or proxy may reuse it without asking again, while 302 "Found" says the target "resides temporarily under a different URI" and is not on the list of heuristically cacheable codes (RFC 9110 §15.4.2, §15.4.3, §15.1). A cached 301 is free for you, but the browser stops coming back, so you lose its later clicks and cannot change or take down the destination for that browser. Choose 302 (or 301 with an explicit short cache lifetime) when analytics or takedowns matter. Bitly answers 301 with cache-control: private, max-age=90 (checked with curl -I on 2026-10-04, src/inputs/bitly_headers.txt): shared caches may not store it and a browser may reuse it for only 90 seconds, so nearly every click still reaches Bitly. Bitly's reason is not published; this is an observation, not their statement.
The redirect looks up the code in Redis (an in-memory key-value store, about 0.14 ms a lookup); on a miss it reads the database and puts the answer in Redis with a TTL (time to live, after which the entry expires). That is cache-aside, taught with its traps (stampedes when a hot key expires, stale entries after a takedown: delete the key on takedown) in Capacity planning and performance, Caching strategy. Links are written once and almost never change, the easiest possible thing to cache. An UPDATE links SET clicks = clicks + 1 on every visit turns each redirect into a write, and a viral link becomes one row that thousands of requests lock in turn; instead the server emits a click event to a queue and answers immediately, and consumers aggregate counts per link per hour. Bitly did exactly this: "Data about the conversion is popped onto a queue for the analytics and other downstream systems" (High Scalability, 2014). Delivery is at-least-once (an event may arrive twice after a crash), which a few duplicate clicks tolerate (Queues, streams and async work).
The access pattern is a pure key lookup by code, with no joins: the easiest data to partition (split rows across several databases by a key). Hash the code to pick a shard; each shard has a replica for failover. Not on day one: the first year is 3.6 TB and 230 writes a second, which one PostgreSQL primary with a replica handles. Use the shard key now, so moving later is mechanical. A partitioned key-value store (DynamoDB, Cassandra) fits this pattern natively and is an equally good answer; pick what the team can operate. How partitioning and consistent hashing work: Distributed systems fundamentals, Partitioning.
Flickr, 2010: "Ticket servers give us globally (Flickr-wide) unique integers to serve as primary keys in our distributed setup": a MySQL table where REPLACE INTO plus LAST_INSERT_ID() hands out the next number, run on two servers, one giving odd and one even numbers, so either can fail (Kremerskothen, Flickr, 2010-02-08).
Twitter Snowflake, 2010: a 64-bit ID made of "time - 41 bits (millisecond precision w/ a custom epoch gives us 69 years)", a "configured machine id - 10 bits - gives us up to 1024 machines" and a "sequence number - 12 bits - rolls over every 4096 per machine", so machines "should not have to coordinate with each other" and IDs sort roughly by time (snowflake README, 2010; announcement, 2010-06-01). Snowflake IDs are too long for a shortener (a 64-bit number needs 11 base62 characters) but are the standard answer for "unique IDs across many machines", and Discord uses them for every message (design 3). Instagram built the same idea inside PostgreSQL (root Case files: Instagram 2012).
| What fails | What happens | Defence |
|---|---|---|
| The cache cluster | All 4,630 redirects a second at peak hit the database | Within its planning capacity (17,500): degraded latency, no outage. Warm a new cache gradually. |
| A database primary | Creates fail for its shard; redirects continue from cache and replica | Automatic failover to the replica; creates return 503 with Retry-After meanwhile |
| The ID range service | Servers keep issuing from the blocks they hold | Blocks large enough for minutes of creates; two range servers like Flickr's |
| Abuse: phishing and spam links | The domain gets blocklisted by browsers | Scan new URLs asynchronously, rate-limit creates per user (design 2), answer 410 for removed links |
| Enumeration | Private links discovered by walking codes | Non-sequential codes (scramble or random), rate limits on 404s |
A rate limiter caps how often one client (an API key, a user, an IP address) may call you and rejects the excess with 429 Too Many Requests. The algorithms (fixed window, sliding window, token bucket, leaky bucket) are animated on one burst in Reliability engineering, Rate limiting: per-client fairness, and what a client sees (the 429, Retry-After, remaining-allowance headers) in Service APIs, section 5. The design question is different: many servers must enforce one limit together, in well under a millisecond, without becoming the thing that takes the API down.
What the numbers say. One Redis node, planned at half its benchmark, handles the whole fleet's checks, and the counters fit in 200 MB: not a big-data problem. Two things are hard. The network round trip (about 0.5 ms in a region) is most of the latency budget, so a check must be one round trip, not three. And counting only inside each server gives a client up to 50 times its limit if its requests spread over all 50 servers: that row turns red. At 10× traffic you need several Redis primaries, which brings sharding and hot keys.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
The naive shared counter reads the count, compares it with the limit, then writes count + 1. Between the read and the write another server reads the same count, so both admit a request the limit should have refused: a race condition (the result depends on the timing of concurrent operations), the same check-then-act bug that makes a retried payment charge twice.
Redis gives two atomic forms: INCR increments and returns the new value in one step (Redis INCR docs); for a token bucket (read tokens and a timestamp, compute, write both), send a Lua script: "Redis guarantees the script's atomic execution. While executing the script, all server activities are blocked during its entire runtime" (Redis scripting docs), so scripts must be short (the script is in the closed block below).
Fail open. When the limiter cannot answer (Redis timeout, script error), allow the request and count the failure; a limiter that fails closed turns a Redis blip into a full API outage (Stripe's rule, below). The Redis call gets a timeout of a few milliseconds and a circuit breaker (Reliability engineering, Circuit breakers).
Each of 32 threads sent 25 requests for the same key at the same moment. Check-then-act (SELECT n, then UPDATE n = n + 1 if under the limit) admitted . Atomic (UPDATE ... SET n = n + 1 WHERE n < 100 RETURNING n, one statement) admitted exactly 100 every time. Measured on PostgreSQL because no Redis was installed on this machine; the race and the fix are the same in Redis, where GET then SET races and a Lua script or INCR-then-compare does not. src/lab/measure_pg.py, 2026-10-04.
The shape mirrors Envoy's open-source limiter, "a Go/gRPC service designed to enable generic rate limit scenarios", where "A descriptor is a list of key/value pairs owned by a domain that the Ratelimit service uses to select the correct rate limit" and counters live in Redis (envoyproxy/ratelimit README).
The Redis docs' "Pattern: rate limiter" pairs INCR with EXPIRE and warns that "If for some reason the client performs the INCR command but does not perform the EXPIRE the key will be leaked".
Written for this page, following the structure of Stripe's published gist (below); the clock comes from the caller, so gateways need roughly synchronised clocks, or the script can call TIME on the Redis server instead.
Sharding and hot keys. Beyond one node, shard counters by key (hash of the key picks the node), so each key's counter lives on exactly one node and stays atomic. One enormous tenant still lands on one node; give it leased tokens or its own node. Replicas help availability but not accuracy: a replica can serve a stale count, and GitHub hit a subtler bug, below.
Stripe (2017-03-30): "At Stripe, we operate 4 different types of limiters in production. The first one, the Request Rate Limiter, is by far the most important one", restricting "each user to N requests per second"; then a concurrent-requests limiter ("You can only have 20 API requests in progress at the same time") and two load shedders that reserve capacity for critical traffic. "We use the token bucket algorithm to do rate limiting. ... We implement our rate limiters using Redis" (one quote joined from two sentences; Stripe blog). Its rules for the rollout: "Make sure that if there were bugs in the rate limiting code (or if Redis were to go down), requests wouldn't be affected", and "Dark launch each rate limiter to watch the traffic they would block" (Tarjan, Stripe, 2017-03-30). The companion gist "relies on the fact that Redis scripts execute atomically. No other operations can run between fetching the count and writing the new count" (gist).
Cloudflare (2017-06-07): counts in memcache inside each data centre, where "the only operations available were GET, SET and INCR", using the sliding window counter approximation (worked example: "rate = 42 * ((60-15)/60) + 18 = 42 * 0.75 + 18 = 49.5 requests"). Measured on real traffic, "0.003% of requests have been wrongly allowed or rate limited"; increments run asynchronously "without slowing down the requests"; it "handles several billion requests per day" and absorbed "as many as 400,000 requests per second to a single domain" (Desgats, Cloudflare). The trade: Cloudflare counts per data centre, not globally, accepting that an attacker spread across the world is judged locally.
GitHub (2021-04-05, updated 2023): moved off shared Memcached because "when it filled up, it would sometimes evict rate limiter data, even when it was still active", to "a replicated Redis backend with client-side sharding", with storage logic "in Lua, to guarantee atomicity", rolled out behind a feature flag. The surprise: "replicas don't expire data until they receive instructions to do so from their primaries", so reads from replicas saw expired windows; they stored the reset time explicitly (Mosolgo, GitHub).
| What fails | What happens | Defence |
|---|---|---|
| Redis node down or slow | Checks time out | Fail open after a few ms; local backstop limits; breaker; replica promotion |
| Cache eviction of counters | Limits silently reset (GitHub's Memcached problem) | A dedicated store with no eviction (maxmemory-policy noeviction) or enough memory |
| Replica reads | Stale or not-yet-expired counts | Read and write counters on the primary; store explicit reset times |
| A bad rule | Legitimate traffic rejected at scale | Dark launch (log would-be rejections first), a kill switch per limiter |
| Clock skew between gateways | Token refill computed wrongly | Use the Redis server's TIME inside the script |
INCR), in one round trip.A chat system delivers a message to the others in a conversation within a second, keeps the history forever and shows who is online. The new ingredient after designs 1 and 2: the server must push, sending you a message while you are not asking for anything.
What the numbers say. The message rate (46,000 a second at peak) is not the hard part. Three numbers are: 10 million open connections, about 100 servers that do nothing but hold connections; 333,000 presence heartbeats a second, seven times the message rate, so presence must be cheap and lossy; and 657 TB a year of stored messages with three copies, which no single database holds. If clients instead asked "anything new?" every 5 seconds, that is 2 million mostly empty requests a second, 43 times the real message rate: the row turns red, and that is why chat uses persistent connections.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
The connection. A WebSocket (RFC 6455) starts as an HTTP request that asks to "upgrade", then either side can send at any time over the same TCP connection. Long polling (the server holds each request until there is news) works everywhere but costs a request per message; server-sent events are one-way server push, what LLM APIs use to stream tokens (Streaming and real-time, section 2). Chat needs both directions often: WebSockets, with long polling as a fallback for hostile networks. Connection setup and TLS cost: Topic: protocols.
Routing to the right connection. The sender is on gateway 17, recipients on 3, 58 and 90. A session registry ("user u is on gateway g") with direct forwarding is simple for one-to-one chat but costs 5,000 lookups per message in a 5,000-member group. Chosen: channel servers: each channel is owned by one server, picked by consistent hashing (adding a server moves only a small share of keys: Distributed systems fundamentals, Partitioning); gateways subscribe to their users' channels, so fan-out is one message per gateway, not per user.
Ordering, offline, presence. The channel's server assigns increasing message IDs, so order is per channel, decided in one place; order across channels is not promised (nobody can see it), and clients use the last ID to ask for what they missed after a reconnect. A message is stored before it is acknowledged, so pushing to connections is best effort and a missed push is caught up from storage by cursor; recipients with no connection get a mobile push through a queue (Queues, streams and async work). Presence is a key with a TTL that heartbeats refresh, so a dead phone goes offline when the key expires; changes go only to people who are looking, batched, and may be seconds stale.
Storage. Reads are always "the latest 50 messages in channel c, then the 50 before", which points to a wide-column store (Cassandra, ScyllaDB: partitioned by a key across machines, rows sorted within a partition) keyed by channel and a time bucket, so a busy channel's partition stays bounded. A very busy channel is a hot partition (one key with a large share of traffic): cache recent messages in the channel servers and coalesce identical concurrent reads.
The client_msg_id is an idempotency key: if the acknowledgement is lost and the phone resends, the server recognises the ID and does not store the message twice. The server-assigned msg_id is a Snowflake-style ID (time first), so sorting by it sorts by time, and it doubles as the pagination cursor (Service APIs, section 2).
Discord presence, 2017: "When a user comes online, they connect to a guild, and the guild publishes a presence to all other connected sessions", and in servers with "up to 30,000 concurrent users", "publishing an event from a large guild could take anywhere from 900ms to 2.1s" until they batched sends per node (Vishnevskiy, Discord, 2017-07-06).
Discord storage, 2017: from one MongoDB collection "with a single compound index on channel_id and created_at" to Cassandra, because "our read/write ratio was about 50/50" and "Cassandra was the only database that fulfilled all of our requirements"; "channel_id became the partition key", message IDs are Snowflakes, and "if we stored about 10 days of messages within a bucket that we could comfortably stay under 100MB", giving the key "((channel_id, bucket), message_id)". They ran "a 12 node cluster with a replica factor of 3" at "well past 120 million" messages a day (Vishnevskiy, Discord, 2017-01-13).
Discord, 2023: "At the beginning of 2022, it had 177 nodes with trillions of messages"; hot partitions led to data services that coalesce reads ("If multiple users are requesting the same row at the same time, we'll only query the database once") and a move to "just 72 ScyllaDB nodes", with history p99 from "between 40-125ms" to 15 ms (Ingram, Discord, 2023-03-06; root Case files: Discord 2023).
Slack, 2023: "Every Slack client has a persistent websocket connection to Slack's servers"; Channel Servers "are stateful and in-memory", mapped to channels "based on consistent hashing"; a message goes from the web app to an Admin Server, which "discovers CS through a consistent hash ring", then to Gateway Servers and clients; "At peak times, about 16 million channels are served per host", messages arrive "across the world in 500ms", and "a new CS is ready to serve traffic in under 20 seconds" (Thangudu, Slack, 2023-04-11). Slack's January 2021 outage (root Case files: Slack 2021) shows the other side: when the network, not the servers, is the bottleneck, autoscaling on CPU misreads it.
WhatsApp, 2012: one tuned Erlang server held "over 2 million tcp connections", "with plenty of CPU and memory to spare" (WhatsApp blog, 2012-01-06). Our planning figure of 100,000 per server is deliberately 20 times lower: a conservative default you would raise after load testing.
| What fails | What happens | Defence |
|---|---|---|
| A gateway server | 100,000 clients disconnect at once and reconnect at once | Reconnect with jittered backoff; catch up by cursor from storage, not from the server that died |
| A channel server | Live delivery for its channels pauses | The hash ring moves its channels to others; Slack's replacement is ready in under 20 s |
| A hot channel (a giant group) | One partition and one channel server overloaded | Recent messages served from memory; coalesced reads; batched fan-out per gateway |
| Lost acknowledgement | The client resends; risk of a duplicate | client_msg_id deduplication |
| Presence storm after an outage | Millions of "online" events in seconds | Batch and throttle presence; it may be stale |
A news feed (home timeline) shows each user the recent posts of the accounts they follow, newest first. The classic case is Twitter around 2012: its engineers published the numbers, and one decision, when to do the merging work, dominates everything else.
What the numbers say. Reads outnumber posts 60 to 1. Assembling each timeline when it is read (fan-out on read: look up everyone you follow, fetch their recent posts, merge) is about 22 million index lookups a second. Copying each post into every follower's timeline when it is written (fan-out on write) makes a read one lookup and moves the work to 375,000 deliveries a second, about 1.1 million inserts counting three copies. Twitter chose write. The bill: 2.9 TB of RAM to hold 800 entries for every user, and one post by an account with 31 million followers is 93 million inserts.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
The gap widens with the number of accounts followed (on-read work grows with it; a precomputed read stays one index range). The price: every post stored once per follower (8 million rows, 766 MB for this toy), and at 31 million followers one post takes minutes to fan out.
The talk notes: "it can take up to 5 minutes for a tweet to flow from Lady Gaga's fingers to her 31 million followers", and the plan was "Not fanning out the high value users anymore. For people like Taylor Swift don't bother with fanout anymore, instead merge in her timeline at read time. Balances read and write paths" (High Scalability, 2013). This hybrid is the expected answer: accounts under a follower threshold fan out on write; accounts over it are stored once and merged into each reader's timeline at read time (a handful of extra lookups, not hundreds); inactive users get no maintained timeline and have it rebuilt on login, which cuts the 2.9 TB to the active users' share.
Spend it when something is produced if reads vastly outnumber writes and the result is reused; spend it when it is consumed if writes fan out enormously, or the result is personal and changes per read. Caches (design 1), materialised views and search indexes are the same decision under other names. Ranking moved Twitter itself back to read time (closed block below).
Medians over 500 users. Top pair: reading the 50 newest posts by joining follows to posts at read time, against reading 50 rows from a timelines table capped at 800 entries per user. Bottom pair: inserting one new post into every follower's timeline, for the most-followed account against a median one ( times longer). Each pair has its own scale. Follows are Zipf-skewed (illustrative: synthetic graph); absolute numbers are a laptop's, the ratios are the lesson. src/lab/measure_pg.py, 2026-10-04.
Deleting a post must remove it from millions of timelines (store ids, not copies of the text, and filter deleted ids at read time); unfollowing leaves old entries (filter at read time or accept it); the fan-out runs on a queue of delivery jobs, so a burst of posts delays delivery rather than failing posts (backpressure: Queues, streams and async work, Backpressure and Little's law).
A chronological timeline is a merge; a ranked one ("For You") is a search problem. Twitter's 2023 description: the system must "distill the roughly 500 million Tweets posted daily down to a handful", first by candidate sourcing ("we attempt to extract the best 1500 Tweets from a pool of hundreds of millions"), then a "~48M parameter neural network" ranks them; the timeline is "50% In-Network Tweets and 50% Out-of-Network Tweets on average"; the pipeline "runs approximately 5 billion times per day and completes in under 1.5 seconds on average", and "A single pipeline execution requires 220 seconds of CPU time". Most strikingly: "We recently stopped using Fanout Service, a 12-year old service that was previously used to provide In-Network Tweets from a cache of Tweets for each user" (Twitter engineering, 2023-03-31, Wayback copy). Once most of a feed comes from accounts you do not follow, precomputing per-follower lists stops paying, and the work moves back to read time, with heavy caching and machine learning. Facebook had made the read-time choice from the start: an aggregator "fanned out the request to all the leaves to fetch data, rank and filter data", where leaves keep recent actions in memory (Zhu, Facebook Multifeed, 2015-03-10).
| What fails | What happens | Defence |
|---|---|---|
| A celebrity posts (or many at once, during a live event) | Fan-out queue backs up; everyone's delivery slows | Hybrid: no fan-out above the threshold; delivery queue per priority |
| Timeline cache node lost | Those users' timelines missing | Three copies; rebuild from the graph on demand |
| Traffic spike 25× average (Twitter's 2013 record) | Write path and fan-out overwhelmed | Accept posts into a durable queue first; fan out as capacity allows (root Case files: Twitter 2013) |
| Deleted post still visible | Ids remain in millions of lists | Filter against a deleted-ids set at read time; clean up lazily |
Every team now calls large language models (LLMs), each with its own API keys, retry code and surprise bill. An LLM gateway is one internal service every model call goes through. Its mechanisms (authentication, routing, token-based limits, budgets, fallbacks) are taught in Gateways and routing, caching and the degradation ladder in ML system design (section 7, and its Cost-quality lab tab); this section runs the interview: what to ask, what the numbers say, what to build first.
What the numbers say. Throughput is not the problem: 18 requests a second at peak fits on one small server (run at least two). Uber's real gateway reported "16 million queries per month, with a peak QPS of 25" for "close to 30 customer teams" (Wang and Bansal, Uber, 2024-07-11), the same order as ours (an independent comparison, not a reproduction). What is big is money: about $4,200 a day, $1.5 million a year at the illustrative Sonnet 5.5 price of $2 and $10 per million input and output tokens (from ML system design, section 6), where a 10% routing mistake is a salary. Also about 180 streams open at once (Little's law with 10-second replies), which sets connection limits and timeouts, and 5.5 GB of request logs a day holding whatever employees typed, a security asset to protect.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
max_tokens) before the call and refund the difference after, with atomic counters as in design 2 (Gateways and routing, sections 5 and 6, including what LiteLLM really does under concurrency).Model aliases (fast, smart) let the platform team change the model behind them; teams that need stability pin a dated version. Buy or adopt first (LiteLLM, Envoy AI Gateway, Kong, Portkey) unless data rules force you to build.
Uber (2024): "A pivotal design decision was to mirror the HTTP/JSON interface of the OpenAI API". The gateway generates "audit logs for comprehensive cost attribution", and its "centralized nature ... streamlines the management of usage and budgeting across various teams". A "PII redactor that anonymizes sensitive information within requests before forwarding them to third-party vendors" restores the entities in the response (Wang and Bansal, above).
Wealthsimple: its gateway redacted personal data too, "enhanced by a PII removal model we developed in-house" (Wealthsimple engineering, date unconfirmed (2023 or 2024)).
LiteLLM: the proxy takes per-team tpm_limit, rpm_limit, max_parallel_requests and a max_budget with a budget_duration (LiteLLM docs), and names the fallback settings fallbacks, num_retries, allowed_fails, cooldown_time, request_timeout (LiteLLM reliability docs).
| What fails | What happens | Defence |
|---|---|---|
| A provider outage or 429 storm | Every product using that model fails at once | Fallback chain with cooldowns; tested regularly with real traffic (a fallback that has never carried load fails when needed) |
| The gateway itself | Every AI feature in the company stops | Stateless replicas in two zones; budget store failure means fail open with a local cap, as in design 2 |
| A runaway script | Burns a month's budget overnight | Per-key token limits and budget alerts at 50%, 80%, 100% |
| Provider silently changes an alias | Quality changes with no deploy | Pin dated versions in routes; log the model version in every usage event; evaluate before switching (Production eval engineering) |
| Buffering proxy | Users see nothing until the whole reply is done | Stream pass-through end to end, long idle timeouts |
Retrieval-augmented generation (RAG) answers a question by first finding the relevant passages in your own documents, then asking an LLM to answer from them, citing them (RAG, Lewis et al. 2020; retrieval methods on Topic: rag-and-retrieval). The design question is the system around it: getting millions of documents in, keeping them fresh, never showing someone a document they may not open, and knowing whether the answers are right.
What the numbers say. Queries are trivial (under 2 a second at peak). The corpus is not: 35 million chunks of about 500 tokens, whose 1,536-dimension vectors take 215 GB as 4-byte floats, more RAM than a typical database server, before the index's own graph. The numbers suggest half-precision storage (pgvector's halfvec, 2 bytes a dimension, halves it), fewer dimensions, or a sharded vector store. Embedding the whole corpus once costs about $350 at $0.02 per million tokens (OpenAI, text-embedding-3-small, read 2026-10-04), so re-embedding is cheap in money; keeping up with 2% of documents changing a day is only 8 chunks a second. Answers cost about $650 a day, mostly the input tokens of the retrieved chunks: the number of chunks per prompt is the cost dial.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
Ingestion is an idempotent, versioned pipeline. A connector per source receives change events (or polls), puts "document d changed" on a queue, and workers fetch, extract text, split into chunks (passages small enough to retrieve precisely, overlapping a little so a sentence cut at a boundary survives), compute an embedding for each (a vector from a model, placed so passages with similar meaning are near each other) and upsert. Key every chunk by (doc_id, chunk_no) and write it with the document's version, so a redelivered or reordered event is harmless (the idempotent-consumer pattern of Queues, streams and async work, Idempotent consumers); delete chunks beyond the new count when a document shrinks; and keep the embedding model's name with every vector, because vectors from different models are not comparable (ML system design, section 4).
Hybrid retrieval. Vectors alone miss exact terms (error codes, product names, people), so run keyword search (BM25, ranking by term frequency) alongside vector search, merge, then rerank the top candidates with a slower, more accurate model. Anthropic, on its own benchmark: adding a short generated context to each chunk ("usually 50-100 tokens") and combining contextual embeddings with contextual BM25 "reduced the top-20-chunk retrieval failure rate by 49% (5.7% → 2.9%)", and "when combined with reranking, by 67%", for a one-time "$1.02 per million document tokens" with prompt caching (Anthropic, Introducing Contextual Retrieval, 2024-09-19).
Permissions and freshness. Copy each document's access groups onto its chunks and filter at query time by the asker's groups; never rely on the LLM to "not mention" a document it was given. The trap: pgvector warns "With approximate indexes, filtering is applied after the index is scanned", so a filter matching few rows can return fewer results than asked unless iterative index scans are enabled. Revocations flow through the same pipeline as edits, and fast: one that takes a day is a leak for a day. Event-driven connectors plus a short queue meet "searchable in 10 minutes"; a nightly full re-sync catches missed events.
Knowing whether it works. RAG fails in two places: retrieval missed the passage, or generation did not use it faithfully. Measure both on a golden set (real questions with the documents that answer them) before every change of chunking, model or prompt, and on sampled traffic; the metrics are on RAG and retrieval evaluation, gates and shadow tests on Production eval engineering.
A vector index finds the chunks nearest to the question's embedding without comparing against all 35 million. The common choice is HNSW (hierarchical navigable small world), a layered graph searched from coarse to fine, which "allows a logarithmic complexity scaling" (Malkov and Yashunin, 2016). In PostgreSQL, pgvector offers HNSW, which "has better query performance than IVFFlat (in terms of speed-recall tradeoff), but has slower build times and uses more memory", and IVFFlat, which "has faster build times and uses less memory than HNSW, but has lower query performance"; indexable vectors go up to 2,000 dimensions, and halfvec up to 4,000 (pgvector README). Start with pgvector if you already run PostgreSQL and the index fits in memory; move to a dedicated vector store when it does not. Database choices in general: Topic: databases. Show each citation's last-updated date so users can judge staleness.
LinkedIn (2024): customer-service question answering over a knowledge graph built from past tickets, which "outperforms the baseline by 77.6% in MRR" and, deployed, "reduced the median per-issue resolution time by 28.6%" (Xu et al., arXiv 2404.17723).
DoorDash (2024): a support assistant that "first condenses the entire conversation to pinpoint the core problem" and then searches past resolved cases and articles; an LLM guardrail "reduced overall hallucinations by 90% and cut down potentially severe compliance issues by 99%" (DoorDash engineering, repost dated 2024-09-17).
Uber (2025-05-29): moving from plain RAG to an agentic version with "an additional BM25-based retriever alongside traditional vector search" raised acceptable answers "by a relative 27%" and cut incorrect advice "by a relative 60%" (Uber, Enhanced Agentic-RAG). All three are vendor-reported results on their own data.
| What fails | What happens | Defence |
|---|---|---|
| Permission sync lags | Someone sees a passage they should not | Permission events on a priority queue; deny by default for unknown groups |
| Connector misses events | Stale answers, silently | Nightly reconciliation; alert on age of the newest indexed change per source |
| Embedding model changed | Old and new vectors mixed: garbage retrieval | Store model version per vector; re-embed into a new index, switch atomically |
| Index outgrows memory | Latency jumps by orders of magnitude | halfvec or fewer dimensions; shard; watch index size against RAM |
| Prompt injection inside a document | A document instructs the model | Treat retrieved text as data; guardrails; restrict tools (Guardrails) |
A job scheduler runs work at a given time: "every day at 02:00, rebuild the search index"; "in 30 minutes, send this reminder". Cron is the classic Unix program that does this on one machine from schedules like 0 2 * * * (minute, hour, day, month, weekday). The company-wide version must survive machines dying without running jobs twice or skipping them silently. (A notification system reuses most of designs 3 and 7 and is a prompt in the Design drill, with Netflix's published design as its reference; the scheduler is worked here because it has the better public sources, all with numbers.)
What the numbers say. The average is small: 116 runs a second, about 2,300 running at once, 48 worker machines. The danger is the clock: people write 0 * * * *, so 30% of the day's runs, 125,000 of them, become due in the same second, which would need 2,500 machines for one second and 48 the rest of the time. Spreading each hourly batch over a minute with jitter (a random delay per job) brings the burst to about 2,100 a second. Run history (5 GB a day) is easy.
Each red step is a bottleneck the estimate exposed; the next green step fixes it. The counters show the naive design's value struck through beside the current one, for the same traffic.
Deciding what is due, exactly once. Two machines both reading "what is due?" will both run the same job. One fix is one leader, elected through a consensus system (etcd, ZooKeeper, or Paxos/Raft directly): clean, but failover takes seconds, and a deposed leader that does not yet know it can still launch, hence leases and fencing tokens (Distributed systems fundamentals, Leader election, leases and fencing tokens). Chosen at this scale: row claiming: every instance runs SELECT ... FROM jobs WHERE next_run_at <= now() ORDER BY next_run_at LIMIT 100 FOR UPDATE SKIP LOCKED, where SKIP LOCKED makes each skip rows another has locked, and in the same transaction inserts the run row and advances next_run_at: no extra system, the database's transaction is the coordination. Either way the runs primary key (job_id, scheduled_for) makes "the 02:00 run of job 7" a row that can exist only once, so a second scheduler gets a conflict instead of a second run.
The scheduler only enqueues. A slow job must not delay every other launch, so the scheduler writes the run to a queue; workers pull, take a lease (a claim that expires unless renewed by heartbeats) and execute; a dead worker's lease expires and another retries. That is at-least-once execution: a run that did its work but died before recording success runs again, so jobs with side effects use job_id plus scheduled_for as their idempotency key, or check whether their effect already happened (Queues, streams and async work).
Google's distributed cron (state kept consistent with Paxos across replicas): "In general, we favor skipping launches rather than risking double launches, as much as the infrastructure allows" (Google SRE book, Distributed Periodic Scheduling with Cron; Davidovič and Guliani, ACM Queue, 2015; the reasoning is in the closed block below). A billing job prefers a skip plus an alert; a cache-warming job prefers a double run. Make it a per-job setting.
overlap says what happens if the previous run is still going; misfire says what happens to runs missed while the scheduler was down: two decisions every scheduler forces, discussed under Queues, streams and async work, Scheduling and cron.
next_run_at in UTC with a real time-zone library, and decide the rule for missing and repeated local times.now() as the one clock for "due".Google cron: skipping is preferred because "it is more acceptable to not launch Cron jobs for a while than to mistakenly launch the same Cron job ten times instead of once", and "all operations on external systems, which we may need to continue upon re-election, either have to be idempotent ... or we need to be able to look up their state" (SRE book, above).
Dropbox ATF (2020-11-11): "currently serving 9,000 async tasks scheduled per second and in use by 28 engineering teams". It guarantees "that a task is executed at least once after being scheduled" and "that at most one instance of a task will be actively executing at any given in point"; "95% of tasks begin execution within five seconds from their scheduled execution time". Its parts match this design: a Store Consumer "periodically polls the task store to find tasks that are ready for execution and pushes them onto the right queues" (Amazon SQS), and executors send heartbeats while they run (Krishnan, Dropbox).
Slack's job queue: "On our busiest days, the system processes over 1.4 billion jobs at a peak rate of 33,000 per second". When a database slowdown filled Redis to its memory limit, Slack "decided to add Kafka in front of Redis rather than replacing Redis with Kafka outright": a durable log absorbs the burst, and a relay feeds Redis at the rate it can take (Slack engineering, page dated 2017-12-06, updated 2020-06-25).
Netflix Maestro (2024-07-22): a workflow orchestrator that "runs half a million jobs daily on average, and has completed around 2 million jobs on particularly busy days" (Netflix tech blog): when jobs depend on each other, a scheduler grows into a workflow engine (durable workflows are in the queues sibling).
| What fails | What happens | Defence |
|---|---|---|
| Scheduler instance dies mid-claim | Its transaction rolls back; another instance claims the rows | Claim, insert run and advance next_run_at in one transaction |
| Worker dies mid-run | Lease expires; the run is retried | Idempotent jobs; heartbeats; max_runtime kills stuck runs |
| Scheduler down for an hour | Missed runs | Per-job misfire policy (run once now, or skip and alert) |
| Top-of-hour burst | Queue backs up; jobs start late | Jitter; bounded queues with priorities; autoscale workers ahead of the hour |
| A job that always fails | Retries forever, crowding others | Capped retries with backoff, dead-letter, page the owner |
(job, scheduled time) and explained at-least-once execution.Reading worked designs builds recognition; only producing designs under a clock builds the skill.
Practise the method under a clock. Pick a prompt, start the timer, and for each step say (or write) your answer before revealing the model answer. Then tick what your answer covered. Seven prompts are the worked designs of the Reading tab (the reveal is their summary, with a link back); five are new, with a reference answer and the sibling sections to read afterwards. Your ticks are saved in this browser only, if it allows storage.
Most strong answers tick about two thirds of the items; the point is to see which kind you miss repeatedly (numbers, failure modes, trade-offs said aloud) and practise that. The traps are listed in the Reading's How to practise section.
Times are estimates for a careful first read. Links checked 2026-10-04; where a site blocks readers, the Wayback Machine copy is linked.
Twelve prompts (the seven worked designs plus a notification system, typeahead, a web crawler, ticket booking and a key-value store), a 45-minute clock, the method revealed step by step with self-check lists. 45 min a drill.
The root: one LLM chat product from 1 user to 10 million; Step 6 is the method this page applies; Scale simulator, Numbers to know (the constants used in every estimate here) and Case files (Discord, Slack, Twitter, Instagram, Stripe, cited here). About 21 min.
The service behind every API sketch on this page (handlers, the data layer, workers, shutdown); the contracts themselves (errors, cursors, idempotency keys, versioning) are Service APIs. About 27 min.
Replication, partitioning, consistent hashing, quorums, leases and fencing: the storage and scheduler deep dives. About 46 min.
At-least-once delivery, idempotent consumers, backpressure, scheduling and cron: clicks, fan-out, ingestion and job runs. About 40 min.
Timeouts, retries, circuit breakers, rate-limiting algorithms (animated), fail-open, safe deploys: every failure-modes table. About 40 min.
How you would know any of these designs works in production. About 39 min.
Little's law, caching strategy, load balancing and load testing behind the estimates. About 39 min.
The service around design 5: tenancy, batch paths, caching, rollouts, degradation ladders, its Cost-quality lab and section 8 (an ML interview run with the method). About 23 min.
Unit, property-based, data and model tests and CI. About 46 min.
Inside one of these boxes: readable code, abstractions, review. About 42 min.
Retrieval metrics, faithfulness, building a test set from your corpus: the evaluation half of design 6. Its own page.
Golden sets, gates, shadow and A/B tests for model and prompt changes. Its own page.
Runtime safety for LLM systems: policies beyond redaction, prompt injection. Its own page.
Retrieval methods in depth. 21 min
Where retrieval-augmented generation started. About 19 min.
The serving engine under a self-hosted model in design 5. About 27 min.
Database classes and choices; HTTP, TLS and WebSockets in depth. 27 and 33 min
Four limiters, token buckets in Redis, fail open, dark launches. 15 min.
The sliding window counter at Cloudflare scale, with its measured error. 15 min.
Lua for atomicity and the replica expiry bug. 10 min.
Choosing Cassandra and the (channel, bucket) key. Then the trillions sequel (2023). 20 min each.
Gateway, channel, admin and presence servers on a hash ring. 15 min.
The talk behind design 4; High Scalability's notes are the readable summary. 50 min video, 20 min notes.
An LLM gateway at a large company, with its numbers. 15 min.
Hybrid retrieval and reranking measured. 15 min.
Paxos-backed cron and the skip-or-double-launch decision. 25 min.
A real scheduler's components and guarantees. 20 min.
A shortener's real architecture, summarised from a talk. 15 min.
The reference for the notification prompt in the drill. 15 min.
Alex Xu's four-phase framework and timings, used on this page. 20 min.
Free, broad, with worked exercises; use it for more prompts. About 2 h for the core.
The book behind most deep dives here. Many evenings.
The ML variant of the interview, free. About 1 h 30 min.