Courses / System Design Interview / Chapter 5
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 5 of 49
Building Blocks: The Parts Every Design Reuses
Builds on Non-Functional Requirements: Availability, Scale, Latency and More and Back-of-the-Envelope Estimates. Next up: DNS: Turning Names into Addresses.
Part 1 · What a building block is
The parts that keep coming back
Every large service, from a train-booking site to a video app, is assembled from the same few parts. This chapter names those parts and shows where each one sits, so that every later chapter can add one piece to a picture you already have.
A building block is a component with one narrow job and a clear contract. You send it a request in a known shape and it gives back a result with a known promise. A database promises that data you saved can be read later. A queue promises that a message you put in will be handed to a worker. You do not need to know how either works inside to use it, but you do need to know what it promises and what it costs.
Designs reuse blocks because the problems repeat. Every product with users has to turn a name into an address, spread traffic over several machines, keep data somewhere that outlives a machine, answer the same question twice without redoing the work, do slow jobs later, and let engineers see what happened. A team that solves each of these again for every product spends its time on plumbing. A team that picks a known block spends its time on what is special about the product.
Each block is also a trade. A cache makes reads faster and can return old data. A queue absorbs a spike and adds delay. Naming the cost is half of choosing the block, so the table has a column for it.
| Block | Job | What it promises | What it costs |
|---|---|---|---|
| DNS | Turns a name into an address | Clients find you without knowing addresses | Answers are cached, so changes spread slowly |
| CDN | Serves copies of content near the user | Fewer long trips to your servers | A copy can be out of date |
Three paths through a design
A design is easier to read once you sort its blocks by the path that data takes. There are three paths, and almost every system uses all of them.
A person is waiting
DNS, CDN, load balancer
App servers, cache, database
Nobody is waiting
Queues, pub-sub, schedulers
Workers that do the slow job
Where bytes and evidence live
Blob store, search index
Logs, metrics, traces
The request path carries the user's click to a response and back, and every millisecond on it is felt. The async path carries work that can finish later, such as sending an email or resizing a photo. The data and watch path holds the large files and the records of what happened, which the other two paths read and write.
The next three lessons walk one path each. Where a block has its own chapter, this chapter only places it on the map and shows one small piece of running code, so you recognise it when the chapter arrives.
What two things should you know about a block before you use it?
- What it promises: the contract on the input and the guarantee on the result.
- What it costs: the delay, the staleness or the extra part that can fail.
A cache returns an answer that was saved ten minutes ago. Which column of the table does that fall under?
- It is a cost: the answer can be out of date.
Part 2 · The request path
From a name to a row
The request path is the route a request takes while a person waits. It has the same six stops in almost every web design, and each stop can answer the request or pass it deeper.
| Step | What happens | What can go wrong |
|---|---|---|
| 1. Name lookup (DNS) | The client asks for the address behind the site's name | The answer is old or slow to arrive |
| 2. Edge (CDN) | A nearby cache answers if it holds a copy, otherwise it forwards the request | The copy is stale |
| 3. Front door (load balancer) | Picks one healthy server for this request | It picks a busy server, or it is down itself |
| 4. App server | Runs your code and keeps no user state of its own | The code is slow or crashes |
| 5. Cache | Looks in fast memory for the answer first | A miss sends the request on to the database |
| 6. Database | Holds the stored truth | A slow query or a lost connection |
Watch for the first step: a name must become an address
Read it as steps
Timing the first steps
The first steps are easy to measure from your own machine. The tool curl can print the time at which each stage finished, using a small format file.
lookup %{time_namelookup}\n
connect %{time_connect}\n
tls %{time_appconnect}\n
first %{time_starttransfer}\n
total %{time_total}\n
new conn %{num_connects}\nfmt.txt: the fields curl prints, one per line
curl -s -o /dev/null -o /dev/null -w "@fmt.txt" \ https://example.com https://example.com
Fetch the page, throw the body away, print the times
The command fetches the page twice in one call, so the second request can reuse the connection that the first one opened. It was run against example.com on 2026-11-22 with curl 8.21.0. Each number is cumulative: it is the time since that request started, in seconds, so the cost of one stage is the difference from the stage before it. The last field, num_connects, counts the new connections the request had to open.
lookup 0.014660 connect 0.017091 tls 0.031079 first 0.037126 total 0.037179 new conn 1 lookup 0.000000 connect 0.000000 tls 0.000000 first 0.005186 total 0.005247 new conn 0
One real run: the first six lines are the first request, the last six the second. The numbers change from run to run.
What the numbers say
Reading the first request: the name lookup took about 15 ms, the TCP connection about 2 ms more, the TLS handshake about 14 ms more, and the wait for the first byte of the reply about 6 ms more, for 37 ms in all. Opening a TCP connection costs about one network round trip, so the server that answered was only about 2 ms away. Other runs on this machine gave totals between about 25 and 45 ms, so treat one run as one sample.
The second request is the interesting one. It reused the open connection, new conn 0, so the lookup, the connection and the handshake cost nothing, and the whole request took about 5 ms. In the first request, 31 ms of the 37 passed before the request was even sent. The wait for the first byte, one round trip plus the server's own work, was the small part. Making the server twice as fast would barely move the total. What moves it is skipping or shortening the early stages: DNS answers that are cached, connections that are kept open and reused, and, when the server is far away, a CDN edge near the user so that each round trip is short.
In the first request, connect is 0.017 and tls is 0.031. How long did the TLS handshake take?
- About 14 ms. The fields are cumulative, so the handshake took
tlsminusconnect. - Reading
tlsalone as the handshake time would wrongly include the lookup and the connection.
The second request took about 5 ms against 37 ms for the first. What did it skip, and why?
- The name lookup, the TCP connection and the TLS handshake, because it reused the connection the first request had opened (
new conn 0). - This is why clients, balancers and servers keep connections open between requests.
A page's first request spends 31 ms before it is sent and 6 ms waiting for the reply. A teammate wants to rewrite the server to answer twice as fast. What do you look at first?
- The early stages: whether connections are reused, whether DNS answers are cached, and how far the user is from the server.
Part 3 · The async path
Work nobody waits for
Some work does not need to finish before the user sees a reply. Sending a receipt email, resizing an uploaded photo and updating a recommendation can all happen a few seconds later. Doing them inside the request would make the user wait for something they never asked to see.
The async path moves that work out of the request. The server writes a description of the job into a queue, replies at once, and a separate worker process takes jobs from the queue and does them. The queue holds the jobs safely if the workers are busy, so a sudden spike turns into a longer queue instead of a crash.
Three blocks appear on this path, and they are easy to mix up.
| Block | What it does | Who receives a message |
|---|---|---|
| Queue | Holds jobs until a worker takes one | One worker per job |
| Pub-sub topic | Announces an event to everyone who subscribed | Every subscriber gets its own copy |
| Scheduler | Starts a job at a set time or on a repeat | A worker, when the time comes |
A queue answers the question: who will do this job? A topic answers: who needs to know this happened? A scheduler answers: when should this run? A design often uses all three. An order placed publishes an event, billing and email each subscribe to it, and a nightly scheduler job sweeps unpaid orders.
The async path is not free, and not everything belongs on it. Use it when the user does not need the result to carry on. Keep on the request path anything the reply depends on, such as checking that an item is in stock or authorising a payment: the user must know at once whether it worked. A common mistake is the opposite one, doing a slow job such as sending email inside the request, so that one slow mail server makes the checkout page time out.
A producer and a consumer
The smallest version is a producer that puts jobs in a queue and a consumer that takes them out. Python's queue.Queue is safe to share between threads, so it shows the idea without any server.
import queue import threading import time jobs = queue.Queue() def producer(): for n in range(1, 6): jobs.put(f"order-{n}") print(f"put order-{n} queue depth {jobs.qsize()}") jobs.put(None) def consumer(): while True: job = jobs.get() if job is None: break time.sleep(0.05) print(f"done {job}") threading.Thread(target=producer).start() c = threading.Thread(target=consumer) c.start() c.join()
queue_demo.py: five jobs, one slow consumer
Run with Python 3.12.10, this printed the following. The producer finished all five put lines before the consumer finished its first job, so the depth climbed to five. The thread order can differ between runs, but the order of the jobs does not.
put order-1 queue depth 1 put order-2 queue depth 2 put order-3 queue depth 3 put order-4 queue depth 4 put order-5 queue depth 5 done order-1 done order-2 done order-3 done order-4 done order-5
The producer never waited for the work: it was free after five quick put calls while the consumer took 50 ms for each job. The depth of the queue was the measure of the backlog. Real queues add three things that this sketch leaves out: they survive a restart, they let you run many workers, and they redeliver a job if a worker dies before it finishes. The message queue chapter covers those.
If a worker dies after doing a job but before telling the queue, the job is handed out again. Jobs on the async path should therefore be safe to run twice.
What changes for the user when a slow job moves from the request to a queue?
- The reply comes back sooner, because the server only has to write the job down.
- The job finishes later, so the user may need a notice or a status page.
An order is placed and three services must react: billing, email and analytics. Queue or pub-sub topic?
Part 4 · The data and watch path
Where bytes and evidence live
The third path has two jobs. It stores what the product is made of, and it records what the product did.
A blob store keeps large files, such as photos, video and documents, under a key. A database could hold them, but it is built for small records that you query, and large files would crowd out the data you need to read quickly. A search index is a second copy of some records, arranged so that you can find them by the words inside. It is filled from the database, so it can lag a little behind.
The watch half has three kinds of record. Logs are lines of text, one per event, that say what happened. Metrics are numbers sampled over time, such as requests per second. Traces follow one request across the servers it touched. Together they let you answer two questions: is it working, and if not, where did it break?
The thread that ties them together is a request id: a short unique value created when the request arrives and written on every log line the request causes. With it, a search for one id returns the story of one request, across every server.
In the program below the id is the first eight hex characters of a random UUID, to keep the line short. That is only 32 bits, so ids will repeat: after about 77,000 requests the chance that two of them share an id is about one half. A real service uses the full value, or the trace id that its tracing system already creates.
One log line with a request id
A log line that a program can read is called a structured log. The usual format is one JSON object per line, with the same field names every time.
import json import time import uuid def handle(path): request_id = uuid.uuid4().hex[:8] start = time.perf_counter() time.sleep(0.02) ms = round((time.perf_counter() - start) * 1000, 1) print(json.dumps({"request_id": request_id, "path": path, "status": 200, "ms": ms}, separators=(",", ":"))) handle("/orders/17")
log_line.py: time one handler and print one JSON line
It printed one line. The request_id is new on every run and the ms field is the time this run took, so your output will differ.
{"request_id":"7df547db","path":"/orders/17","status":200,"ms":20.4}Four fields already answer useful questions. Searching the request_id finds every line of one request. Filtering on status finds the failures. Averaging ms per path finds the slow routes. The same lines can be counted to produce a metric, which is why structured logs are the raw material for monitoring.
Which chapter adds which block
Each row of the map below names a block from this chapter and the chapter where it is built up. Use it as the index for the rest of the course.
| Block | Path | Where it gets its own chapter |
|---|---|---|
| DNS | Request | The dns chapter, next |
| Load balancer | Request | The chapter after DNS |
| Database, replicas, shards | Request and data | The databases chapter and the key-value store chapter |
| CDN | Request | The cdn chapter |
| Unique ids | All | The sequencer chapter |
| Monitoring, errors, logs | Watch | The monitoring, server errors, client errors and logging chapters |
| Cache | Request | The cache chapter |
| Queue and pub-sub | Async | The message queue and pub-sub chapters |
| Rate limiter | Request | The rate limiter chapter |
| Blob store and search | Data | The blob store and search chapters |
| Task scheduler | Async | The task scheduler chapter |