Courses / System Design Interview / Chapter 25
Module 5 · AI Building Blocks and Review · Chapter 25 of 49
Putting the Blocks Together: Timed Practice
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Back-of-the-Envelope Estimates, DNS: Turning Names into Addresses, Load Balancers, Databases: Choosing, Replicating and Partitioning, Design a Distributed Key-Value Store, Content Delivery Networks, Unique IDs: Sequencers, UUIDs and Snowflake IDs, Distributed Monitoring: Metrics, Logs and Traces, Distributed Caches, Distributed Message Queues, Publish-Subscribe Systems, Rate Limiters, Blob Stores, Distributed Search, Distributed Logging, Distributed Task Schedulers, Sharded Counters and AI Building Blocks: Inference, Embeddings, Retrieval and Agents. Next up: Design a Video Platform like YouTube.
Part 1 · Matching requirements to blocks
From a sentence to a block
The blocks chapters taught one part at a time. A real problem arrives as a sentence, and the first skill is to hear which block that sentence is asking for.
Most requirements contain a verb or a number that gives it away. Words like "find by name", "the same file for everyone", "slow job", "tell the other services" or "no more than three a minute" each point to one block. The table below is a lookup from what the system needs to the block that provides it. The last column gives the chapter to reread if the row is unfamiliar.
| The system needs to | Block | What the block gives | Chapter |
|---|---|---|---|
| Reach servers by a name that can move | DNS | Name to address, with a TTL | dns |
| Serve the same file to many users far apart | CDN | Copies near the user | cdn |
| Spread requests over several servers and drop the dead ones | Load balancer | One address, health checks | load-balancers |
| Keep records that survive a machine and answer queries | Database | Storage, transactions, replication | databases |
| Look up one value by key at very large scale | Key-value store | Partitioned, replicated lookups | key-value-store |
Turning requirements into an order
Take any requirement and ask three questions about it. Who is waiting? If a person is waiting for the result, the block is on the request path and must be fast: cache, CDN, database read. If nobody is waiting, it belongs on the async path: queue, topic, scheduler. How much? A number such as a rate or a size decides whether one machine is enough, and the estimates chapter gives the method. What happens if it fails? The answer decides whether you need a replica, a retry, a dead-letter queue or a fallback.
Then write the blocks in the order a request meets them. For a photo site, a request meets DNS, then the CDN, then a load balancer, then an app server, then a cache, then the database, and a photo upload also goes to a blob store and to a queue for resizing. Every block you name should come with its reason, which is the "what the block gives" column in the table, and with its cost, such as staleness for a cache or delay for a queue.
Two habits keep the answer short and correct. Name the smallest set of blocks that meets the requirement, because each extra block is something to run and something that fails. And say what you are not building yet. A first design for a small site does not need a key-value store, a search index and a task scheduler, and a design that lists all of them has not decided anything.
A requirement says "send the customer a receipt after payment, and do not slow down the payment screen". Which block, and on which path?
- A queue on the async path: the payment service writes the job and replies, and a worker sends the receipt.
- Nobody is waiting for the receipt, so it must not sit on the request path.
A requirement says "show the number of likes on a post that millions are liking right now". Which block?
- A sharded counter: writes are spread over several rows and the total is summed on read, or cached.
- One row would be a hot key and the bottleneck.
Why name the smallest set of blocks that works?
Part 2 · Trade-offs that recur
The same bargains in different clothes
Almost every block in this course is a bargain: you buy something and you pay for it with something else. A few bargains recur so often that it helps to recognise them by name.
Freshness against speed. A cache, a CDN edge and a read replica all answer faster by answering from a copy, and a copy can be old. In the cache chapter the same code gave a 4.7% hit ratio on a uniform workload, where few reads repeat, and 57.4% on a skewed one, where popular items are read again and again: the speed is real only when reads repeat. The cost is the window in which a copy is stale, which a TTL or an invalidation controls.
Push against pull. Push sends the work to the receiver when it appears, which is fast but needs the receiver to keep up. Pull lets the receiver ask when it is ready, which gives it control and adds a little delay. A queue worker that polls, a log subscriber that reads from an offset and a client that polls a score endpoint are all pull. A webhook, a push subscription and a server-sent update are all push.
Precompute against compute on read. Do the work before anyone asks, and reading is cheap but the stored results may be old and take space. Do the work when someone asks, and the result is fresh but each read pays. A timeline built when a post is written, a search index built from documents, and a result page copied into a cache before the exam results open are all precomputing.
Synchronous against asynchronous. The caller waits and gets a real answer, or the caller carries on and gets a promise. In the message queue chapter's simulation, a three-second spike lost 600 of 2,300 orders when the service was called directly, and lost none when a queue held the backlog. The price was a delay of up to three seconds.
Copies against consistency. More copies give more reads and more safety, and make it harder to keep them equal. Replication lag, stale caches and duplicate deliveries are all forms of it.
Choosing, with numbers
Naming a trade-off is the start. The next step is to put a number on both sides. For the bargain between speed and freshness, how old may the data be? A product price can be a minute old and a seat count cannot be a second old. For the bargain between asynchronous and synchronous, how long may the user wait for the result? Three seconds is fine for a receipt and wrong for a login.
A useful rule is to take the most expensive guarantee only where it is needed. Keep the seat count in the database and read it inside a transaction. Cache the product description with a one-minute TTL. Count likes with a sharded counter and accept a total that lags by a second. One system can use three different answers to the same bargain, because the data has three different needs.
A product page shows a price that may be one minute old, and a seat count that must be exact. How do you treat them differently?
- Cache the price with a TTL of about a minute. Read the seat count from the database inside the booking transaction, uncached.
In the message queue chapter run, what did the queue convert a loss of 600 orders into?
- A delay of up to about three seconds for the orders that arrived during the spike.
Why is a read replica an example of freshness against speed?
- Reads from it are fast and spread the load, but it applies changes after the leader, so a read can return an older value.
Part 3 · Timed drill 1: a results page on results day
The prompt and the clock
A university will publish the results of 4 lakh students at 10 am. Students enter a roll number and see their marks. Design the system so that it stays up for the first fifteen minutes. This is a drill: set a timer for 15 minutes, answer on paper before reading the model answer, and then compare.
| Minutes | What to do |
|---|---|
| 0 to 2 | Requirements: what is a lookup, what must never happen, what can be late |
| 2 to 5 | Estimates: users in the first minutes, lookups per second, bytes, servers |
| 5 to 10 | Design: the blocks in request order, with a reason for each |
| 10 to 13 | One deep dive: the part most likely to fail |
| 13 to 15 | Failure and trade-offs: what breaks and what you accept |
Use these assumptions, and write down any you add. 80% of students check in the first 15 minutes. Each makes two lookups, one try and one retry or second tab. The busiest second is three times the average. A page is 0.6 MB and is downloaded once per student. One app server handles 300 requests a second and one database replica 1,000 reads a second. The assumptions are invented for the drill. What matters is that the answer states them.
The estimate
The script below turns the assumptions into numbers. It is the arithmetic you would do on paper, written down so that every figure can be traced.
import math students = 400_000 # all candidates in the university early = 0.80 # share who check in the first 15 minutes window = 15 * 60 # seconds peak_factor = 3 # the busiest second against the average lookups_each = 2 # one try plus one retry or a second tab page_mb = 0.6 # html, scripts and images, once per user users = students * early avg_rps = users * lookups_each / window peak_rps = avg_rps * peak_factor print(f"users in window {users:.0f}") print(f"lookups per second avg {avg_rps:.0f}, peak {peak_rps:.0f}") print(f"page bytes in window {users * page_mb / 1000:.0f} GB, " f"{users * page_mb * 8 / window / 1000:.1f} Gbit/s average") app_rps, replica_rps = 300, 1000 # assumed capacity of one machine print(f"app servers at peak {math.ceil(peak_rps / app_rps)}") print(f"replicas, no cache {math.ceil(peak_rps / replica_rps)}") cache_mb = students * 1 / 1000 # 1 KB per precomputed result print(f"all results cached {cache_mb:.0f} MB, database reads ~ 0")
l3_results.py: the estimate for the results page
It was run with Python 3.12.10. It is deterministic arithmetic.
users in window 320000 lookups per second avg 711, peak 2133 page bytes in window 192 GB, 1.7 Gbit/s average app servers at peak 8 replicas, no cache 3 all results cached 400 MB, database reads ~ 0
The first 15 minutes bring 3.2 lakh users, which is 711 lookups a second on average and 2,133 at the busiest second. The page itself is the heavier load: 192 GB in 15 minutes, 1.7 Gbit/s on average. Eight app servers cover the peak lookups. Without a cache, three database replicas would cover them, so the database is not the biggest problem by arithmetic alone. The risk is that the real peak is higher than the assumed one, and that every lookup is a database read at the worst moment.
The model answer
Requirements. Functional: look up marks by roll number, show a result page. Non-functional: a lookup must return the right student's marks and never another's, the site must stay up at 10 am, and the data does not change after publication. That last point is the key: the data is read-only, so it can be copied freely.
Design, in request order. DNS gives the site's name an address with a short TTL, so that a problem can be routed around. A CDN serves the page, scripts and images from the nearest edge, which removes 192 GB of traffic from the servers. A load balancer spreads lookups over eight to ten app servers, with a spare for failures. The app servers read from a cache. A job copies every student's result into the cache before 10 am, so that no lookup needs the database. The database remains the source of truth and takes reads only during that warm-up and if the cache fails.
Watch for the database: before 10 am a job copies every result into the cache
Read it as steps
Page files come from the edge. Every result was copied into the cache before the page opened, so the database stays idle.
Deep dive and trade-offs
Deep dive: the cache warm-up. The cache holds 4 lakh results of about 1 KB each, 400 MB, which fits in memory on one machine, and two replicas protect against a failure. The warm-up runs before 10 am and a check compares the cache's record count with the database's. If the cache is empty or a node is lost at 10 am, the lookups fall back to the database, which is why the replica count matters: three replicas at 1,000 reads a second can carry the whole peak of 2,133. A rate limit per client stops one script from asking for every roll number.
Failures and trade-offs. The cost of precomputing is that the results must be final before the cache is filled, and that a correction means updating the database and the cache entry together. If a result is wrong, delete the cache entry and let the next read reload it. Accept the extra memory, since it removes the database from the busy path.
Self-check. Did you state your assumptions? Did you reach a rate in lookups a second, and a figure for bytes? Did you name what stays on the CDN and what reaches a server? Did you protect the database? Did you say what you gave up?
Why does the model answer copy all results into the cache before 10 am?
- The data does not change after publication, so it can be precomputed, and lookups then never reach the database.
- It trades 400 MB of memory for a database that stays idle at the busiest moment.
In the run, what is the busiest second's rate and how many app servers does it need?
- 2,133 lookups a second, which needs 8 app servers at 300 a second each.
What must be in place for the fallback when the cache fails?
- Enough database replicas: 3 at the assumed 1,000 reads a second each can carry the whole peak.
Part 4 · Timed drills 2 and 3: a one-time password service and a live score feed
Drill 2: one-time passwords by SMS
Set a timer for 15 minutes. Design a service that sends a six-digit one-time password to a phone and later checks it. A code is valid for five minutes, and a user may try three times. Use these assumptions: 10 lakh requests a day, a login rush ten times the average, and a message gateway that sends 20 messages a second per worker.
Both drills use one estimate script, so the numbers below can be traced.
import math # Drill 2: one-time passwords by SMS otp_day = 1_000_000 # requests a day peak_factor = 10 # a login rush against the average valid_s, record_bytes = 300, 100 # code lives 5 minutes avg = otp_day / 86_400 peak = avg * peak_factor print(f"otp requests/s avg {avg:.1f}, peak {peak:.0f}") print(f"live codes {peak * valid_s:.0f} at peak, " f"{peak * valid_s * record_bytes / 1e6:.1f} MB") print(f"sms workers {math.ceil(peak / 20)} at 20 sends/s each") # Drill 3: a live cricket score during a final viewers, poll_s, edges, ttl_s = 20_000_000, 5, 200, 2 print(f"polling requests {viewers / poll_s:.0f}/s at the edge") print(f"origin requests {edges / ttl_s:.0f}/s ({ttl_s} s edge TTL)") servers = math.ceil(viewers / 50_000) print(f"push connections {viewers} open, {servers} servers at 50000")
l4_drills.py: estimates for both drills
otp requests/s avg 11.6, peak 116 live codes 34722 at peak, 3.5 MB sms workers 6 at 20 sends/s each polling requests 4000000/s at the edge origin requests 100/s (2 s edge TTL) push connections 20000000 open, 400 servers at 50000
Model answer for drill 2. The average is 11.6 requests a second and the rush is 116. A code lives for five minutes, so at the rush about 34,722 codes are alive, which is 3.5 MB at 100 bytes each. That is tiny, so the store is a cache or a key-value store with a TTL of five minutes, and the main work is not storage. Six SMS workers cover the rush.
Drill 2: the request path
The request path is a rate limiter, then the OTP service. The limiter allows a few requests per phone number and per address in a window, since an unlimited sender can be abused to flood a person with messages or to run up the provider's bill. The service draws the code from a cryptographically secure random generator (in Python, the secrets module, not random), stores a keyed hash of it (an HMAC made with a secret that is not kept in the store) next to the phone number, sets the TTL, and puts a send job on a queue.
A plain hash would not help, because anyone holding the store could hash all ten lakh six-digit codes in moments. The keyed hash is defence in depth, a choice of this answer rather than a NIST requirement for codes sent by SMS.
SMS workers take jobs and call the gateway. Because the gateway can fail, the worker retries with backoff and jitter and, after several failures, moves the job to a dead-letter queue and tries a second gateway.
Verification recomputes the keyed hash, compares it in constant time, and counts attempts with an atomic increment, so three wrong tries lock the code. Keep a failure count per phone number as well, because a user who could simply ask for a fresh code would get unlimited guesses: NIST SP 800-63B says that generating a new secret must not reset the failed-attempt count. A correct code is deleted at once, since NIST also requires that a secret be accepted only once, and five minutes is inside its limit of 10 minutes for completing the check.
The sending is at-least-once, so a user may receive the same message twice. The client's request carries an idempotency key, so a request that is retried gets the code already pending rather than a second one.
Self-check for drill 2. Did you protect the sender with a limit? Did you avoid storing the code in plain text, and did you limit the tries per code and per phone, since a six-digit code has only ten lakh values? Did you make each code single-use? Did you put the slow gateway call on a queue? Did you say what a user sees if the gateway is down? NIST classes SMS delivery as a restricted authenticator, because a phone number can be moved to another SIM, so a strong answer also offers another factor such as an authenticator app.
Drill 3: a live cricket score
Set a timer for 15 minutes. Design the feed behind a live score on a phone app during a final. Use these assumptions: 2 crore users watching at once, an app that asks for the score every five seconds, 200 CDN edge locations, and a score that changes about once every ten seconds.
Model answer for drill 3. The same script shows the arithmetic. Two crore users polling every five seconds make 40 lakh requests a second at the edge. No origin survives that, and none needs to. The answer is that every user receives the same data, so it can be cached. If the edge keeps each response for 2 seconds, each of 200 edges asks the origin once in that time, so the origin sees 100 requests a second, not 40 lakh. The cost is that a user can be up to about 2 seconds behind.
Drill 3: the data path
The data path is short. The scorer's app writes each ball to a database. A change event goes on a topic. A small service builds the current score as one compact document, with a version number inside, and publishes it at one fixed address that the app polls. The edge caches that address with a 2 second lifetime. The cdn chapter explained how stale-while-revalidate lets an edge answer at once from an expired copy while it fetches a new one in the background, so no user waits on the origin. The figure of 100 origin requests a second assumes each edge sends one refresh per expiry, not one per waiting user, which is what that background refresh gives you.
There is an alternative: keep a connection open to every user and push each update. That means 2 crore open connections, and at an assumed 50,000 connections a server that is 400 servers just to hold them, as the script shows, before any message is sent. Pushing can deliver an update sooner than a poll would, and it costs much more, so push is reserved for the cases that need it. Polling a cached document is the cheaper default.
Self-check for drill 3. Did you notice that every user wants the same data and use that to cache it? Did you give the origin a number? Did you say how fresh the score is and why that is acceptable? Did you compare push and pull with numbers?
In drill 2, why store a hash of the code and not the code?
- If the store leaks, plain codes would be live passwords. A keyed hash cannot be reversed by trying all ten lakh codes unless the attacker also has the secret, and verification only needs to recompute and compare it.
- The five-minute life, single use and the try limits still matter, because a six-digit code is easy to guess if tries are unlimited. The failure count must survive a request for a new code.
In drill 3, how does an edge TTL of 2 seconds change the load on the origin?
- From 40 lakh requests a second at the edge to about 100 at the origin, since 200 edges each ask once every 2 seconds.
- The price is that a user can be about 2 seconds behind.
Why is push to every viewer costly in drill 3?
All chapters · Previous: AI Building Blocks: Inference, Embeddings, Retrieval and Agents