Sub topic 5
Know your building blocks
This chapter assumes you can read a short Python snippet and know how a client talks to a server over HTTP. It also assumes you have used a relational database. You do not need to have run any of the components below in production. The goal is a working model of each component: what it does, what it costs, and how it fails.
Why a fixed vocabulary helps
Most system designs are assembled from the same dozen components. Experienced designers do not invent new parts. They pick known parts, place them where the requirements demand, and state what each one costs.
Learning the blocks has two payoffs:
- You can turn a requirement into a component quickly. "Users upload photos" suggests object storage. "Results must be fast for repeat readers" suggests a cache.
- You can discuss trade-offs precisely. Every block solves one problem and creates another, and naming that new problem is what makes a design credible.
The core set
| Block | Problem it solves | Main cost or risk |
|---|---|---|
| DNS | Maps names to addresses, can route by region | Cached answers change slowly, so failover is delayed |
| CDN | Serves static content from locations near users | Stale content, invalidation effort |
| Load balancer | Spreads requests across servers, removes dead ones | Itself a single point of failure unless redundant |
| Application server | Runs business logic | Holds no durable state if you want to scale it out |
| Cache | Avoids repeated expensive reads | Stale data, cold starts, invalidation bugs |
| Relational database | Transactions, joins, constraints | Harder to scale writes horizontally |
| NoSQL store | Horizontal scale for simple access patterns | Weaker queries, often weaker consistency |
| Object storage | Cheap, durable storage for large blobs | Higher latency, no in-place edits |
| Message queue | Decouples producers from consumers, absorbs bursts | Delivery semantics, duplicates, lag |
| Search index | Full-text and ranked queries | Eventually consistent copy of your data |
| Rate limiter | Protects services from overload and abuse | Needs shared state, can reject legitimate users |
The sections below cover the ones that are most often misused.
Load balancers and stateless servers
A load balancer receives requests and forwards each to one of several identical servers. Two common choices:
- Layer 4 balancers forward TCP connections without reading the HTTP request. They are fast and simple.
- Layer 7 balancers read the HTTP request. They can route by path or header, terminate TLS, and retry on another server.
A load balancer only helps if the servers behind it are interchangeable. That means they are stateless: no request depends on data held in one server's memory. Session data, uploaded files, and counters belong in a shared store such as a cache or database. If you keep state on the server, you need sticky routing, which makes scaling and failure recovery harder.
Caches
A cache keeps a copy of data in fast storage, usually memory, so repeated reads skip the slower source. The most common pattern is cache-aside:
- The application checks the cache.
- On a hit, it returns the cached value.
- On a miss, it reads the database, stores the result in the cache, and returns it.
- On a write, it updates the database and deletes the cached entry.
import time
class TTLCache:
def __init__(self, ttl_seconds: float):
self.ttl = ttl_seconds
self._data = {}
def get(self, key):
entry = self._data.get(key)
if entry is None:
return None
value, expires_at = entry
if time.monotonic() >= expires_at:
del self._data[key]
return None
return value
def set(self, key, value):
self._data[key] = (value, time.monotonic() + self.ttl)
def delete(self, key):
self._data.pop(key, None)
DATABASE = {"user:42": {"name": "Ada"}}
cache = TTLCache(ttl_seconds=60)
db_reads = 0
def read_user(key):
global db_reads
value = cache.get(key)
if value is not None:
return value
db_reads += 1
value = DATABASE.get(key)
if value is not None:
cache.set(key, value)
return value
def update_user(key, value):
DATABASE[key] = value
cache.delete(key)
for _ in range(3):
read_user("user:42")
print(db_reads) # 1: only the first read reached the database
update_user("user:42", {"name": "Grace"})
print(read_user("user:42"), db_reads) # {'name': 'Grace'} 2The time-to-live (TTL) bounds how stale an entry can get even if an invalidation is missed. Deleting on write, rather than updating the cache, avoids a race where two concurrent writers leave the older value in the cache.
Caches also have failure modes you should be ready to name:
- Cold start. After a restart the cache is empty, and the database receives the full read load at once.
- Stampede. A popular key expires and many requests miss at the same moment, all hitting the database.
- Hot key. One key receives so much traffic that the single cache node holding it becomes the bottleneck.
A cache helps most when reads far outnumber writes and the same items are read repeatedly. If every request asks for a different key, the hit rate will be low and the cache only adds a hop.
Queues and asynchronous work
A message queue stores messages from producers until consumers process them. Use one when work does not need to finish before the user gets a response, such as sending email, resizing images, or updating a search index.
A queue gives you three things:
- Bursts are absorbed. The queue grows and consumers catch up later.
- The producer and consumer fail independently.
- You can add consumers to increase throughput.
It also forces decisions about delivery. Most queues offer at-least-once delivery, so a message can arrive twice. Consumers must therefore be idempotent, meaning that processing the same message again produces the same end state. A common approach is to attach a unique ID to each message and record the IDs already handled. Also decide what happens to a message that keeps failing. A dead-letter queue holds such messages for inspection instead of retrying them forever.
Object storage and CDNs
Object storage keeps large, immutable blobs (images, video, backups) under a key. It is far cheaper per gigabyte than a database and very durable. Do not put such blobs in database rows. Store the blob in object storage and keep its key and metadata in the database.
A content delivery network (CDN) caches copies of static files on servers near users. Put one in front of object storage when the same files are fetched by many users in many regions. Changing a file requires either invalidating the CDN entry or using a new URL, and versioned URLs are usually simpler.
Databases and search indexes
Choose the database from the access pattern, not from habit. A relational database suits data with relationships, multi-row transactions, and ad hoc queries. A key-value or wide-column store suits simple lookups by key at very high volume. Chapter "Choose storage that fits the access pattern" covers this choice in detail.
A search index is different. It is a derived copy of your data, built for text queries, and it is updated after the main database changes. Treat the database as the source of truth and the index as rebuildable. Never write data only to the index.
Assembling blocks from requirements
The diagram shows one common assembly for a service where users upload images and read feeds.
To pick blocks, walk through the requirements one at a time and ask which block each one implies:
- A latency target on reads points to a cache or CDN.
- A durability requirement points to replicated storage and backups.
- A traffic spike or slow background task points to a queue.
- A text search feature points to a search index.
- An availability target means every block on the request path needs redundancy.
Add a block only when a requirement or an estimate justifies it. Each extra component adds operations work and another way for the system to fail.
Common errors
- Adding a cache before measuring. If the database handles the estimated load comfortably, the cache adds staleness and complexity for no benefit.
- A single load balancer, queue, or cache node drawn as one box. State how each is made redundant, or say that you accept the risk.
- Treating the queue as exactly-once. Design consumers for duplicates.
- Storing session state on app servers. This breaks horizontal scaling and failover.
- Using the search index as the source of truth. A rebuild then loses data.
- Naming a product instead of a role. Say "a key-value cache" and explain why. Then name a product only if it matters.
Exercise
A photo-sharing service lets users upload images, shows each user a feed, and must stay responsive when a celebrity posts and millions of followers load the feed. Which blocks would you add for image storage, feed reads, and thumbnail generation, and what is one failure mode of each?
Show answer
Image storage: object storage fronted by a CDN, with only the key and metadata in the database. Failure mode: a stale CDN copy after an image changes, avoided by versioned URLs. Feed reads: a cache in front of the database, since many followers read the same feed data. Failure mode: a hot key or stampede when the celebrity's content is requested by millions at once, mitigated by request coalescing or replicating the hot entry. Thumbnail generation: a queue with worker consumers, so uploads return quickly. Failure mode: duplicate or poison messages, handled by idempotent workers and a dead-letter queue.
Exercise
Why must application servers behind a load balancer be stateless, and where should session data live instead?
Show answer
If a server holds session data in its own memory, the load balancer must always send that user to the same server, and the session is lost if the server dies. Stateless servers are interchangeable, so any server can handle any request and servers can be added or removed freely. Session data should live in a shared store such as a cache or database, or in a signed token held by the client.