System design case studies: worked designs from requirements to bottlenecks

Seven whole designs (a URL shortener, a rate limiter, chat, a news feed, an LLM gateway, a RAG service, a job scheduler), each run through one method from requirements and a computed estimate to the bottlenecks, with what real companies built. Each building block links to the sibling that teaches it. Child page of Topic: swe-and-system-design. Data as of October 2026. Reading: 41 min, plus 28 in closed details.

The idea in one screen

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).

Functional / non-functional
what the system does / how much, how fast, how reliably, how consistently, how cheaply. The second kind decides the architecture.
Back-of-the-envelope estimate
users to requests a second, bytes and machines, one significant figure, each row compared with one machine's capacity.
Bottleneck
the first resource to run out as load grows; in the 3D build-ups it turns red and the next step fixes it (green).
Fan-out
one event delivered to many recipients (followers, gateways, subscribers); where it happens (on write or on read) is a recurring choice.
Fail open
when a check cannot run, allow the request (a rate limiter); fail closed denies (a permission check).

One method, seven designs: the estimate points at the part that is hard

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).

DesignWhat the numbers say is hardThe key moveWho built it for real
1. URL shortenerReads outnumber writes 10 to 1; 36 billion links after five years do not fit 6 charactersUnique IDs without coordination, base62, a cache in front of the databaseBitly (2014), Twitter Snowflake (2010), Flickr (2010)
2. Rate limiterMany servers must agree on one counter in under a millisecondAn atomic check-and-increment in a shared store; fail openStripe (2017), Cloudflare (2017), GitHub (2021)
3. Chat10 million open connections; presence heartbeats outnumber messages 7 to 1Persistent connections, a routing layer from user to connection, storage partitioned by channel and timeDiscord (2017, 2023), Slack (2023), WhatsApp (2012)
4. News feed60 reads per write; one celebrity post means 31 million deliveriesFan-out on write, except for celebrities (merge them at read time)Twitter (2012 to 2023), Facebook Multifeed (2015)
5. LLM gatewayThroughput is tiny (18 requests a second); money, keys and personal data are the problemOne front door: virtual keys, budgets in tokens, redaction, fallbacks, usage eventsUber (2024), Wealthsimple (2023)
6. RAG service215 GB of vectors; permissions; freshness; knowing whether answers are rightAn ingestion pipeline, hybrid retrieval, permission filters, an evaluation setAnthropic (2024), LinkedIn (2024), Uber (2025), DoorDash (2024)
7. Job scheduler125,000 jobs due in the same second at the top of the hour; a crash must not run a job twiceSeparate "decide what is due" from "do the work"; leases, jitter, idempotent jobsGoogle 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.

The method, out loud

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.

StepWhat you doWhat it sounds like
1. RequirementsFunctional 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. EstimateUsers 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. APIThe 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 modelTables 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 designThe boxes and arrows, each justified by a requirement or a number."Stateless app servers behind a load balancer, a cache, one database."
6. Deep divesThe 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 failureWhat 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."

The estimating toolkit

Every estimate here uses the parent root's Numbers to know constants, so the topic stays consistent (recompute.py asserts they match):

  • A day is 86,400 seconds (call it 100,000: a million a day is about 12 a second); a month is 2.6 million seconds.
  • Peak over average: the root uses 2 as an illustrative planning factor; Twitter's record second in 2013 was 25 times its average (root, Case files: Twitter 2013). Say which you assume.
  • One app server (AWS m7i.xlarge, $0.2016 an hour): 500 requests a second, the root's illustrative default.
  • One PostgreSQL database: about 35,000 read queries a second, 18,000 mixed read-write (PlanetScale, 4 vCPU; root Numbers), planned at half a benchmark (the root's derating).
  • One Redis node: 180,180 SETs a second with 50 clients (Redis docs benchmark), planned at 90,090; about 0.14 ms an operation locally, about 0.5 ms a round trip inside one cloud region.
  • GPUs: 2,209 output tokens a second per H100 for Llama 3.3 70B in FP8 (TensorRT-LLM, commit 8a9c66c), $3.99 per GPU-hour (Lambda); see ML system design, section 6.
  • Little's law: things in the system = arrival rate × time each stays; it turns requests a second into connections open or jobs running (Capacity planning and performance, Queueing theory you actually use).
An estimate earns its minutes only if it changes a decision

"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.

Design 1URL shortener: IDs, base62, caching, read-heavy scaling

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.

Requirements (agreed with the interviewer)
Functional
  • Create a short link (optionally a custom alias); visiting it redirects.
  • Click counts per link for owners.
  • Out of scope: accounts, editing, link previews.
Non-functional
  • Sized like Bitly in 2014: 600 million new links and 6 billion clicks a month (High Scalability, 2014, a summary of a Bitly engineer's talk).
  • Redirect under 50 ms at the server, p99. Links never break, kept 5 years; never give two users the same code.
  • Click counts may lag by minutes; a few lost clicks are acceptable.

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.

The design, built step by step: three bottlenecks, three fixes

  1. The naive design: one server, one database. The browser asks the app server for a code; it reads the long URL from Postgres, adds 1 to a click counter in the same row, and answers 302. New links get a random 6-character code.
  2. Bottleneck: the code space fills up. After five years, 36 billion links fill 63% of the 56.8 billion 6-character codes, so most new random codes collide and must be retried, and the retries get worse every month.
  3. Fix: 7-character codes from leased ID ranges. Each server leases a block of numbers from an ID range service, scrambles and encodes it in base62: 7 characters, 3.52 trillion codes, 1% used after five years, no collisions and no network call per create.
  4. Bottleneck: every redirect is a database read and a write. At peak, 4,630 redirects a second each read the row and update its click count. A viral link becomes one row locked by thousands of requests in turn.
  5. Fix: a cache in front, clicks to a queue. Redis answers 90% of redirects (cache-aside, about 0.14 ms). The click becomes an event on a queue that consumers aggregate; the redirect no longer writes anything.
  6. Bottleneck: one app server: capacity and a single point of failure. 5,093 requests a second at peak against about 500 per server, and if the one machine dies, every link on the internet that points at us breaks.
  7. Fix: a load balancer and 12 stateless servers. Servers hold no state (codes come from leased blocks, data from cache and database), so any server can answer any request and one can die unnoticed.
  8. Bottleneck: 18 TB, and one primary for every write. Five years of links is 18 TB on one database primary: backups, index rebuilds and failover all get slow, and the primary is still a single point of failure for creates.
  9. Fix: partition by code, a replica per shard. Hash the code to choose a shard; each shard has a replica that takes over on failure. Planned from day one (code is the key), executed when storage demands it.

The decision that matters: where short codes come from

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:

  • Hash the long URL (the first 7 base62 characters of its SHA-256). Deduplicates for free, but different URLs can collide, so every create must check, and two users shortening one URL share one code and one click count. Rejected as the main scheme.
  • Random codes, made unique by a unique index (the database refuses a duplicate and the server retries). The chance a new code collides is the share already used: about 1% at 7 characters after five years, 63% at 6. Acceptable at 7 characters.
  • A counter turned into base62. Never collides, but a single counter is a coordination point and sequential codes let anyone walk every link (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.

API and data model (the calls and the one table)
POST /v1/links create; Idempotency-Key header makes retries safe {"url": "https://example.com/a/very/long/path", "alias": null} -> 201 {"code": "aZ3kQ9x", "short_url": "https://sho.rt/aZ3kQ9x"} -> 409 if the alias is taken; 422 if the URL is not http(s) GET /{code} the redirect: the hot path -> 302 Found, Location: https://example.com/a/very/long/path -> 404 if unknown, 410 Gone if taken down for abuse GET /v1/links/{code}/stats?from=.. owner analytics, read from the analytics store

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.

links(code TEXT PRIMARY KEY, 7 base62 characters long_url TEXT NOT NULL, owner_id BIGINT, created_at TIMESTAMPTZ, status SMALLINT) -- the redirect is one primary-key lookup: no other index is on the hot path click_events -> a queue, then an analytics store (counts per link per hour)
Deep dives: 301 or 302, the cache and click counting, when to split (with sources)

301 or 302?

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 cache, and counting clicks without slowing redirects

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).

18 TB, and when to split the database

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.

What real companies built: Flickr's ticket servers, Twitter Snowflake

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).

Failure modes, and what interviewers listen for
What failsWhat happensDefence
The cache clusterAll 4,630 redirects a second at peak hit the databaseWithin its planning capacity (17,500): degraded latency, no outage. Warm a new cache gradually.
A database primaryCreates fail for its shard; redirects continue from cache and replicaAutomatic failover to the replica; creates return 503 with Retry-After meanwhile
The ID range serviceServers keep issuing from the blocks they holdBlocks large enough for minutes of creates; two range servers like Flickr's
Abuse: phishing and spam linksThe domain gets blocklisted by browsersScan new URLs asynchronously, rate-limit creates per user (design 2), answer 410 for removed links
EnumerationPrivate links discovered by walking codesNon-sequential codes (scramble or random), rate limits on 404s
What interviewers listen for
  • You asked about the read-to-write ratio and computed the code space instead of picking "6 characters" by habit.
  • You named at least two ID schemes and why you rejected one (collisions, enumeration, coordination).
  • You said 301 versus 302 out loud and tied it to analytics.
  • Click counting is off the hot path, and you said what at-least-once means for counts.
  • You did not shard on day one, and you said when you would.

Design 2Rate limiter as a service: distributed counters, atomic checks, fail open

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.

Requirements
Functional
  • Limits per API key per second and per minute, configurable per plan; rules change without a deploy.
  • A check call: "may key K do one more request?" answering allow or deny, plus remaining allowance.
Non-functional
  • 50,000 requests a second at peak across 50 gateway servers; 1 million active keys (illustrative).
  • Adds under 1 ms at p99. A few percent over the limit is fine; 50 times over is not.
  • If the limiter breaks, the API must keep working (fail open).

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 design, built step by step: local counters, a shared counter, then an atomic one

  1. The naive design: each gateway counts alone. Every gateway keeps its own counter per key in memory: no network call, zero added latency.
  2. Bottleneck: a client gets the limit once per gateway. Spread across 50 gateways, one key gets 50 × 100 = 5,000 requests a second against a limit of 100.
  3. Fix: one shared counter in Redis. Every gateway asks Redis: read the count, compare with the limit, write count + 1.
  4. Bottleneck: the read and the write race. Between one gateway's read and its write, others read the same value. Measured with 32 concurrent clients: 117 to 119 admitted against a limit of 100.
  5. Fix: check and update atomically, in one round trip. A Lua script (or INCR then compare) runs as one indivisible step on the Redis server: exactly 100 admitted. One round trip, about 0.5 ms in a region.
  6. Bottleneck: when Redis is slow, the API is down. If every request waits for the limiter, a Redis blip becomes an outage of the whole API. A bad rule does the same.
  7. Fix: fail open, with a local backstop, a kill switch and dark launches. A few-millisecond timeout, then allow the request under a coarse local limit. New rules first only log what they would block (Stripe's rule); each limiter has a kill switch.
  8. Bottleneck: 10× traffic: one node is not enough. At 500,000 checks a second one node (planned at 90,090) is saturated, and one giant tenant's key is hot.
  9. Fix: shard counters by key; replicas for failover. Each key lives on one shard, so its updates stay atomic. Read and write counters on the primary (replicas lag and expire keys late: GitHub's bug). Hot tenants get leased token batches.

The race, measured

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).

Check-then-act lets 17 to 19% too many through; one atomic statement, none. One key, limit 100, 32 clients at once (PostgreSQL 16.2, laptop, 3 runs)

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.

API, data model and the token-bucket Lua script
// internal gRPC or HTTP call from each gateway, or a library that talks to Redis directly Check(domain="public_api", descriptors=[("key","k_123"),("plan","pro")], cost=1) -> {allowed: true, remaining: 41, reset_after_ms: 380} // what the public client sees when denied HTTP/1.1 429 Too Many Requests Retry-After: 1

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).

-- token bucket per key: two fields, one Redis hash, expiring when idle rl:{k_123} -> tokens = 41.7, ts = 1759600000123 TTL 2 x (capacity / refill rate) -- rules: a small table or config file, cached in every gateway rules(plan, window, limit, burst)
-- token bucket in one round trip (KEYS[1] = rl:{key}; ARGV = rate, capacity, now_ms, cost) local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts') local rate, cap, now, cost = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4]) local tokens = tonumber(b[1]) or cap local ts = tonumber(b[2]) or now tokens = math.min(cap, tokens + (now - ts) / 1000 * rate) -- refill for the time elapsed local ok = tokens >= cost if ok then tokens = tokens - cost end redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now) redis.call('PEXPIRE', KEYS[1], math.ceil(cap / rate * 2000)) return {ok and 1 or 0, tokens}

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.

Deep dive: where the limiter lives, sharding and hot keys
  • In each server's memory only. No network call, zero added latency. Each server enforces limit ÷ servers, exact only if the load balancer spreads every client evenly; a client hitting few servers is throttled too hard, one hitting all of them less. Rejected as the only layer; kept as a coarse local backstop for when Redis is unreachable.
  • A central store (Redis), one atomic call per request. Accurate, one round trip. Chosen.
  • Batching: each server takes a lease of N tokens from the central store and spends them locally. Fewer round trips, slightly over-admits when leases go unused. Kept in reserve for hot keys at 10× traffic.

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.

What real companies built: Stripe, Cloudflare, GitHub

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).

Failure modes, and what interviewers listen for
What failsWhat happensDefence
Redis node down or slowChecks time outFail open after a few ms; local backstop limits; breaker; replica promotion
Cache eviction of countersLimits silently reset (GitHub's Memcached problem)A dedicated store with no eviction (maxmemory-policy noeviction) or enough memory
Replica readsStale or not-yet-expired countsRead and write counters on the primary; store explicit reset times
A bad ruleLegitimate traffic rejected at scaleDark launch (log would-be rejections first), a kill switch per limiter
Clock skew between gatewaysToken refill computed wronglyUse the Redis server's TIME inside the script
What interviewers listen for
  • You named the race between read and write and made the check atomic (Lua or INCR), in one round trip.
  • You chose fail-open and explained why a limiter must never be the outage.
  • You said what local-only limiting gets wrong (limit × servers) and where it is still useful.
  • You knew per-data-centre counting (Cloudflare) versus global counting is a trade-off, not a mistake.
  • You mentioned hot keys and dark launches.

Design 3Chat and messaging: WebSockets, fan-out, ordering, presence, storage

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.

Requirements
Functional
  • One-to-one and group conversations (both called channels), groups up to a few thousand members.
  • Real-time delivery to online members; offline members catch up on return and get a push notification.
  • Full scrollable history; presence (online dots); read receipts.
Non-functional
  • 50 million daily users, 40 messages each a day, 20% connected at the peak (illustrative).
  • Delivery under 500 ms for online members.
  • Never lost once acknowledged; order within a channel the same for everyone; history kept forever.

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 design, built step by step: from polling to channel servers and partitioned storage

  1. The naive design: clients poll an HTTP API. Each app asks "anything new?" every 5 seconds; the service reads new messages from one Postgres table.
  2. Bottleneck: 2 million polls a second, almost all empty. 10 million connected clients ÷ 5 s = 2,000,000 requests a second, 43 times the real message rate, and messages still wait up to 5 seconds.
  3. Fix: persistent WebSocket connections. Each client holds one WebSocket to a gateway server, which can push the moment a message arrives. About 100 gateways at a conservative 100,000 connections each.
  4. Bottleneck: which gateway holds the recipient? A message arrives at gateway 17; the recipients sit on gateways 3, 58 and 90. Something must know who is where and fan out.
  5. Fix: channel servers on a hash ring; push for the offline. Each channel is owned by one channel server, chosen by consistent hashing; gateways subscribe for their users and receive each message once per gateway. The channel server assigns the order. Offline members get a push notification.
  6. Bottleneck: 657 TB a year in one database. 46,000 writes a second at peak and history kept forever: no single Postgres holds it, and a busy channel is a hot spot.
  7. Fix: a wide-column store keyed by channel and time. Partition by (channel_id, time bucket), sort by message id inside: Discord's key. Reads of "the latest 50" hit one bounded partition.
  8. Bottleneck: presence: 333,000 heartbeats a second. Every connection reports "still here" every 30 s, seven times the message rate; naively each change fans out to every contact.
  9. Fix: presence as TTL keys, sent only to watchers, batched. A heartbeat refreshes a key that expires on its own; changes go only to people looking, in batches, and may be seconds stale.

The decisions that matter

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.

API and data model (frames over the WebSocket, Discord's storage key)
// over the WebSocket, as small JSON frames client -> {"op":"send", "channel":"c_42", "client_msg_id":"7f3a...", "text":"hi"} server -> {"op":"ack", "client_msg_id":"7f3a...", "msg_id":"1124203949381050368"} server -> {"op":"message", "channel":"c_42", "msg_id":"1124...", "from":"u_9", "text":"hi"} server -> {"op":"presence", "user":"u_9", "status":"online"} // over plain HTTP GET /v1/channels/c_42/messages?before=1124203949381050368&limit=50 history, by cursor

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).

messages PRIMARY KEY ((channel_id, bucket), message_id) -- Discord's key, below author_id, content, edited_at, ... -- bucket = time window (Discord: about 10 days), so one channel's history is many bounded partitions channel_members(channel_id, user_id, last_read_message_id) -- read receipts and unread counts sessions (in memory, e.g. Redis): user_id -> set of gateway servers holding that user's connections presence (in memory, with TTL): user_id -> online, expires unless refreshed by a heartbeat
What real companies built: Discord, Slack, WhatsApp

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.

Failure modes, and what interviewers listen for
What failsWhat happensDefence
A gateway server100,000 clients disconnect at once and reconnect at onceReconnect with jittered backoff; catch up by cursor from storage, not from the server that died
A channel serverLive delivery for its channels pausesThe 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 overloadedRecent messages served from memory; coalesced reads; batched fan-out per gateway
Lost acknowledgementThe client resends; risk of a duplicateclient_msg_id deduplication
Presence storm after an outageMillions of "online" events in secondsBatch and throttle presence; it may be stale
What interviewers listen for
  • You computed connections, not just messages, and noticed presence outweighs messaging.
  • You justified WebSockets against polling with a number.
  • Order is per channel, assigned in one place; you did not promise global order.
  • Store before acknowledging; deliver best effort; catch up by cursor.
  • The storage key follows the read pattern (channel and time), and you named the hot-partition risk.

Design 4News feed and timeline: fan-out on write against on read, and celebrities

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.

Requirements
Functional
  • Post a short message; follow and unfollow.
  • Home timeline: newest posts from followed accounts, paginated.
  • Out of scope at first: ranking, search, replies.
Non-functional
  • Twitter's published scale (2012): "150M world wide active users, handles 300K QPS to generate timelines"; "5K/sec daily average; 7K/sec daily peak; >12K/sec during large events" for posts; "30b deliveries / day" (High Scalability, 2013-07-08, notes on Raffi Krikorian's QCon 2012 talk Timelines at Scale; the blogger's notes, not a transcript).
  • Timeline reads in hundreds of ms end to end; a new post visible to followers within seconds.

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 design, built step by step: on read, on write, then the hybrid

  1. The naive design: fan-out on read. Each timeline request looks up who you follow, fetches each account's recent posts and merges them. Posting is one insert.
  2. Bottleneck: 22.5 million index lookups a second. 300,000 timeline reads a second, each touching about 75 accounts. Measured on a laptop: the join took 2.9 ms against 0.085 ms for a precomputed list (34 times slower).
  3. Fix: fan-out on write into cached timelines. A post goes on a queue; fan-out workers push its id into each follower's timeline list in Redis (800 ids, 3 copies). A read is one lookup.
  4. Bottleneck: celebrities: 31 million deliveries for one post. One post by the biggest account is 93 million inserts with 3 copies; reported to take up to 5 minutes, delaying everyone else's posts behind it.
  5. Fix: the hybrid: no fan-out above a threshold. Celebrity posts are stored once and merged into each reader's timeline at read time: a handful of extra lookups per read, not millions of writes per post.
  6. Bottleneck: 2.9 TB of RAM for every user's timeline. 150 million users × 800 ids × 8 bytes × 3 copies, most of them for users who will not open the app today.
  7. Fix: cache only active users; rebuild on login. Inactive users' timelines are dropped and rebuilt from the follow graph when they return: one slow first read instead of terabytes of idle memory.

The two strategies, measured

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 decision that matters: celebrities, and the hybrid

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.

The lesson that generalises: on write or on read is where to spend work

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).

A precomputed timeline reads times faster; the price is paid when a popular account posts. PostgreSQL 16.2 on a laptop, 10,000 users following 100 accounts each, 100,000 posts

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.

All timings, with p99 and the table's size
API and data model
POST /v1/posts {"text": "..."} -> 201 {"id": "..."} POST /v1/follows {"followee": "u_7"} GET /v1/timeline?cursor=...&limit=50 -> {"items": [...], "next_cursor": "..."}
posts(id BIGINT PRIMARY KEY, author_id, created_at, text) -- id is time-ordered (Snowflake) follows(follower_id, followee_id) + an index on followee_id -- "who must receive this post?" timeline:{user_id} -> list of up to 800 post ids, newest first -- in Redis, 3 copies
Deep dives: deletes and unfollows, and how ranking changes the question

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).

Failure modes, and what interviewers listen for
What failsWhat happensDefence
A celebrity posts (or many at once, during a live event)Fan-out queue backs up; everyone's delivery slowsHybrid: no fan-out above the threshold; delivery queue per priority
Timeline cache node lostThose users' timelines missingThree copies; rebuild from the graph on demand
Traffic spike 25× average (Twitter's 2013 record)Write path and fan-out overwhelmedAccept posts into a durable queue first; fan out as capacity allows (root Case files: Twitter 2013)
Deleted post still visibleIds remain in millions of listsFilter against a deleted-ids set at read time; clean up lazily
What interviewers listen for
  • You computed the read-to-write ratio first and let it choose fan-out on write.
  • You raised the celebrity problem yourself and proposed the hybrid, with a threshold.
  • You estimated the timeline cache memory and trimmed it (cap at N entries, active users only).
  • Deletes, unfollows and ranking were at least mentioned.

Design 5An LLM gateway for a company: routing, quotas, fallbacks, cost

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.

Requirements
Functional
  • One OpenAI-compatible API for every model, so existing SDKs work.
  • Per-team keys, budgets, rate limits, usage and cost.
  • Routing to vendors and self-hosted models, with automatic fallback.
  • Personal data removed before it leaves the company; an audit log of every call.
Non-functional
  • 10,000 employees, 40% using AI daily, 30 requests each, plus 400,000 automated requests a day (illustrative).
  • Adds under 50 ms before the first token; streams pass through unbuffered.
  • More available than the providers behind it; spend correct to the cent per team per month.

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.

The design, built step by step: from keys in every service to one front door

  1. The naive design: every team calls the vendor directly. Each team has its own API key in its own config, its own retry code, and a share of one invoice.
  2. Bottleneck: nobody knows who spends what, and keys are everywhere. About $4,200 a day arrives as one bill. A leaked key in a repository can only be revoked for everyone at once.
  3. Fix: one gateway, virtual keys, usage events. Teams get gateway keys; the gateway holds the real ones. Every call emits a usage event (team, feature, model, tokens, cost) to a queue and a warehouse.
  4. Bottleneck: one runaway script spends the month. A loop calling a large model with 8,000-token outputs can burn a team's monthly budget overnight, and request counts would not notice.
  5. Fix: budgets and limits counted in tokens. Reserve input plus max_tokens before the call, settle after; per-team tokens per minute and monthly dollars, with atomic counters as in design 2.
  6. Bottleneck: the vendor has an outage. Every AI feature in the company fails together, and each team's SDK retries on top of the others.
  7. Fix: ordered fallbacks, one retry layer. Each alias has a route: vendor A, then vendor B, with timeouts and cooldowns. Only the gateway retries; the fallback is exercised regularly so it works when needed.
  8. Bottleneck: customer data leaves the company. Employees paste customer records into prompts that go to an outside vendor, against the data policy.
  9. Fix: redaction and policy routing. Personal data is replaced before external calls and restored in the response; teams whose data may not leave are routed to a self-hosted model.
  10. Bottleneck: the gateway is now the single point of failure. Every model call in the company passes one service: its outage is everyone's outage.
  11. Fix: stateless replicas in two zones. State lives in the budget store and the warehouse; replicas are interchangeable. If the budget store fails, allow requests under a local cap (fail open, as in design 2).

The decision that matters: what to build first, in order

  1. Virtual keys and usage events. The gateway holds the real provider keys; teams get gateway keys; every call emits a usage event to a queue and a warehouse. This alone answers "who spends what" and is the precondition for everything else.
  2. Budgets and limits in tokens. A request's cost is unknown until it finishes, so reserve the worst case (input tokens plus 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).
  3. Fallbacks with one retry layer. An ordered route per alias (vendor A, vendor B, a self-hosted model), a timeout per hop, a cooldown for a failing route. Retry in the gateway only, or retries multiply (the 243× case in Reliability engineering, Retries); what a fallback costs in time is measured in Gateways and routing, sections 3 and 4.
  4. Data protection. Redact personal data before external calls according to each team's policy; route data that may not leave to self-hosted models. Policy beyond redaction belongs to Guardrails.
  5. Cost cuts, only after measuring: prompt (prefix) caching, tier routing of easy requests to a cheaper model, batch APIs for pipelines that can wait (ML system design, sections 4, 6 and 7).

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.

API and data model
POST /v1/chat/completions OpenAI-compatible; the gateway key identifies the team Authorization: Bearer gw_team-support_... {"model": "fast" | "smart" | "vendor/model-2026-05-01", "messages": [...], "stream": true, "metadata": {"feature": "ticket-triage"}} -> streamed SSE chunks, then a usage record -> 429 + Retry-After when the team's tokens-per-minute or budget is exhausted -> 503 when every route in the fallback chain failed GET /v1/usage?team=support&from=2026-10-01 cost and tokens per team, feature, model
teams(id, monthly_budget_usd, tpm_limit, allowed_models, pii_policy) keys(hash, team_id, created_at, revoked_at) store a hash, never the key routes(alias, ordered list of (provider, model, weight), timeout_ms) budget counters (Redis): spend:{team}:{month}, tokens:{team}:{minute} usage_events -> queue -> warehouse: (request_id, team, feature, model, tokens_in, tokens_out, cost, latency, status)
What real gateways do: Uber, Wealthsimple, LiteLLM's knobs

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).

Trade-offs rejected, failure modes, and what interviewers listen for
  • A shared client library instead of a service. No extra hop, but every language needs a copy, keys still live in every service, and budgets cannot be enforced across processes. Rejected: the extra few milliseconds are nothing against seconds of generation.
  • Logging full prompts and responses forever. Useful for evaluation, dangerous for privacy. Chosen instead: metadata always; content sampled, redacted, with a retention limit and access controls.
  • Exact-match response cache for everything. Cheap, but personal answers can leak between users. Only per team and per opted-in feature; semantic caching only with a measured false-hit rate (ML system design, section 7).
  • Building it. Build when your policy needs outgrow the off-the-shelf gateways.
What failsWhat happensDefence
A provider outage or 429 stormEvery product using that model fails at onceFallback chain with cooldowns; tested regularly with real traffic (a fallback that has never carried load fails when needed)
The gateway itselfEvery AI feature in the company stopsStateless replicas in two zones; budget store failure means fail open with a local cap, as in design 2
A runaway scriptBurns a month's budget overnightPer-key token limits and budget alerts at 50%, 80%, 100%
Provider silently changes an aliasQuality changes with no deployPin dated versions in routes; log the model version in every usage event; evaluate before switching (Production eval engineering)
Buffering proxyUsers see nothing until the whole reply is doneStream pass-through end to end, long idle timeouts
What interviewers listen for
  • You noticed throughput is small and moved the discussion to cost, keys, data rules and reliability.
  • Limits and budgets are counted in tokens, reserved before and settled after.
  • One retry layer, ordered fallbacks, and how you would test the fallback.
  • Usage events off the request path, attributed per team and feature.
  • A clear build order, and a buy-versus-build opinion.

Design 6A RAG service over company documents: ingestion, embeddings, vector index, freshness, evaluation

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.

Requirements
Functional
  • Ask in a chat box; get an answer with links to the source passages.
  • Sources: wiki, shared drives, tickets (5 million documents, illustrative).
  • Answers use only documents the asker may read.
Non-functional
  • An edited document is searchable within 10 minutes.
  • First token in under 3 seconds at p95; 50,000 questions a day.
  • Measured answer quality, tracked over time.

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.

The design, built step by step: from one prompt to an ingestion pipeline, hybrid retrieval and an eval set

  1. The naive design: keyword search, top results pasted into the prompt. A nightly export feeds a keyword index; the top 5 matching documents are pasted, whole, into the prompt.
  2. Bottleneck: whole documents miss and overflow. Questions phrased differently from the text find nothing; whole documents waste the context window and dollars on irrelevant pages.
  3. Fix: chunks, embeddings and a vector index. Documents are split into about 500-token chunks, embedded and indexed with HNSW; the prompt gets the 8 nearest chunks with their citations.
  4. Bottleneck: vectors miss exact terms. "Error E1402" or a product code is a rare string, not a meaning: nearest-neighbour search often ranks it low.
  5. Fix: hybrid retrieval and a reranker. BM25 and vectors run together, results merged, then reranked. Anthropic measured 49% fewer retrieval failures from contextual embeddings plus contextual BM25, 67% with reranking.
  6. Bottleneck: answers a day out of date. The nightly export means an edit made at 09:00 is invisible until tomorrow, against a 10-minute requirement.
  7. Fix: change events through an idempotent pipeline. Connectors emit "document changed"; workers re-chunk and upsert by (doc_id, chunk_no, version), deleting leftover chunks. About 8 chunks a second on average.
  8. Bottleneck: someone sees a document they may not open. Retrieval searches everything; the LLM quotes a salary spreadsheet to a person outside HR.
  9. Fix: permission filters at retrieval. Each chunk carries its document's access groups; queries filter by the asker's groups (watch the post-filter trap in approximate indexes). Permission changes flow through the same pipeline, with priority.
  10. Bottleneck: is it right? nobody knows. A prompt change "felt better" in three tries; nobody can say whether retrieval or generation got worse last week.
  11. Fix: a golden set, scored separately for retrieval and generation. Real questions with the documents that answer them; recall at k for retrieval, faithfulness for answers; run before every change and on sampled traffic.

The decisions that matter

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.

API and data model
POST /v1/ask {"question": "How do I rotate the staging database password?", "conversation_id": "..."} -> SSE stream of the answer, then {"citations": [{"doc_id": "...", "chunk": 3, "url": "...", "title": "..."}]} POST /v1/feedback {"answer_id": "...", "rating": "down", "reason": "outdated"} // ingestion is driven by the sources' change events, not by an API users call
documents(doc_id, source, url, title, version, updated_at, acl_groups TEXT[]) chunks(doc_id, chunk_no, version, text, embedding VECTOR(1536), acl_groups TEXT[], PRIMARY KEY (doc_id, chunk_no)) -- HNSW index on embedding; GIN index on acl_groups; full-text index on text for keyword search eval_set(question, expected_doc_ids, reference_answer) -- the golden set
Deep dive: the vector index, pgvector or a dedicated store

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.

What real companies built: LinkedIn, DoorDash, Uber

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.

Failure modes, and what interviewers listen for
What failsWhat happensDefence
Permission sync lagsSomeone sees a passage they should notPermission events on a priority queue; deny by default for unknown groups
Connector misses eventsStale answers, silentlyNightly reconciliation; alert on age of the newest indexed change per source
Embedding model changedOld and new vectors mixed: garbage retrievalStore model version per vector; re-embed into a new index, switch atomically
Index outgrows memoryLatency jumps by orders of magnitudehalfvec or fewer dimensions; shard; watch index size against RAM
Prompt injection inside a documentA document instructs the modelTreat retrieved text as data; guardrails; restrict tools (Guardrails)
What interviewers listen for
  • You sized the vectors and saw memory, not queries, is the constraint.
  • Ingestion is an idempotent, versioned pipeline with deletes handled.
  • Permissions enforced at retrieval, with the post-filtering trap named.
  • Hybrid retrieval and reranking, justified by what vectors miss.
  • An evaluation plan that separates retrieval from generation.

Design 7A distributed job scheduler: cron for a whole company

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.)

Requirements
Functional
  • Register recurring (cron syntax) and one-off delayed jobs; cancel; pause.
  • Run each due job on a worker and record each run (start, end, result, logs link).
  • Retries with backoff; alert the owner after N failures.
Non-functional
  • 10 million runs a day, 30% of them scheduled at the top of an hour (illustrative).
  • Start within a few seconds of the due time (Dropbox's target: 95% within 5 s, below).
  • No double runs of non-idempotent jobs, no silent skips; survives the loss of any machine.

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.

The design, built step by step: one crontab, two schedulers, then a queue and jitter

  1. The naive design: cron on one machine. One server runs a crontab: at the due minute it starts each job as a local process. No history, no retries.
  2. Bottleneck: one machine: when it dies, nothing runs, silently. A reboot during 02:00 skips the nightly jobs, and nobody notices until the reports are missing.
  3. Fix: a jobs table and two scheduler machines. Schedules and runs live in a database; two scheduler machines read what is due, so either can die.
  4. Bottleneck: both schedulers run the same job. Both read "job 7 is due at 02:00" and both start it: the invoice email goes out twice.
  5. Fix: claim rows atomically; one row per intended run. FOR UPDATE SKIP LOCKED divides due rows between schedulers; the runs table's key (job, scheduled time) makes a second launch a conflict, not a run.
  6. Bottleneck: the scheduler runs the work, and a slow job blocks launches. A 40-minute export holds a scheduler thread while hundreds of other launches wait; a crash mid-job loses it.
  7. Fix: schedulers only enqueue; workers lease runs. Due runs go on a queue; workers lease them and heartbeat. A dead worker's lease expires and the run is retried (at-least-once, so jobs are idempotent).
  8. Bottleneck: 125,000 runs due in the same second. 30% of the day's runs are "0 * * * *": every hour, one second needs 2,500 machines' worth of slots and the queue explodes.
  9. Fix: deterministic jitter over a minute. Jobs that do not need the exact second get a fixed offset from a hash of their id: about 2,100 starts a second instead of 125,000 at once.

The decisions that matter

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).

Skip or double-run? Say which you prefer, and why

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.

API and data model (overlap and misfire policies)
POST /v1/jobs {"name": "rebuild-index", "schedule": "0 2 * * *", "timezone": "Europe/London", "target": {"queue": "search", "payload": {...}}, "max_runtime_s": 3600, "overlap": "skip" | "queue" | "allow", "misfire": "run_once" | "skip"} POST /v1/jobs/{id}/pause DELETE /v1/jobs/{id} GET /v1/jobs/{id}/runs?cursor=...

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.

jobs(id, schedule, timezone, next_run_at TIMESTAMPTZ, target, overlap, misfire, paused) INDEX ON (next_run_at) WHERE NOT paused runs(job_id, scheduled_for, attempt, state, lease_until, started_at, ended_at, result, PRIMARY KEY (job_id, scheduled_for)) -- one row per intended run: the idempotency key
Deep dive: time is harder than it looks
  • Time zones and daylight saving: "02:30 every day" does not exist on the spring-forward day in London and happens twice on the autumn one. Store the job's time zone, compute next_run_at in UTC with a real time-zone library, and decide the rule for missing and repeated local times.
  • Thundering herd: add deterministic jitter (hash of the job id modulo the spread) to jobs that do not need an exact minute, so the same job runs at the same offset every hour.
  • Clock skew: scheduler machines disagree by milliseconds; use the database's now() as the one clock for "due".
What real companies built: Google cron, Dropbox ATF, Slack's job queue, Netflix Maestro

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).

Failure modes, and what interviewers listen for
What failsWhat happensDefence
Scheduler instance dies mid-claimIts transaction rolls back; another instance claims the rowsClaim, insert run and advance next_run_at in one transaction
Worker dies mid-runLease expires; the run is retriedIdempotent jobs; heartbeats; max_runtime kills stuck runs
Scheduler down for an hourMissed runsPer-job misfire policy (run once now, or skip and alert)
Top-of-hour burstQueue backs up; jobs start lateJitter; bounded queues with priorities; autoscale workers ahead of the hour
A job that always failsRetries forever, crowding othersCapped retries with backoff, dead-letter, page the owner
What interviewers listen for
  • You separated "decide what is due" from "do the work" with a queue between.
  • You made a run unique by (job, scheduled time) and explained at-least-once execution.
  • You found the top-of-the-hour spike from the numbers and answered it with jitter.
  • You chose between skipping and double-running per job, citing why.
  • Time zones, daylight saving and misfires were mentioned.

How to practise

Reading worked designs builds recognition; only producing designs under a clock builds the skill.

  1. Timed drills, out loud. Pick a prompt in the Design drill tab, start the 45-minute clock, say each step before revealing it, write the estimate on paper, then tick the self-check list honestly. One drill a day for two weeks beats ten designs read in an evening.
  2. Redo the seven designs from a blank page a week later. If you cannot reproduce an estimate, you understood the answer, not the method.
  3. Change one requirement and redesign (editable destinations; end-to-end encrypted chat; a ranked feed; jobs that depend on each other): what interviewers do in the last ten minutes.
  4. Read one real write-up a week from the root's Case files or the sources here, and write it in this page's template: requirements, numbers, boxes, what broke.
  5. Practise with a person once you can finish in time: a mock interviewer interrupts, which solo drills cannot train.

The common traps (open any)

Drawing boxes before asking a single question
The first five minutes decide the design. "How many users? Read-heavy or write-heavy? What may be stale, lost or duplicated?" Each answer removes a branch of possible designs.
Estimates that change nothing
Arithmetic is worth time only when its result moves a decision: the code length, whether to shard, whether to push or poll. State the decision the number made.
Scaling what does not need it
Sharding a database that takes 230 writes a second, or Kafka for 18 requests a second, signals that you add components by habit. Say "one Postgres is enough until X, and here is how I would split it then".
Naming products instead of mechanisms
"Use Kafka" is not a design. "A durable, partitioned log so the fan-out can lag behind posts without losing them, keyed by author so order per author holds" is. Products are fine once the mechanism is said.
Ignoring failure
For every box, say what happens when it is slow or gone. Most interview designs fail on "what if the cache dies?" or "what if the worker crashes after charging the card?". The answers are in Reliability engineering.
Promising exactly-once, global order or strong consistency everywhere
Each costs latency or availability. Say which data needs which guarantee: per-channel order, at-least-once plus idempotency, stale presence. CAP is about what happens during a network partition, not "pick two" (Distributed systems fundamentals, CAP stated correctly).
Going deep too early, or never
Get a complete, simple design on the board first (about 15 minutes in), then deepen the two parts the numbers flagged. A beautiful ID generator with no storage design is an incomplete answer.
Silent thinking and no trade-offs
The interviewer grades reasoning they can hear. "I considered X, chose Y because Z, and I would revisit if W" is the sentence to practise.
Forgetting observability and rollout
How would you know it works in production, and how would you ship a change safely? One sentence each (Observability; canaries in Reliability engineering, Deployment safety).
Glossary (every term this page defines)
At-least-once: a delivery or execution guarantee where nothing is lost but something may happen twice; paired with idempotency.
Base62: writing numbers with 62 symbols (0 to 9, a to z, A to Z); 7 characters give 3.52 trillion codes.
BM25: a classic keyword ranking function based on how often query terms appear in a passage.
Cache-aside: read the cache; on a miss read the database and fill the cache.
Channel server: in chat, the server that owns a conversation, orders its messages and forwards them to subscribed gateways.
Chunk: a passage of a document (a few hundred tokens) embedded and retrieved as one unit.
Consistent hashing: mapping keys to servers so adding or removing a server moves only a small share of keys.
Cron: the Unix scheduler, and its five-field schedule syntax (minute, hour, day, month, weekday).
Design document: the written proposal for a system, reviewed before building; the work-world form of the interview.
Embedding: a vector of numbers representing a text, close to the vectors of similar texts.
Fail open: when a check cannot run, allow the request (a rate limiter); fail closed means deny (a permission check).
Fan-out on write / on read: copy a post to every follower's timeline when posted, or assemble each timeline when read.
Functional / non-functional requirements: what the system does / how much, how fast, how reliably, how cheaply.
Golden set: a fixed set of questions with known good answers or sources, used to evaluate changes.
HNSW: a layered graph index for approximate nearest-neighbour search over vectors.
Hot partition (hot key): one key receiving a disproportionate share of traffic.
Hybrid retrieval: keyword and vector search combined, often followed by reranking.
Idempotency key: a client-chosen id that makes a retried request return the first result instead of acting twice.
Jitter: a random delay added so that many clients or jobs do not act at the same instant.
Lease: a claim that expires unless renewed; lets a crashed holder's work be taken over.
Little's law: items in a system = arrival rate × time each stays.
LLM gateway: one internal service every model call passes through, for keys, limits, routing, redaction and cost.
Lua script (Redis): code that Redis runs atomically, so a read-compute-write cannot interleave with other clients.
Presence: whether a user is online, kept as a key with a TTL refreshed by heartbeats.
Race condition: a bug where the result depends on the timing of concurrent operations (check, then act).
RAG: retrieval-augmented generation; answer from retrieved passages, citing them.
Rate limiter: caps one client's request rate; excess gets 429.
Redirect (301, 302): an HTTP answer telling the browser to go elsewhere; 301 is cacheable by default, 302 is not.
Rerank: re-order retrieval candidates with a slower, more accurate model.
Snowflake ID: a 64-bit id of timestamp, machine number and sequence, unique without coordination and sortable by time.
TTL: time to live; how long a cached or stored entry lasts before it expires.
Vector index: a structure that finds the nearest vectors without comparing against all of them.
WebSocket: a long-lived, two-way connection over TCP that starts as an HTTP upgrade.