Summary#
Definition: system design is the work of choosing the parts of a software system (clients, servers, databases, caches, queues, storage) and deciding how they connect and how data flows between them, so that the system does what users need and keeps doing it as load grows and parts fail. It happens at two zoom levels: high-level design (HLD) decides the components and their interactions, and low-level design (LLD) decides the code inside one component. Almost every web system is built from the same ten building blocks on a client-server model. Good design serves two kinds of goals: functional (what the system does) and quality (how fast, reliable, secure and cheap it is). Every decision trades one quality for another, and the core skill, in real projects and in interviews, is making those trade-offs explicitly with numbers.
Why It Exists#
A program that runs on your laptop for one user is easy to reason about. Everything is in one memory space, a function call takes nanoseconds and never gets "lost", and if the machine crashes you just restart it. The same program used by ten million people breaks in ways that no amount of better code can fix:
- Capacity. One machine has a fixed amount of CPU, memory, disk and network bandwidth. A modest server handles roughly 1,000-10,000 simple requests per second. A popular product may need a million.
- Data size. A single disk holds a few terabytes. A photo-sharing service stores petabytes.
- Failure. At scale, hardware failure is routine, not rare. Google's paper "The Datacenter as a Computer" (Barroso and Hölzle) describes failures as a constant background condition in large clusters. With thousands of disks, some fail every day.
- Distance. Light in fibre needs about 80-100 ms for a round trip between the US and Europe. A user in Mumbai talking to a server in Virginia waits for every round trip, however fast the code is.
- Change. Many teams change the system every day. A bug in one feature must not take down the whole product.
These problems are solved by architecture: how many machines there are, what each one does, where each piece of data lives, how copies are kept in sync, and what happens when any part fails. System design is the discipline of making those decisions on purpose instead of by accident. If you read How to Use This Handbook, this page is the first step of every learning path.
How It Works#
A working definition#
System design has three parts, and each later page in this handbook deepens one of them:
- Components: the boxes. Web servers, databases, caches, queues, search indexes, object stores, CDNs.
- Interactions: the arrows. Who calls whom, synchronously or asynchronously, over which protocol, with what data format and what happens on failure.
- Data: where each piece of data lives, how it is partitioned and copied, how consistent the copies are, and how long it is kept.
A design is "good" only relative to its goals. A design for a bank ledger that loses one transaction in a million is broken; a design for a view counter that loses one view in a million is fine and probably wasteful if it tries harder. So system design always starts from requirements and ends in trade-offs.
The idea is older than the web. In 1968, Melvin Conway observed in "How Do Committees Invent?" that organisations design systems that mirror their own communication structures, now called Conway's law. In 1972, David Parnas's paper "On the Criteria To Be Used in Decomposing Systems into Modules" argued that you should split a system around the decisions most likely to change, hiding each behind an interface. Both ideas still shape how services and teams are drawn today.
High-level vs low-level design#
High-level design (HLD) describes the big boxes and arrows: services, data stores, caches, queues, external providers, and how requests and data flow between them. It answers questions such as "Do we need a cache?", "Which database?", "How do we shard?", "What happens when a region is down?".
Low-level design (LLD) zooms into one box: classes and interfaces, data structures, algorithms, database schemas in full detail, concurrency within one process, error handling. It answers "How is the rate limiter's token bucket implemented?" or "What classes make up the parking-lot system?".
Take a URL shortener as an example:
| Question | Level | Example answer |
|---|---|---|
| How do redirects stay under 10 ms worldwide? | HLD | Cache short-code lookups in Redis and at the CDN edge |
| Which database holds the mappings? | HLD | A key-value store keyed by short code, replicated across zones |
| How are short codes generated without collisions? | HLD and LLD | A counter service hands out ID ranges; base-62 encode each ID |
What does the encode(id) function look like? | LLD | A loop dividing by 62 and mapping digits to characters |
| What classes handle analytics events? | LLD | An EventPublisher interface with a Kafka implementation |
This handbook focuses on HLD. Both matter, but HLD decisions are the expensive ones to change later. Rewriting a function takes an afternoon. Migrating a petabyte from one database to another can take a year.
Between the two sits a useful middle layer: component design (how a single service is structured internally, which libraries it uses and which data it owns). The C4 model popularised by Simon Brown names these zoom levels Context, Containers, Components and Code, and many teams use it to draw architecture diagrams at a consistent level of detail.
The client-server model#
Almost every system in this handbook is built on the client-server model. A client (browser, mobile app, IoT device or another service) sends a request. A server processes it and returns a response. The two sides are different in important ways:
- Clients are many and untrusted. There may be millions of them, running old versions of your app on slow networks, and some of them are malicious. Never trust input from a client; validate everything on the server.
- Servers are fewer and controlled by you. You choose their hardware, software and location. Everything else in this handbook is about making the server side fast, reliable and scalable.
- The network between them is unreliable. Requests can be lost, delayed, duplicated or reordered. A client that gets no response cannot tell whether the server never got the request, or did the work and the response was lost.
The client-server model has grown several tiers:
- Two-tier: the client talks directly to a database (early desktop apps). Simple, but every client holds database credentials and business logic.
- Three-tier: presentation (client), application (servers with business logic) and data (database). This is the default for web applications.
- N-tier / service-oriented: the application tier is split into many services that call each other. The "client" of one service is often another service.
The main alternative is peer-to-peer (P2P), where every node is both client and server, as in BitTorrent or blockchain networks. P2P removes central servers but makes trust, consistency and discovery much harder, so most products use client-server and reserve P2P-like techniques (gossip, for example) for internals. See Networking Fundamentals.
Following one request#
The fastest way to understand a system is to trace one request through it. Here is what happens, roughly, when a user opens their home feed on a large social app:
Each hop is a design decision. DNS decides which region serves the user. The CDN caches images close to the user. The load balancer spreads load and skips unhealthy servers. The feed service is stateless so it can be copied many times. The cache answers most reads, and the database is the source of truth. What Happens When You Type a URL walks through the network side in detail.
A useful habit is to write a latency budget: if the product needs the feed in 200 ms at the 99th percentile, and the mobile network round trip already takes 80 ms, the backend has roughly 100 ms for everything else. That single number rules out designs that make five sequential database calls of 20 ms each.
The building blocks#
A typical production web application combines the same ten building blocks. Learning what each one is for, and what it costs, is most of the vocabulary of system design.
DNS (Domain Name System) turns a name like example.com into an IP address. It is the first step of nearly every request, and it is also a routing tool: by returning different IPs to different users, DNS can send each user to the nearest or healthiest region. Answers are cached for a TTL (time to live), so changes take seconds to hours to spread. See DNS.
CDN (Content Delivery Network) is a network of servers in hundreds of cities that cache your static files (images, video, JavaScript) and sometimes API responses. A user in Sydney gets an image from a Sydney server in 10-20 ms instead of from Virginia in 200 ms, and your servers see only a fraction of the traffic. See CDN.
Load balancer receives incoming requests and spreads them across many app servers, checking their health and skipping failed ones. It is what lets you add servers without users noticing. Layer-4 balancers route by IP and port; layer-7 balancers understand HTTP and can route by path or header. See Load Balancing.
App servers run your business logic. The key design rule is to make them stateless: no user data kept in local memory between requests. Then any server can handle any request, and you scale by adding copies. See Vertical vs Horizontal Scaling.
Database stores the source of truth: data that must survive crashes and be shared by all servers. Relational databases (PostgreSQL, MySQL) offer transactions and flexible queries; NoSQL databases (DynamoDB, Cassandra, MongoDB) trade some of that for easier horizontal scaling or flexible schemas. Choosing and scaling the database is often the hardest part of a design. See Relational Databases.
Cache keeps frequently read data in memory (Redis, Memcached) so reads take about 1 ms instead of 5-50 ms, and the database sees far less load. Caches introduce the risk of serving stale data. See Caching Fundamentals.
Message queue lets one part of the system hand work to another without waiting: sending emails, resizing images, updating search. It absorbs traffic spikes and isolates failures. See Message Queues.
Object store (Amazon S3, Google Cloud Storage, Azure Blob Storage) holds large files cheaply and durably, at a few cents per gigabyte per month, designed for very high durability (S3 is designed for eleven nines). Databases store the metadata and a pointer to the object. See Object Storage.
Search index (Elasticsearch, OpenSearch) answers full-text, fuzzy and ranked queries ("posts mentioning 'pizza' near me") that a normal database index handles badly. It is usually a secondary copy built from the database. See Elasticsearch.
Monitoring (metrics, logs and traces) tells you when something is wrong and why. Without it, you learn about outages from your users. See Observability.
| Block | What it does | Typical numbers | Learn more |
|---|---|---|---|
| DNS | Name to IP; coarse traffic routing | Cached lookups ~0 ms, uncached 20-100 ms | DNS |
| CDN | Static content near users | Edge hit ~10-30 ms, offloads 80-95% of bytes | CDN |
| Load balancer | Spread requests, skip unhealthy servers | Adds ~0.1-1 ms | Load Balancing |
| App servers | Business logic, stateless | ~1k-10k requests/s each | Scaling Up vs Out |
| Database | Durable source of truth | Indexed read ~1-5 ms; primary ~5k-20k writes/s | Relational Databases |
| Cache | Hot data in memory | ~0.5-1 ms per read; ~100k ops/s per node | Caching Fundamentals |
| Message queue | Async work, buffering | Milliseconds to enqueue | Message Queues |
| Object store | Large files, cheap and durable | Tens of ms first byte | Object Storage |
| Search index | Full-text and ranked queries | Tens of ms per query | Elasticsearch |
| Monitoring | Metrics, logs, traces, alerts | Seconds to detect | Observability |
Not every system needs all ten. A design is the selection of the blocks your requirements justify, plus the rules for how they interact.
Functional goals vs quality goals#
Every design serves two kinds of goals.
Functional requirements say what the system does, as user actions: "users can post a photo", "users can follow others", "users see a feed of posts from people they follow". They decide which features, APIs and data entities exist.
Non-functional requirements (quality goals, or quality attributes) say how well it does it:
- Performance: "the feed loads in under 200 ms at p99" (p99 means 99% of requests are faster).
- Scalability: "supports 100 million daily users and 10x growth".
- Availability: "99.9% of minutes in a month the service works" (about 43.8 minutes of downtime allowed).
- Durability: "no uploaded photo is ever lost".
- Consistency: "after you post, you see your own post immediately".
- Security and privacy: "only followers see private posts; data is encrypted at rest".
- Cost and operability: "runs on a budget of X per month; one on-call engineer can handle incidents".
The standard ISO/IEC 25010 lists similar product quality characteristics (functional suitability, performance efficiency, compatibility, usability, reliability, security, maintainability, portability). You do not need to memorise the list, but it is a good checklist.
Functional goals decide what to build. Quality goals decide the architecture. Two products with identical features ("post a message, read messages") can need completely different designs. A team chat for 50 people runs on one server. A global messaging app for a billion users needs sharding, replication across regions and a persistent connection layer. Requirements Gathering and Non-Functional Requirements teach both in depth.
Design is trade-offs#
Almost every design choice buys one quality at the cost of another:
- A cache buys speed and costs freshness.
- Replicas buy availability and read capacity, and cost consistency (replication lag) and money.
- Splitting into services buys team independence and costs network calls, partial failures and harder debugging.
- Strong consistency across regions buys correctness and costs latency, because every write waits for a distant round trip.
There are no "best practices" in isolation, only practices that fit a given set of requirements. This is why experienced designers answer most questions with "it depends", followed by exactly what it depends on. See Core System Design Trade-offs.
Good teams write down significant decisions with their context, the options considered and the trade-off accepted. A common lightweight format is the architecture decision record (ADR), described by Michael Nygard in 2011: a short document per decision with context, decision and consequences.
Distributed systems are different#
Once a system spans more than one machine, it becomes a distributed system, and some intuitions from single-machine programming stop being true. Engineers at Sun Microsystems in the 1990s (L. Peter Deutsch and others) listed the fallacies of distributed computing, false assumptions newcomers make:
- The network is reliable.
- Latency is zero.
- Bandwidth is infinite.
- The network is secure.
- Topology does not change.
- There is one administrator.
- Transport cost is zero.
- The network is homogeneous.
Each fallacy leads to a class of bugs: missing timeouts and retries, chatty APIs that make 50 calls per page, unencrypted internal traffic, hard-coded IP addresses. Much of this handbook (timeouts, retries, idempotency, replication, consensus) exists because these assumptions are false. See Distributed Systems Fundamentals, and for the research behind these ideas, Landmark Distributed Systems Papers.
When each building block earns its place#
Knowing what a block does is half the vocabulary. The other half is knowing when it is justified. Beginners add every block to every diagram. Experienced designers add a block only when a number or a requirement forces it, and they say which one. A cache with no stated reason is noise. A cache added because "the database will see 50,000 reads per second at peak and one Postgres primary comfortably serves perhaps 10,000-20,000 simple indexed reads per second" is a design decision.
The table below lists the trigger that usually justifies each block, what it costs, and the most common misuse.
| Block | Add it when | It costs you | Common misuse |
|---|---|---|---|
| CDN | Static bytes dominate egress, or users are far from your region | Cache invalidation, a vendor bill per GB | Caching personalised API responses that differ per user |
| Load balancer | More than one app server, or you need zero-downtime deploys | One more hop, a component that itself must be redundant | Sticky sessions that quietly make servers stateful again |
| Cache | Reads repeat, the database is the bottleneck, or latency targets are below what the database gives | Stale data, invalidation logic, a stampede when it fails | Caching before measuring, or caching data that is rarely re-read |
| Read replicas | Reads outgrow one primary but writes still fit | Replication lag, read-your-own-write surprises | Sending a read that must see the latest write to a lagging replica |
| Sharding | Writes or data size outgrow the largest single machine you can buy | Cross-shard queries and transactions become hard | Sharding at a few hundred GB when one node would do |
| Message queue | Work does not need to finish inside the request, or producers spike faster than consumers | Eventual results, retries, duplicates, a new thing to monitor | Putting large files in the queue instead of a pointer |
| Object store | Files larger than about 1 MB, or total bytes in terabytes | Tens of ms to first byte, no rich queries | Storing images as database blobs |
| Search index | Full-text, fuzzy, ranked or geo queries | A second copy to keep in sync, eventual freshness | Using it as the source of truth |
| Monitoring | Always, from day one | Storage and attention | Collecting metrics nobody alerts on |
Two rules sit behind the table. First, the simplest design that meets the numbers wins. Every block you add is another thing that can fail, another thing to deploy and another thing a new engineer must learn. Second, blocks come in response to bottlenecks, in roughly the order bottlenecks appear: the single server runs out of CPU, so you add servers behind a load balancer; the database runs out of read capacity, so you add a cache and replicas; it runs out of write capacity or disk, so you shard. Scaling from Zero to Millions tells that story step by step.
The pointer pattern deserves a special mention because it appears in almost every design. Large payloads (videos, photos, documents, crawled HTML) go into the object store. Everything else (the database row, the queue message, the cache entry, the search document) carries only a small reference to that object, such as its key. When a user uploads a video for transcoding, the message on the queue says "transcode the object at videos/abc123/raw.mp4", not the 2 GB file itself. Queues and databases are tuned for many small records. Kafka, for example, recommends keeping messages under about 1 MB. Object stores are tuned for few large ones. Keeping each job on the right block is a decision that never goes out of fashion.
Introducing a building block: a four-step habit#
Whether you are writing a design document or talking in an interview, the strongest way to add any component follows the same four steps.
- Name the bottleneck with a number. "User-profile reads hit the database 500 times a second at peak, at 30 ms each, and the same profiles are read again and again."
- Say exactly what the block will hold or do. "We cache profiles under the key
user:123:profile, because they are read on every page and change only when a user edits settings." - Pick the variant and the policy. "Cache-aside in Redis: read the cache first, fall back to the database on a miss, then fill the cache. LRU eviction, a 10-minute TTL as a safety net, and an explicit delete when a profile changes."
- Address the cost it introduces. "If Redis goes down, every read falls on the database at once, so we put a circuit breaker in front of the database and keep a small in-process cache for the hottest keys. For a very popular key that expires, we coalesce requests so only one goes to the database."
The same shape works for every block. For sharding: first prove one database is not enough ("50,000 writes per second at peak is beyond one primary"), then pick the shard key from the access pattern ("almost every query is scoped to one user, so shard by user_id"), then the distribution scheme ("hash the key, with consistent hashing so adding shards moves only a fraction of the data"), then the cost ("a global query such as 'trending across all users' must hit every shard, so we pre-compute it with a background job and cache it"). For a queue: the burst you are absorbing, what goes in the message (a pointer, not the payload), the delivery guarantee you rely on, and what happens to a message that keeps failing.
Notice what the habit leaves out: listing every possible problem. Pick the one or two failure modes that matter for this system and handle them well. Reciting all ten cache pitfalls signals memorisation, not judgement.
Consistency or availability: the first architectural fork#
Of all the quality goals, one splits designs into two families early: when the network between replicas fails, should the system refuse to answer rather than risk a stale answer (consistency), or answer from whatever copy it can reach (availability)? This is the practical heart of the CAP theorem, and it is worth deciding while you list non-functional requirements, because it shapes almost every later choice.
The decision is usually made per feature, not per system. In a ticket-booking product, two people must never buy the same seat, so the booking path favours consistency. The event description page can be a few seconds stale without anyone noticing, so it favours availability and caching.
| If a feature needs | Typical design moves | Technologies that fit |
|---|---|---|
| Consistency (no stale or conflicting reads) | Keep the data in one primary or a consensus-replicated store, make related writes atomic with transactions, accept extra latency for coordination | PostgreSQL or MySQL on a single primary, Google Spanner, DynamoDB with strongly consistent reads, etcd or ZooKeeper for small coordination data |
| Availability (always answer, maybe stale) | Asynchronous replicas that serve reads, change data capture (CDC) that streams changes from the primary to caches, search and other stores, conflict handling when copies diverge | Cassandra, DynamoDB across zones with eventually consistent reads, Redis replicas and clusters, CDNs |
Neither column is "better". A consistent design pays in latency and in downtime during partitions. An available design pays in application complexity, because code must tolerate stale reads and sometimes merge conflicts. Consistency Models explains the spectrum in between.
Hardware moved on; so should the defaults#
A surprising amount of system design material still reasons with hardware from around 2015: small memory, spinning disks, slow networks. Those numbers lead to designs that shard and cache far too early. Today a single commodity cloud server can have dozens of cores, hundreds of gigabytes of RAM and NVMe SSDs that serve hundreds of thousands of random reads per second. Some practical consequences:
- A single relational database goes a long way. One well-indexed PostgreSQL primary on a large instance can hold several terabytes and serve thousands of writes per second. A product with 500 million users at 5 KB of profile data each needs about 2.5 TB, which one node can hold. You shard because of growth or write rate, not because "databases do not scale".
- Memory is large and cheap. A whole working set of tens of gigabytes fits in one cache node. A Redis node handles on the order of 100,000 simple operations per second.
- One message broker is big. As a hand-wavy rule, a single well-provisioned Kafka broker can hold around a terabyte and handle up to about a million small messages per second. If your estimate is below that, "how do we scale Kafka" is not the interesting question.
- Network inside a data centre is fast. A round trip inside one zone is about 0.5 ms, and 10-25 Gbps links are normal, so a cache hop is cheap compared with a database query or a disk seek.
These are rough orders of magnitude, and they change every year. Numbers to Know keeps a current table. The point is the habit: check a modern number before you assume a block is needed.
Kinds of design problems#
"System design" covers several distinct kinds of problem, and the work (and the interview) differs for each.
| Kind | Typical prompt | What the work is about | Where the depth goes |
|---|---|---|---|
| Product design | "Design Ticketmaster", "Design Instagram", "Design Uber" | A user-facing product end to end: features, API, data model, the main request flows and their scaling | The one or two flows that are hard for this product, such as seat contention, feed fan-out or matching drivers |
| Infrastructure design | "Design a rate limiter", "Design a key-value store", "Design a message queue", "Design a distributed cache" | One reusable building block whose users are other engineers | Internals: algorithms, replication, partitioning, failure handling, exact guarantees |
| Low-level or object-oriented design | "Design a parking lot", "Design a vending machine" | Classes, interfaces, state and behaviour inside one program | Clean abstractions, patterns, extensibility |
| ML system design | "Design a recommendation system", "Design a spam classifier" | Data, features, models, training and serving pipelines, evaluation | Feature engineering, offline and online metrics, model serving |
| Frontend system design | "Design a news feed UI", "Design an autocomplete widget" | Client architecture, rendering, state, network usage | Performance on the device, caching on the client, accessibility |
This handbook concentrates on the first two, which are what most companies mean by a system design interview. They overlap heavily: a product design for a ride-hailing app may include a rate limiter or a queue as one box, while an infrastructure design for a rate limiter zooms into what was one box and makes it the whole page.
The main difference is who the user is. In product design the users are people, so requirements talk about features, latency people can feel and data they care about. In infrastructure design the users are other services, so requirements talk about guarantees: "at most N requests per window per key, with decisions in under 1 ms, and a defined behaviour when the counter store is unreachable". Infrastructure designs are judged on precision. A product design that says "use a queue here" is fine. An infrastructure design of a queue must say how messages are stored, ordered, replicated and acknowledged.
Worked example: a product prompt#
Prompt: "Design a ticket-booking site like Ticketmaster." A sketch of how the definition plays out:
- Functional goals. Users search for events, view an event and its seat map, and book a seat. Out of scope: reselling, payments internals, recommendations.
- Quality goals. No seat is ever sold twice (consistency on booking). Search and event pages should be fast and highly available (availability and caching are fine there). A popular show can bring millions of users in the first minutes of a sale.
- Building blocks chosen. A CDN for static assets and event pages that are the same for everyone. A load balancer in front of stateless services. A relational database as the source of truth for events, seats and bookings, because booking needs transactions. A search index (Elasticsearch) for "events by keyword, date and place", fed from the database by CDC. A cache for repeated search queries and event details. A short-lived seat reservation held while the user pays, with a lock or a status-plus-expiry on the seat row. A queue (a "waiting room") to meter users into the booking flow during a huge on-sale.
One deep dive shows how design decisions stack. The same searches ("Taylor Swift, this month") arrive thousands of times. Three layers can absorb them:
- An application cache (Redis or Memcached) keyed by every parameter that changes the result, for example
search:keyword=taylor swift&start=2026-12-01&end=2026-12-31. If any parameter is missing from the key, two different searches share one answer, which is a correctness bug. A TTL keeps answers from living forever. - The search engine's own caches. Elasticsearch caches filter results per shard and can cache whole responses for aggregation-heavy queries, so even cache misses are cheaper.
- The CDN, but only if results are the same for everyone. A personalised result ("events near you, ranked by your taste") cannot be shared across users at the edge.
The hard part is invalidation. When a new event is announced, which cached searches are now wrong? Searches and results are not linked by a simple key, so you combine short TTLs with tags (for example, tag each cached result with the artists or venues it contains, and purge by tag when one of them changes). This is a typical shape: a simple idea (cache), a precise key, then a real trade-off (freshness against load).
Worked example: an infrastructure prompt#
Prompt: "Design a rate limiter used by all our public APIs." The same definition applies, but the users are services.
- Functional goals. Given a key (API key, user ID or IP) and a rule ("100 requests per minute"), decide allow or reject for each request, and tell the caller how long to wait.
- Quality goals. The decision must add under about 1 ms, because it sits on every request. It must work across many API servers, so counters are shared. It must keep working, or fail in a known way, when the counter store is unreachable.
- Building blocks chosen. The limiter runs inside the API gateway or as a library in each service. Counters live in an in-memory store (Redis) because every request reads and updates them. Rules live in a small configuration store and are cached in each process.
The interesting questions are all about internals and failure, which is what marks an infrastructure problem. Which algorithm (fixed window, sliding window, token bucket) and how accurate it is at window edges. Whether the increment and the check are atomic (a Lua script or a single INCR with expiry in Redis). What happens if Redis is down: fail open (allow everything, protect availability) or fail closed (reject everything, protect the backend). What happens to a single very hot key that sends all its traffic to one Redis shard. The full answer is in the rate limiter case study, but the definition already tells you the shape: components, interactions, data, then trade-offs.
When to Use It#
Think in system design terms when any of these are true:
- More than one machine is involved, or soon will be.
- Data must survive hardware failure, or must be shared by many users.
- Traffic is large (thousands of requests per second) or very spiky (10x at a launch or sale).
- Users are spread across regions, or latency targets are tight (under 100 ms).
- Several teams will build and run parts of the system independently.
- The cost of being wrong is high: money, safety, legal compliance or user trust.
When NOT to Use It#
- A prototype or internal tool with a handful of users. One server and one database is the right design; anything more is waste. Many successful products ran on a single database for years.
- Problems that are really algorithmic or local: a slow loop, a missing index, an N+1 query. Fix the code and the query before redrawing the architecture.
- Before you understand the requirements. Designing first and asking later produces elegant answers to the wrong question.
How to Implement It#
A repeatable process works for both real projects and interviews:
- Clarify requirements. Who are the users, what do they do, how many are there, and which qualities matter most? Write down what is out of scope.
- Estimate scale. Rough numbers for requests per second, storage and bandwidth tell you which problems are real. 100 writes per second fits on any database; 100,000 does not. See Back-of-the-Envelope Estimation.
- Define the core entities and API. Name the main objects (User, Post, Order) and the few endpoints that use them. This keeps the design anchored to real operations.
- Draw the simplest design that works. Client, server, database. Make it satisfy every functional requirement before optimising anything.
- Find the bottlenecks. Use your numbers and quality goals to see what breaks first: database writes, a hot key, cross-region latency, fan-out.
- Deep dive and iterate. Add caches, replicas, queues or shards only where the numbers justify them, and say what each one costs.
- Plan for failure and operations. For each component, ask "what happens when this dies?" and "how will we know?".
- Record decisions. Write ADRs for choices that are expensive to reverse.
The full method lives in Design Process.
# A one-page design doc skeleton (real projects)
1. Context and goals - problem, users, success metrics
2. Requirements - functional, non-functional (with numbers), out of scope
3. Estimates - QPS avg/peak, storage per year, bandwidth
4. API and data model - endpoints, entities, access patterns
5. High-level design - diagram + one line per component
6. Deep dives - the 2-4 hardest problems and options considered
7. Failure modes - what breaks, blast radius, mitigation
8. Rollout and migration - flags, dual writes, backfills
9. Cost and operations - monthly cost estimate, on-call, dashboards
10. Alternatives rejected - and why| Technology | Fits when |
|---|---|
| Diagrams-as-code (Mermaid, PlantUML, Structurizr for C4) | Diagrams versioned with the design doc |
| Whiteboard tools (Excalidraw, Miro) | Interviews and early brainstorming |
| ADR templates in the repository | Recording decisions next to the code |
| Load-testing tools (k6, Gatling, Locust) | Checking estimates against reality |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Add a cache | Faster reads, less database load | Stale data, invalidation bugs | Read-heavy, tolerant of brief staleness |
| Add replicas | Higher availability, more read capacity | Replication lag, more machines | Reads dominate or downtime is costly |
| Split into services | Teams ship independently, scale parts separately | Network calls, partial failures, harder debugging | Many teams, clear domain boundaries |
| Use a queue | Smooth spikes, async work, failure isolation | Eventual results, more moving parts | Work that need not finish in the request |
| Shard the database | Write capacity and storage beyond one node | Cross-shard queries and transactions are hard | One node cannot hold the data or writes |
| Go multi-region | Lower latency worldwide, survives a region loss | Consistency complexity, 2x+ cost | Global users or strict availability |
| Add a CDN | Low latency for static bytes worldwide, far less origin egress | Invalidation delays, per-GB vendor cost | Static or shared content, global users |
| Add a search index | Full-text, fuzzy and ranked queries | A second copy that lags the source of truth | Users search text or need relevance ranking |
| Store files in an object store | Cheap, durable, scales to petabytes | Higher first-byte latency, no rich queries | Anything larger than about 1 MB |
| Strong consistency | Simple reasoning, no stale or conflicting data | Higher latency, less availability during partitions | Money, inventory, bookings, unique names |
| Eventual consistency | Always answers, low latency, scales out | Application must tolerate stale reads and conflicts | Feeds, counters, profiles, catalogues |
| Build versus buy (managed service) | Managed: no operations work, fast start | Vendor cost and lock-in, less control | Buy unless the component is core to your product or the bill is huge |
Common Pitfalls#
- Designing for Google scale when you have a thousand users.
- Picking technologies before understanding requirements ("we will use Kafka and Kubernetes").
- Ignoring failure: every box on your diagram will fail at some point, and so will the arrows.
- Forgetting the data: drawing services without saying where each piece of data lives and who owns it.
- No numbers: claiming "this scales" without estimating load.
- Treating the design as fixed. Good designs evolve as scale and requirements change.
- Optimising one quality to the extreme (latency) while silently breaking another (cost, consistency).
- Adding a block without saying which bottleneck it solves and with what number.
- Putting large payloads (videos, images, HTML pages) into a database row or a queue message instead of storing a pointer to an object.
- Reasoning with hardware limits from a decade ago and sharding a database that one modern machine could hold.
- Choosing one consistency level for the whole system instead of per feature: bookings need strong consistency, the event page does not.
- Treating an infrastructure prompt like a product prompt: drawing boxes for a rate limiter instead of explaining its algorithm, atomicity and failure behaviour.
- Building cache keys that omit a parameter that changes the result, so different requests get each other's answers.
- Listing every possible failure mode instead of handling the two that matter most for this system.
Real-World Examples#
Amazon Prime Video published a case study in 2023 describing how its audio/video quality monitoring tool moved from a distributed design built on serverless components to a single process, reporting an infrastructure cost reduction of over 90% for that tool. The lesson is not "monoliths are better", but that the right architecture depends on the workload.
Typical scenario: a startup runs its product on one server with one database. As users grow, it adds a load balancer and more app servers, then a cache, then read replicas, then a CDN for images, then queues for background work. Each step answers a specific bottleneck, which is the story told in Scaling from Zero to Millions.
Typical scenario: a large company splits a monolith into team-owned services, with queues between them so one outage does not cascade. A few years later it merges some services back because the network calls cost more than the independence gained.
Netflix is a frequently cited example of architecture driven by failure. In August 2008 a database corruption stopped its DVD shipping for about three days. The company concluded that a single large database in its own data centre was a risk it did not want, and over the following years moved to many smaller services on AWS designed to tolerate the loss of individual machines. It later released tools such as Chaos Monkey, which deliberately terminates production instances so that teams must design for failure instead of hoping it does not happen.
Stack Overflow is the opposite lesson. For many years it served one of the busiest sites on the web from a small number of powerful web servers and a handful of large SQL Server machines, and its engineers wrote publicly about how far careful caching and vertical scaling took them. A design is not judged by how many boxes it has, but by whether it meets its goals at an acceptable cost.
Ticket sales for very popular tours are a recurring example of quality goals that dominate everything else. When demand is many times the number of seats, the hard problems are not "can we show the event page" but "can we admit users fairly, hold seats without overselling and survive a burst far beyond normal traffic". That is why designs for such systems add waiting rooms, seat reservations with expiry and strict consistency on the booking path. See the ticket booking case study.
In the Interview#
Who faces a system design interview, and why it weighs so much#
Most entry-level roles have no system design round, although some companies include a light one. From mid-level it becomes common, and at senior level and above it is standard and often carries more weight than any other single interview. The reason is simple: the cost of a junior engineer's mistake is usually a bug; the cost of a senior engineer's mistake can be an architecture the company lives with for years.
The format is practical rather than academic. You get an ambiguous, high-level prompt and 45-60 minutes. Most engineers find it closer to real work than algorithm puzzles. There is rarely one correct answer. Several quite different designs can all pass; what is being judged is how you got to yours.
The four things interviewers grade#
Rubrics differ in wording between companies, but almost all of them measure the same four abilities.
1. Problem navigation. Can you take an under-specified problem, split it into manageable pieces, decide which pieces matter most, and move through them to a solution? This is often the most important dimension and the one newcomers struggle with most. Typical failures:
- Not exploring the problem or gathering requirements before drawing.
- Spending time on trivial parts (the login page) instead of the hard ones (seat contention).
- Getting stuck on one piece and never moving on.
- Running out of time without a system that works end to end.
The cure is structure: a fixed sequence of steps you follow every time, such as the one in the Interview Framework. Structure gives you a track to run on when nerves hit.
2. Solution design. Once the problem is broken down, can you solve each piece and fit the pieces into one clean whole? Typical failures are weak fundamentals (not really knowing what a cache or a replica does), ignoring scale and performance, and "spaghetti design": arrows everywhere, unclear ownership of data, a diagram no one can follow. Interviewers also test whether you memorised answers. They push back, doubt a choice, or ask "what if this were 100 times bigger?". Only real understanding survives that.
3. Technical excellence. Do you know current technologies and well-known patterns, and can you apply them correctly? Typical failures: not knowing an obvious tool exists, reasoning with outdated hardware limits, naming a technology without knowing how it fits the problem, and missing standard patterns (pre-signed upload URLs, CDC, fan-out on write). The Key Technologies part of this handbook (for example PostgreSQL and Kafka) and Choosing Technologies are built for this dimension.
4. Communication and collaboration. The interviewer is also asking "what would it be like to design with this person?". Typical failures: explaining complex ideas unclearly, getting defensive when challenged, and diving so deep into one detail that the interviewer cannot steer you back. Treat hints as gifts. When the interviewer says "what about hot partitions?", they are pointing you at what they want to grade.
| Dimension | What a strong signal looks like | What a weak signal looks like |
|---|---|---|
| Problem navigation | Clear requirements in five minutes, the two hardest problems named early | Twenty minutes of drawing before asking how many users there are |
| Solution design | Every functional requirement traced through the diagram | Boxes that no request passes through |
| Technical excellence | "Postgres with a unique constraint on seat ID, because booking needs a transaction" | "We use NoSQL because it scales" |
| Communication | Thinking aloud, checking in, adapting to hints | Silence, or arguing with every question |
Breadth versus depth by level#
All levels must finish a working design that meets the requirements. What changes is how fast you get through the basics and how deep you go afterwards. A useful rule of thumb from interviewers:
| Level | Breadth : depth | What the interviewer expects |
|---|---|---|
| Mid-level | About 80 : 20 | A complete high-level design with sensible components. Expect probing on basics ("what does an API gateway actually do?"). You drive the start, and it is fine if the interviewer drives the later deep dives. |
| Senior | About 60 : 40 | Move quickly through the basics, then go deep on two or three hard parts with real technical detail. Name trade-offs and bottlenecks before you are asked. Some hints are acceptable. |
| Staff and above | About 40 : 60 | Breeze through standard parts (REST endpoints, normalisation). Spend most of the time on what is truly hard, drawing on real experience with the technologies. The interviewer should step in only to focus the conversation, not to steer it. |
For a concrete bar, take a ticket-booking prompt. A mid-level candidate defines the API and data model, gets viewing and booking working, and prevents double booking with at least a simple approach (a seat status with a timeout and a cleanup job). A senior candidate does that quickly and then goes deep on search (a search index, query caching), on a solid reservation mechanism (a distributed lock or equivalent), and on the surge when a huge show goes on sale. A staff candidate covers the same ground but also brings judgement from practice: which of these problems actually hurts in production, what the operational cost is, and how the design behaves when a dependency fails.
Leave a diagram someone can read tomorrow#
Interviewers often write their feedback hours later, after a day of meetings, from the diagram you left behind and their notes. A clean final diagram (labelled boxes, arrows in one direction, the data stores clearly marked, deep-dive changes folded back in) is part of your answer. Update the high-level diagram as you make deep-dive decisions, so the final picture shows the design you actually argued for.
How much preparation it takes#
If system design is new to you, plan for about three to four weeks of steady study, or a shorter period of very focused work. If you already know the core concepts or design systems at work, under a week can be enough to refresh. Two practical tips:
- Ask for time. Many recruiters would rather move the interview date than see you fail. Asking to push it back is normal.
- Practise applying, not just reading. A common failure is having read everything and then freezing when asked to produce a design. Do full timed mock designs out loud, then compare them with worked case studies such as Ticket Booking and URL Shortener.
If time is very short, prioritise in this order: learn the delivery framework, skim the key technologies so you know what exists, then study the core concepts (caching, sharding, replication, consistency). See Interview Levels and Preparation for a full plan.
Deep Dive: What changes as you go from mid-level to staffShow
The same question is judged differently by level.
A mid-level engineer is expected to produce a working design that covers the functional requirements and uses standard components correctly: a load balancer, stateless servers, a sensible database, a cache where reads dominate. Some guidance from the interviewer is expected.
A senior engineer is expected to drive the conversation, find the real bottlenecks with numbers, and go deep on two or three hard parts: how the feed is generated for users with millions of followers, how double booking is prevented, how a counter stays accurate under 100,000 increments per second. They should name failure modes without being asked.
A staff+ engineer is expected to show judgement: which problems matter most for the business, what to build versus buy, how the system evolves over years, how it fails across regions, what it costs to run, and how teams will own it. They can explain why a simpler design is better even when a complex one is possible.
There is also a difference between interview design and real design. Interviews compress the process into 45-60 minutes and reward breadth with a few deep dives. Real design adds things interviews skip: migration from the current system, team ownership, cost reviews, security and privacy reviews, rollout plans, on-call load, and the politics of shared infrastructure. Practise both mindsets. In an interview, mention a real-world concern in one sentence ("we would roll this out behind a feature flag and dual-write during migration") to show you know the difference.
Deep Dive: Why system design is hard, and how experts thinkShow
Emergent behaviour. Large systems behave in ways no single component does. A retry policy that is sensible for one client becomes a "retry storm" when 100,000 clients retry together after a brief outage, keeping the backend overloaded long after the original fault is gone. Researchers call these metastable failures: the system stays broken because of its own recovery mechanisms. Good designers think about the whole system's dynamics, not just each box.
Non-linear scaling. Doubling load rarely doubles cost smoothly. Queueing theory shows that as a server's utilisation approaches 100%, waiting time grows towards infinity. A server at 50% load might have 10 ms latency, at 80% about 25 ms, and at 95% over 100 ms. Designers keep headroom (often running at 50-70% peak utilisation) because of this curve. See Latency, Throughput and Performance.
Tail latency amplification. If one user request fans out to 100 servers in parallel and waits for all of them, the slowest server decides the response time. Even if each server is slow only 1% of the time, about 63% of such requests hit at least one slow server (1 - 0.99^100). Jeff Dean and Luiz André Barroso described this in "The Tail at Scale" (2013), along with fixes such as hedged requests.
Two kinds of decisions. Amazon popularised the distinction between "one-way doors" (decisions that are hard to reverse, such as the primary data model, the sharding key or a public API) and "two-way doors" (easy to reverse, such as a cache TTL or an instance size). Experts spend their care on one-way doors and move fast on two-way doors.
Start from the data. Experienced designers often start with the data rather than the services: what are the entities, how big are they, how fast do they grow, who reads and writes them, and how consistent must they be? Services and APIs follow from the data's access patterns. Martin Kleppmann's book "Designing Data-Intensive Applications" (2017) is built around this view.
Deep Dive: How deep 'knowing a building block' goes, using Kafka as the exampleShow
"I would put a queue here" is a sentence any candidate can say. What separates levels is how much you can say next. Kafka, a distributed append-only log used as a message queue and event stream, is a good example of the layers. Junior and mid-level engineers rarely need anything past the first layer. Senior engineers should know some of the rest, and staff engineers most of it. See Kafka for the full treatment.
Layer 1: what it is for. Producers append messages to a topic. The topic is split into partitions, each an ordered log on disk. Consumers read at their own pace and record how far they got (their offset). Messages are kept for a retention period (7 days by default, configurable by time or size), so several independent consumers can read the same stream and a consumer can replay history.
Layer 2: when you even need to scale it. As a rough rule, one well-provisioned broker can hold about a terabyte and handle up to around a million small messages per second, although the real figure depends on message size and hardware. If your estimate is far below that, say so and move on. If it is above, you add brokers, but adding brokers helps only if topics have enough partitions to spread across them. Partitions are the unit of parallelism: one consumer in a group reads each partition, so 12 partitions cap a consumer group at 12 parallel readers.
Layer 3: the partition key. Each message is placed by hash(key) % partitions (the Java client uses murmur2 by default). Messages with the same key stay in order on one partition. A good key spreads load evenly. A bad key creates a hot partition. In an ad-click pipeline keyed by ad ID, one viral advert can push most traffic onto a single partition. The usual remedies:
- No key, if ordering does not matter. Modern clients use a "sticky" partitioner that fills a batch for one partition and then rotates, giving roughly even spread.
- Salting: append a small random number (say 0-9) to the hot key, spreading it across 10 partitions, then merge the 10 partial results on the consumer side.
- A compound key, such as ad ID plus region, if the second attribute varies independently.
- Back-pressure: slow the producer when partition lag grows too high, if the requirements allow it.
Layer 4: durability. Each partition is replicated to several brokers (a replication factor of 3 is common: one leader and two followers). With acks=all, the producer's write is acknowledged only after all in-sync replicas have it, so losing one broker loses no acknowledged data. This is why practitioners say Kafka is "always available, sometimes consistent", and why "what if the whole Kafka cluster goes down?" is a less useful question than "what if a consumer dies?".
Layer 5: consumer failure and offset commits. When a consumer in a group dies, its partitions are rebalanced to the survivors, which resume from the last committed offsets. If a consumer did the work but crashed before committing, the message is processed again. That is at-least-once delivery, so processing must be idempotent. When you commit matters. A web crawler that commits the offset before saving the downloaded HTML to object storage can lose pages. Committing after the save is safe. Keeping each consumer's work small (for example, splitting crawling into "download" and "parse" stages) limits how much is redone after a crash.
Layer 6: retries and errors. Producers retry transient failures automatically. Turning on idempotent producer mode stops a retry from writing the message twice when the first attempt actually succeeded. Consumers have no built-in retry, so a common pattern is a separate retry topic with its own consumer, plus a dead-letter queue (DLQ) for messages that fail too many times, where engineers can inspect them. If built-in retries and DLQs matter more than replay and throughput, a managed queue such as Amazon SQS, which provides them out of the box, may be the better choice.
Layer 7: performance. Producers batch many messages per network request and can compress batches (GZIP, Snappy, LZ4, Zstandard), trading CPU for bandwidth. Even so, the largest performance lever is the partition key, because it decides parallelism.
The same layering exists for every block. For a cache: what it is for, the hit ratio you need, the key design, the write policy, eviction, invalidation, and stampede protection. For a database: data model, indexes, replication, partitioning, isolation level, and storage engine. Studying a block means walking down its layers until you can answer "and then what happens?" two or three times in a row.
Deep Dive: What is inside each building blockShow
Each block on the diagram hides one or two core mechanisms. Knowing them turns the boxes from magic into machines you can reason about.
DNS is a hierarchical, cached database. A resolver asks a root server which servers handle .com, asks those which servers handle example.com, then asks the authoritative server for the record. Every answer carries a TTL, and every layer (browser, operating system, ISP resolver) caches it, which is why DNS is fast on a hit and slow to change. Large providers use anycast, announcing the same IP address from many locations so the network routes each user to the nearest server.
CDN edge servers are mostly large HTTP caches. A request reaches the nearest point of presence, usually via anycast or DNS steering. On a miss, the edge fetches from a regional tier or from your origin. HTTP headers such as Cache-Control: max-age=86400 tell the edge how long a response may be reused. Hit ratios of 90% or more are common for static assets, which is where the bandwidth savings come from.
Load balancers keep a list of healthy backends, updated by health checks every few seconds, and pick one per connection (layer 4) or per request (layer 7). Common policies are round robin, least connections, and hashing on a key so the same client or the same cache key reaches the same server. Consistent hashing keeps most keys in place when a server is added or removed.
App servers are processes with a thread pool or an event loop. Their capacity is set by how long each request holds a thread or a connection, which is why a slow downstream call can exhaust a server that has idle CPU. Little's law (concurrency equals arrival rate times time in system) gives the sizing: 2,000 requests per second at 50 ms each means 100 requests in flight.
Databases combine a storage engine with a query layer. Most relational databases use a B-tree on disk, which is good for reads and range scans, plus a write-ahead log (WAL) so a crash cannot lose a committed transaction. Many NoSQL stores use an LSM tree instead, which buffers writes in memory, flushes them as sorted files and merges those files in the background. LSM trees favour heavy writes at some cost to reads. See Storage Engines.
Caches such as Redis and Memcached are in-memory hash tables with an eviction policy (often an approximation of least-recently-used). Because a lookup is a hash and a memory read, the server-side work takes microseconds. The 0.5-1 ms you observe is mostly the network round trip.
Message queues and logs are either per-message queues, where each message is delivered, acknowledged and deleted (RabbitMQ, SQS), or append-only logs, where messages stay and consumers track offsets (Kafka). The first is natural for task distribution. The second is natural for event streams that several consumers replay.
Object stores split large objects into chunks spread across many disks and machines, and protect them with replication or erasure coding. An erasure code such as Reed-Solomon stores k data fragments plus m parity fragments, so any k of the k+m fragments rebuild the object. That gives high durability at roughly 1.5x storage overhead instead of the 3x of triple replication.
Search indexes are built around an inverted index: for each term, a sorted list of the documents that contain it. A query intersects lists, then scores documents with a relevance formula such as BM25. The index is split into shards, each with replicas, and it is refreshed from the source of truth, so it is usually a second or so behind.
Monitoring is three data types. Metrics are numeric time series that are cheap to store and good for alerts. Logs are discrete events that are rich but expensive at volume. Traces follow one request across services, which is how you find which hop caused a slow p99.
Key Takeaways#
- System design means choosing components, interactions and data placement so a system meets both functional and quality goals.
- High-level design covers services, data stores and their interactions; low-level design covers the code inside one service; HLD decisions are the expensive ones to reverse.
- Almost every system uses the client-server model, where clients are untrusted, servers are controlled, and the network between them is unreliable.
- Most web systems combine the same building blocks: DNS, CDN, load balancer, app servers, database, cache, queue, object store, search and monitoring.
- Functional requirements decide features; non-functional requirements (latency, scale, availability, durability, consistency, cost) decide architecture.
- Every choice is a trade-off; state what you gain and what you pay, with numbers.
- Distributed systems break single-machine intuitions: the network is unreliable, latency is not zero, and failures are routine.
- Interviewers grade the process: requirements, estimates, a working design, then trade-off-driven deep dives, judged more strictly at higher levels.
- Add a building block only when a number or a requirement forces it. Name the bottleneck, say what the block holds, pick the variant and handle its main downside.
- Large payloads go in an object store. Databases, queues and caches carry a pointer to them.
- Decide consistency against availability per feature, early, because it shapes the database, replication and caching choices.
- Modern hardware is large: one database node holds terabytes, and one cache node serves about 100,000 operations per second. Check current numbers before adding complexity.
- Product design problems are about features and user-facing flows. Infrastructure design problems are about one building block's internals, guarantees and failure behaviour.
- Interviewers grade problem navigation, solution design, technical excellence, and communication and collaboration. The balance shifts from breadth toward depth as the level rises.