Summary#
Systems are not designed at full size on day one; they grow one bottleneck at a time. A typical path is: a single server running everything; a separate database; vertical scaling (a bigger machine) until it gets too expensive or risky; a load balancer with a stateless web tier so you can add servers; session storage moved out of the servers; database replication for read capacity and failover; a cache for hot reads; a CDN for static content; a message queue for slow or spiky work; multiple data centers for global users and disaster recovery; and sharding when one database primary cannot hold the writes or the data. Throughout, you add logging, metrics and automation, because you cannot scale what you cannot see or repeat. The key skill is knowing the trigger (the measured symptom) that justifies each step, because every component you add also adds cost and new ways to fail.
Why It Exists#
New engineers often draw the "final" architecture, with dozens of services, Kafka, Kubernetes and five databases, for a product that has a hundred users. Experienced engineers do the opposite: they start with the simplest design that works and add complexity only when a real limit appears. There are good reasons for this:
- Complexity has a cost. Every new component needs to be built, deployed, monitored, secured, paid for and understood by everyone on call.
- You do not know the future load shape. You may expect a write-heavy app and discover it is 99% reads. Premature sharding on the wrong key is worse than no sharding.
- Most bottlenecks are predictable. The same sequence of limits appears in almost every web product, so if you know the sequence, you can see the next step coming and prepare for it.
This page walks through that sequence. It is also the backbone of many interview answers: start simple, find the bottleneck, fix it, repeat. It builds on What Is System Design?, and each step links to the page that covers it in depth.
How It Works#
The stages below follow a hypothetical photo-sharing app. The numbers are approximate but realistic, and the point is the trigger for each change.
| Users (DAU) | Peak requests/s | Typical architecture |
|---|---|---|
| 1-1,000 | under 10 | One server, everything on it |
| 1k-50k | 10-500 | App server + separate managed database |
| 50k-500k | 500-5,000 | Load balancer, several stateless app servers, shared session store, read replica, cache, CDN |
| 500k-10M | 5k-100k | Queues and workers, autoscaling, multiple replicas, heavy caching, a few services |
| 10M+ | 100k+ | Multiple regions, sharded databases, many services, dedicated platform teams |
These ranges overlap widely. A simple app with light requests can serve millions of users on very little hardware; a compute-heavy app may need the later stages much earlier.
Stage 1: A single server#
Everything runs on one machine: the web server, application code, database and uploaded files. DNS points the domain to the machine's IP address.
- Why it is right at first: cheapest, simplest to deploy and debug, no network calls between components, one place to look when something breaks.
- What it can handle: a modern server with 8-16 vCPUs and 32-64 GB of RAM can serve hundreds to a few thousand simple dynamic requests per second, which is far more than most new products ever need.
- Its weaknesses: it is a single point of failure (SPOF): if it dies, the product is down and data may be lost if backups are missing. The application and database compete for the same CPU, memory and disk, so a heavy query slows every page.
Trigger to move on: CPU or memory is regularly above 60-70% at peak, the database and app fight for resources, or the business cannot tolerate the risk of losing the one machine.
Stage 2: Separate the database#
Move the database to its own server, or better, to a managed database (Amazon RDS, Google Cloud SQL, Azure Database). Now the web tier and data tier can be sized, tuned and scaled independently.
- The app connects to the database over the network, adding about 0.5 ms per query inside a data center; this is negligible compared with the benefit.
- A managed service handles backups, patching, point-in-time recovery and a standby replica for failover.
- Uploaded files move to object storage (such as Amazon S3) instead of the server's disk, so the server holds no important data. See Object Storage.
Which database? For most products, a relational database (PostgreSQL or MySQL) is the right default: transactions, flexible queries and mature tools. NoSQL stores fit specific needs (huge write volumes, simple key-based access, flexible documents). See SQL vs NoSQL.
Trigger to move on: the web server is now the bottleneck (CPU-bound request handling), or you need zero-downtime deploys and protection from the web server failing.
Getting files off the server#
The first file-upload design most people build is to have the app server accept the file and write it to its local disk, with a metadata row in the database. For a small application this works. It fails in two ways as the product grows:
- Capacity. Files accumulate forever. The disk fills, so you buy bigger disks, then more servers. Now a file lives on whichever server received it, and every other server needs a way to find and fetch it.
- Reliability. If that server's disk fails, or the server is terminated, its files are gone. A backup restores yesterday's files, not this morning's.
The fix is object storage (blob storage), such as Amazon S3, Google Cloud Storage or Azure Blob Storage. It stores each object redundantly across devices and data centres, scales without capacity planning, and is far cheaper per GB than database or block storage. The database keeps only metadata: owner, size, content type and the object's key.
A further step removes the app server from the data path entirely. The client asks the app server for permission to upload. The server checks the request and returns a pre-signed URL: a time-limited URL that allows exactly one upload to one object key. The client then sends the bytes straight to object storage.
Now a 2 GB video does not tie up an app server thread for minutes, and the web tier sizes only for small API calls. Large files can use multipart upload, sending parts in parallel and retrying only the parts that fail. Downloads work the same way: pre-signed GET URLs, usually served through a CDN. See Object Storage.
Stage 3: Vertical scaling and its limits#
The first response to load is often vertical scaling (scaling up): moving to a machine with more CPU, RAM or faster disks. It needs no code changes, and it is often the right first step, especially for the database.
Its limits are real:
- Hardware ceiling: the largest cloud instances have a few hundred vCPUs and several terabytes of RAM. Beyond that, there is no bigger box.
- Non-linear cost: the biggest machines cost much more per unit of capacity than mid-sized ones.
- Still a single point of failure: a bigger machine fails just like a small one.
- Downtime to resize: moving to a larger instance often means a restart or failover.
- Diminishing returns: software may not use 128 cores efficiently because of locks or single-threaded parts.
Horizontal scaling (scaling out), adding more machines of the same size, has no hard ceiling and removes single points of failure, but it requires the software to work across many machines. Every stage after this is about making horizontal scaling possible. See Vertical vs Horizontal Scaling.
Trigger to move on: the next instance size costs too much, you are near the largest size, or a single web server is an unacceptable risk.
Stage 4: Load balancer and a stateless web tier#
Put a load balancer in front of several identical app servers. DNS now points at the load balancer, which forwards each request to a healthy server and stops sending traffic to servers that fail their health checks. You can add or remove servers, deploy one at a time, and survive the loss of any single server.
This only works if the app servers are stateless: they keep no user-specific data in local memory or on local disk between requests. If server 1 remembers that Asha is logged in, and her next request goes to server 2, she is suddenly logged out. Anything that must persist goes to a shared store: the database, a cache, object storage or a session store.
A load balancer also gives you a place to terminate TLS, enforce timeouts, and route by path (/api to one group of servers, /images to another). See Load Balancing.
Trigger: one app server cannot handle peak traffic, or you need high availability for the web tier and zero-downtime deploys.
Stage 5: Session storage#
A session is what the server remembers about a logged-in user between requests: who they are, their cart, their preferences. Once there are many servers, you need a strategy:
| Option | How it works | Pros | Cons |
|---|---|---|---|
| Sticky sessions | The load balancer sends each user to the same server (by cookie) | No code change | Uneven load; sessions lost when that server dies; harder to scale down |
| Shared session store | Sessions stored in Redis or Memcached; any server can read them | Servers fully stateless; fast (~1 ms) | One more system to run and keep available |
| Database sessions | Sessions in a database table | Simple, durable | Adds load to the database on every request |
| Client-side tokens | A signed cookie or token (such as a JWT) holds the session data | No server storage at all | Hard to revoke before expiry; size limits; must be signed and often encrypted |
A shared store such as Redis, with session keys expiring after a period of inactivity, is the most common choice. Token-based sessions are common for APIs and mobile apps, usually with short-lived access tokens and a revocable refresh token. See Authentication and Authorization.
Stage 6: Database replication#
The database is now the bottleneck: every app server sends queries to one machine. Most web apps are read-heavy (often 10 to 100 reads per write), so the next step is replication:
- One primary (leader) accepts all writes.
- One or more read replicas (followers) receive a copy of every change and serve read queries.
- If the primary fails, a replica is promoted to become the new primary (automatically with managed databases, typically within tens of seconds to a couple of minutes).
Replication brings two big benefits, read capacity and availability, and one big catch: replication lag. Replicas are usually a few milliseconds to a few seconds behind. If a user updates their profile and the next page reads from a lagging replica, they see the old profile. A common fix is read-your-writes: read from the primary for a short time after a user's own write, or for the user's own data. See Replication.
Trigger: the primary's CPU or I/O is saturated by reads, or the business needs the database to survive a machine failure with minimal downtime.
Connection pooling: a limit that arrives early#
Adding app servers multiplies database connections, and many relational databases handle large connection counts poorly. In PostgreSQL, for example, each connection is a separate server process using memory. The default limit is 100 connections, and performance often degrades well before a few thousand.
The arithmetic catches teams by surprise. Fifty app servers, each with a pool of 20 connections, want 1,000 connections, even if most of them are idle. Autoscaling makes it worse: a traffic spike adds servers, each opens its pool, and the database runs out of connections at the moment it is busiest.
The fixes, in order:
- Size pools from Little's law. Connections needed is roughly queries per second × average query time. At 5,000 queries per second and 2 ms each, about 10 connections are busy at once. A pool of 20 per server is often far more than needed.
- Add a connection pooler such as PgBouncer or a managed proxy (for example, Amazon RDS Proxy). Thousands of client connections are multiplexed onto a few dozen real database connections.
- Keep transactions short, so connections return to the pool quickly. A transaction that waits on an external API call holds a connection for the whole wait.
Trigger: connection errors or rising latency when the app tier scales out, or the database's connection count approaching its limit while CPU is still low.
Stage 7: Cache#
Many reads ask for the same data again and again: the home page, popular posts, user profiles. A cache keeps that data in memory (Redis or Memcached), where a read takes about 0.5-1 ms instead of 5-50 ms for a database query.
The most common pattern is cache-aside: the app looks in the cache first; on a miss, it reads the database and stores the result in the cache with an expiry time (TTL).
The effect on the database is dramatic. If the app makes 20,000 reads per second and the cache answers 95% of them (a 95% hit ratio), the database sees only 1,000. At 99%, it sees 200. That is why caches usually come before sharding: they are far cheaper and simpler.
The cost is staleness: the cache may hold old data after the database changes. You manage that with TTLs and by deleting cache entries when data changes. See Caching Fundamentals and Caching Strategies.
Trigger: the same queries dominate database load, read latency is too high, or replicas are multiplying just to handle repeated reads.
Hot keys: millions of reads for the same item#
A cache spreads keys across nodes, so a cluster with ten nodes has roughly ten times the capacity of one. That stops being true when one key is far more popular than the rest. A viral post, the home page or the ticket page for a big concert can receive hundreds of thousands of reads per second. All of them hash to the same cache node, which saturates its CPU or network while the other nodes sit idle.
Several techniques handle hot keys. They are usually combined:
- A local in-process cache. Each app server keeps the hottest items in its own memory for a short time, such as 1-5 seconds. With 100 app servers, the shared cache sees at most about one request per item per server per second, instead of every read.
- Key replication. Store the hot item under several keys (
post:42#1topost:42#8) on different nodes, and have readers pick one at random. Writes update all copies. - Request coalescing. When many requests miss on the same key at once, only one goes to the database. The others wait for its result. This prevents a cache stampede, where a popular key expires and thousands of requests hit the database together.
- Early refresh. Refresh popular entries shortly before they expire, or let a background job keep them warm, so they never expire under load.
- Push it to the edge. If the content is the same for everyone, a CDN with a short TTL can serve it from hundreds of locations, and the origin sees only a trickle.
The trade-off is freshness. Every layer adds a few seconds of possible staleness. For a like count or a news article that is fine. For a seat map at a ticket sale, the cached page can show availability, while the booking step itself goes to the authoritative store. See Distributed Caching.
Stage 8: CDN#
Static files (images, video, CSS, JavaScript, fonts) are often 80-95% of the bytes a site serves. A CDN (Content Delivery Network) caches them on servers in hundreds of cities. A user in Sydney gets the photo from a Sydney edge server in 10-20 ms instead of from Virginia in 200 ms, and your servers no longer serve those bytes at all.
Files get versioned names (such as app.3f9c1b.js) so they can be cached for a year and replaced instantly by changing the name. Modern CDNs also cache API responses for anonymous users, terminate TLS near users and absorb DDoS attacks. See CDN.
Trigger: bandwidth costs are high, far-away users see slow page loads, or static traffic is a large share of server load.
Stage 9: Message queue#
Some work does not need to finish before the user gets a response: generating thumbnails, sending emails and notifications, updating search indexes, running fraud checks. Doing it inside the request makes users wait and makes the web tier fragile.
A message queue (Amazon SQS, RabbitMQ, or a stream such as Kafka) lets the web server record "this work needs doing" and return immediately. Workers pull jobs from the queue and process them at their own pace.
- Faster responses: the upload request returns in 100 ms, not 3 seconds.
- Spike absorption: if 50,000 photos arrive in one minute, the queue holds them and workers catch up.
- Failure isolation: if the email provider is down, jobs wait and retry; uploads keep working.
- Independent scaling: add workers based on queue length.
The cost is that results arrive later (eventual completion), and you must handle retries and duplicate processing. See Message Queues.
Trigger: slow operations inside requests, spiky workloads, or tasks that call unreliable external services.
When the queue itself becomes the bottleneck#
A queue absorbs spikes, but it is a system with its own limits, and it fails in ways that are easy to miss. Slack's engineers published a post-mortem-style account of an incident with their job queue, which was built on Redis. It is a good illustration:
- Contention in the database slowed the jobs that workers were running.
- Jobs piled up in Redis faster than they drained, until Redis reached its configured memory limit.
- Once Redis was full, enqueues failed, and with them every product feature that depended on the queue.
- The database recovered, but the queue did not. Taking a job off the queue meant moving it to a "processing" list, and that move needed free memory, which a full Redis did not have. Draining the queue required manual intervention.
The write-up found further structural problems:
- every client connected to every Redis instance, so connections grew with the product of the two counts;
- adding workers added polling load on Redis, so adding capacity could make an overloaded queue worse;
- dequeue cost grew with queue length, so the queue slowed down exactly when it most needed to drain;
- the queue's exact delivery and deduplication semantics had never been written down, so engineers were wary of building on it or changing it.
The root cause was structural. The burst buffer (the backlog of waiting jobs) and the dispatch workspace (in-flight lists, deduplication index, retry bookkeeping) shared one bounded pool of RAM. Under overload, that design ends in lockup rather than lag.
Slack's fix, described in a 2017 post, was deliberately small. At the time the queue handled over a billion jobs on busy days, with peaks in the tens of thousands per second. Rather than rewrite the queue, they put Kafka in front of Redis:
- The web app enqueues into Kafka through a small stateless gateway service. The backlog now lives on disk, bounded by a retention period rather than by RAM, so a flood of jobs makes the log longer instead of filling memory.
- A relay service drains each Kafka topic into its Redis cluster at a controlled rate. It commits its Kafka offset only after a job is safely in Redis, so nothing is lost if Redis is down. It simply waits and retries while the log absorbs new work behind it.
- Redis keeps only the short window of jobs that workers are actually draining, with the job semantics the application already depended on. Operators can turn the relay rate down during an incident to match what workers can execute.
The rollout is a model of safe change. Jobs were first written to both paths while the new relay ran in shadow mode, reading everything and discarding it. Jobs were counted at every hop, a canary job was sent through every partition every minute, and job types were moved to the new path one at a time. One surprise came from mixing runtimes: two languages serialised the same JSON with different escaping, which produced different bytes for the same job.
The lessons generalise to any queue:
- Bound the queue and decide what happens when it is full. Reject new work with a clear error, shed low-priority work, or spill to disk. Never let it fail in an undefined way.
- Make draining cheap. Dequeue and acknowledge should cost the same at any queue length, and must not need resources the full queue has run out of.
- Monitor the age of the oldest message, not just the queue length. Age tells you how far behind you are in time, which is what users feel.
- Keep the backlog somewhere that cannot run out of memory. A durable, disk-backed log (such as Kafka) or a managed queue (such as SQS) holds large backlogs. Let the fast in-memory layer hold only the work in flight.
- Write down the semantics: at-least-once or at-most-once delivery, ordering, deduplication and retry policy.
See Message Queues and Pattern: Long-Running Tasks.
Stage 10: Multiple data centers#
With users across continents, or a business that cannot afford a full-region outage, you run in multiple data centers (cloud regions).
- GeoDNS or anycast routes each user to the nearest healthy region.
- Stateless tiers are easy to copy to each region.
- Data is the hard part. Options range from active-passive (one region takes writes; others hold replicas and take over on disaster) to active-active (every region takes writes, with conflict resolution or data partitioned by user's home region).
- Cross-region round trips are 70-200 ms, so synchronous replication across regions makes every write slow; most systems replicate asynchronously and accept a small risk of losing the last seconds of writes in a disaster.
Before going multi-region, most companies first use several availability zones (separate data centers within one region, 1-2 ms apart), which protects against most failures at much lower complexity. See Multi-Region and Global Data.
Trigger: latency for distant users is too high, a full-region outage is unacceptable, or data residency laws require data to stay in a country or region.
Stage 11: Sharding#
Eventually one primary database cannot keep up: too many writes per second (a single primary typically handles roughly 5,000-20,000 write transactions per second, depending on hardware and workload), or too much data (tens of terabytes make backups, restores and schema changes painful). Replicas do not help, because every replica must apply every write.
Sharding (horizontal partitioning) splits the data across several independent databases, each holding a subset of rows, chosen by a shard key such as user_id:
- User 1-1,000,000 on shard 1, the next million on shard 2; or more commonly,
hash(user_id)decides the shard, which spreads load evenly. - Each shard has its own primary and replicas, so write capacity grows with the number of shards.
Sharding is powerful but expensive in complexity:
- Cross-shard queries ("top posts across all users") need to query every shard and merge results.
- Cross-shard transactions are hard; design so that most operations touch one shard.
- Hot shards: a celebrity's data can overload one shard.
- Resharding (adding shards) means moving data while the system is live; techniques such as consistent hashing and many small logical shards make it easier.
That is why sharding comes late, after caching, replication and query optimisation are exhausted. See Partitioning and Sharding.
Trigger: write throughput or data size exceeds what one primary can handle with headroom, even after optimisation and vertical scaling.
Sharding is often built in now. Many modern databases shard for you. Cassandra and DynamoDB partition every table by a partition key from the start. MongoDB has native sharding. Vitess (for MySQL) and Citus (for PostgreSQL) add sharding on top of a familiar relational engine. Spanner and CockroachDB split data into ranges automatically and move them as they grow. With these systems, "sharding" is less about building routing code and more about choosing the partition key well. The key decides which queries stay on one node, where hot spots appear and how evenly data spreads. The hard thinking does not go away. It moves from the code into the schema. See Partitioning and Sharding.
Separate analytics from serving#
As the product grows, someone asks for reports: daily active users, revenue by country, clicks per ad per minute. Running those queries on the production database is a classic mistake. A query that scans a month of orders competes with checkout for CPU, I/O and buffer cache, and checkout loses.
The standard step is to split the transactional workload (OLTP: many small reads and writes of individual rows) from the analytical workload (OLAP: few large queries that scan and aggregate millions of rows). An ad-click system shows the pattern clearly:
- Each raw click is written to an event store built for heavy writes. Cassandra is a common choice. It is an LSM-tree store: writes go to an append-only commit log for durability and to an in-memory sorted table (a memtable), which is flushed to immutable sorted files (SSTables). That makes writes cheap, but scans and aggregations are not its strength.
- Every few minutes, a batch job, for example in Apache Spark, reads the new raw events, groups them by ad ID and minute, and counts them.
- The results go into an analytical database with columnar storage, such as Amazon Redshift, Snowflake or Google BigQuery, where sums and counts over millions of rows are fast.
- Advertisers query the pre-aggregated table, so their dashboards respond in well under a second.
It is worth estimating the batch size before reaching for a big framework. At 10,000 clicks per second, a 5-minute batch has 3 million events. At about 100 bytes each, that is about 300 MB, which one machine can process easily. Spark is still a reasonable choice, because it scales out if volume grows and its map-reduce model is easy to explain, but the estimate shows it is not strictly required.
Why columnar OLAP rather than a time-series database? Time-series databases (InfluxDB, TimescaleDB) are excellent when queries look like "metric X over time range Y" with relatively few distinct series. Ad analytics has millions of ad IDs and will soon be sliced by device, country and campaign. High-cardinality, multi-dimensional queries are what columnar OLAP engines are built for. If the requirements really are only simple time-range queries, a time-series database is a perfectly reasonable proposal.
The batch design has two weaknesses that drive the next step:
- Freshness. Data is always at least one batch interval old.
- Spikes cascade. A burst of clicks puts write pressure on the event store and makes the next batch larger. If a batch takes longer than its interval, the next one starts late and is bigger still, so the data falls further behind exactly when advertisers are watching a big campaign launch.
A queue in front of the event store smooths the write spikes, but it does not fix freshness. Fixing both leads to stream processing: a consumer such as Apache Flink reads events from a log and keeps per-minute counts continuously. See Pub/Sub and Event Streaming.
Trigger: reporting queries slow down production, analysts need joins across many tables, or the business wants dashboards fresher than a nightly export.
Split services and add specialised stores#
At some point, the single application becomes the bottleneck for people rather than machines. Dozens of engineers deploy one codebase, every change risks every feature, and one slow endpoint can exhaust the shared thread pool. This is when teams split out services along clear boundaries, such as payments, search, notifications and media processing, each with its own deploys and often its own data store.
The same stage usually brings specialised stores:
- a search index (Elasticsearch or OpenSearch) for full-text queries the primary database handles poorly, kept in sync from the database through a queue or change data capture;
- a wide-column or key-value store for very high write rates or simple key access (Cassandra, DynamoDB);
- a graph store or precomputed adjacency lists for social graphs;
- object storage plus a data lake for raw history.
Each new store is another copy of data that can drift, so the question "which store is the source of truth for this field?" must have one clear answer. Splitting services is an organisational decision as much as a technical one. Many teams do well for a long time with a modular monolith: one deployable unit with strict internal boundaries. See Monolith vs Microservices.
Trigger: deploys are blocked by coordination between teams, one component's load or failures regularly affect unrelated features, or a workload needs a data store the main database cannot provide.
Across all stages: logging, metrics and automation#
You cannot scale what you cannot see, and you cannot run 500 servers by hand. From the first server onwards, invest in:
- Logging: structured logs (JSON with request ID, user ID, latency) shipped to a central place (ELK/OpenSearch, Loki, a cloud service).
- Metrics: request rate, error rate and latency percentiles (p50, p95, p99) per endpoint; CPU, memory, disk and connection counts per machine; queue depth; cache hit ratio; replication lag. Prometheus and Grafana, or a hosted service such as Datadog.
- Tracing: once there are several services, distributed traces (OpenTelemetry) show where a slow request spent its time.
- Alerting: alerts on user-facing symptoms (errors, latency) rather than every CPU spike.
- Automation: infrastructure as code (Terraform), CI/CD pipelines for safe deploys, autoscaling of stateless tiers based on load, and automated backups with tested restores.
Metrics are also how you find the trigger for the next stage. "The database feels slow" is not a reason to shard; "the primary is at 85% CPU at peak, 70% of queries are the same 20 reads, and cache hit ratio is 0%" is a reason to add a cache. See Observability.
The full picture at large scale#
Put together, a large consumer system after all these stages looks roughly like this. Few systems need every box, and each box should be there because a trigger justified it.
The trigger that justifies each step#
| Step | Trigger (measured symptom) | What it buys | What it costs |
|---|---|---|---|
| Separate database | App and DB compete for CPU/RAM; need managed backups | Independent scaling and tuning | Network hop, one more system |
| Vertical scaling | A tier is at 60-70%+ utilisation at peak | Quick capacity with no code change | Cost, hard ceiling, still a SPOF |
| Load balancer + stateless tier | One app server cannot handle peak, or its failure is unacceptable | Horizontal scaling, high availability | Must remove local state |
| Shared session store | Users logged out when moved between servers | Truly stateless servers | A store to keep available |
| Read replicas | DB CPU/I/O saturated by reads; need failover | Read capacity, availability | Replication lag |
| Cache | Repeated hot reads dominate DB load or latency | 10-100x fewer DB reads, ~1 ms reads | Staleness, invalidation |
| CDN | Static bytes dominate bandwidth; distant users slow | Lower latency and bandwidth cost | Cache invalidation, vendor cost |
| Message queue | Slow or spiky work inside requests | Fast responses, spike absorption | Eventual results, retries, duplicates |
| Multiple data centers | Distant users slow; region outage unacceptable; data residency | Lower global latency, disaster recovery | Data replication complexity, cost |
| Sharding | Writes or data size exceed one primary | Write and storage scale-out | Cross-shard queries and transactions |
| Object storage with pre-signed URLs | Files fill local disks; uploads tie up app servers | Unlimited, durable file storage off the web tier | Upload flow and lifecycle rules to manage |
| Connection pooler | Connection errors as the app tier scales out | Thousands of clients on a few dozen connections | One more hop; session features limited in some pooling modes |
| Hot-key defences | One cache node saturated while others idle | Survives viral items and stampedes | Extra staleness; more cache logic |
| Durable queue in front of workers | Backlogs exhaust an in-memory queue | Backlog on disk; controlled drain rate | Another system; end-to-end latency during backlogs |
| Separate OLAP store | Reports slow down production | Fast analytics, isolated from OLTP | Pipeline to run; data is minutes old |
| Split services and specialised stores | Team coordination blocks deploys; one workload needs a different store | Independent deploys, fit-for-purpose storage | Network calls, data copies that can drift |
| Observability and automation | From day one; essential before 5+ servers | Find the next bottleneck; safe changes | Engineering time, tooling cost |
When to Use It#
- Planning a new product: start at stage 1 or 2, and write down which metrics would trigger each next step.
- Diagnosing a growing system: find which stage you are at and which symptom you are seeing.
- Interviews: when asked to "scale this design", walk the stages in order, driven by the numbers from your estimates.
- Capacity reviews: before a launch or seasonal peak, check each tier's headroom against the expected load.
When NOT to Use It#
- Do not follow the stages blindly. A video-processing service may need queues and workers on day one; a read-only documentation site may need only a CDN and object storage forever.
- Do not add a stage "for future scale" without a trigger; each one adds cost and failure modes.
- Not every system follows this order. Serverless platforms and managed databases (DynamoDB, Spanner, Aurora) collapse several stages into a configuration change, though the underlying trade-offs remain.
How to Implement It#
- Start simple: one app server (or a managed platform such as a PaaS) and one managed database, with automated backups.
- Keep the app stateless from day one: sessions in a shared store or signed tokens, files in object storage. This makes stage 4 a configuration change later.
- Instrument everything: request rate, errors and latency percentiles, plus resource metrics, from the first deploy.
- Define triggers: for each tier, write the threshold that triggers action (for example, "database CPU above 70% at peak for a week").
- Load test before launches, so you find the next bottleneck in staging rather than in production.
- Scale the cheapest way first: optimise queries and add indexes, then add caching, then replicas, then vertical scaling of the database, and shard last.
- Automate deployment and infrastructure before you have many servers.
- Rehearse failures: kill a server, fail over the database, and restore a backup on a schedule.
# Example scaling triggers (one-line runbook entries)
web tier: p99 latency > 300 ms OR CPU > 65% for 15 min -> autoscale +2 instances
database: primary CPU > 70% at daily peak for 7 days -> review slow queries, add cache, add replica
cache: hit ratio < 90% on hot endpoints -> review keys and TTLs, add memory
queue: oldest message age > 5 min -> add workers, check failing jobs
storage: database size growth > 50% of disk within 6 mo -> plan archiving or sharding
region: > 30% of users with RTT > 150 ms to origin -> CDN for dynamic content, consider 2nd region| Technology | Fits when |
|---|---|
| A PaaS (Heroku, Render, Google App Engine, AWS Elastic Beanstalk) | Stages 1-4 with minimal operations work |
| Amazon RDS / Aurora, Cloud SQL, Azure Database | Managed relational database with replicas and failover |
| AWS ALB, Google Cloud Load Balancing, NGINX, HAProxy | Load balancing the web tier |
| Redis / Memcached (or ElastiCache, Memorystore) | Session store and cache |
| CloudFront, Cloudflare, Fastly, Akamai | CDN |
| SQS, RabbitMQ, Kafka | Queues and streams for async work |
| Vitess, Citus, DynamoDB, Cassandra, CockroachDB | When sharding is needed |
| Prometheus + Grafana, Datadog, OpenTelemetry | Metrics, dashboards and tracing |
| Terraform, Kubernetes, CI/CD pipelines | Automation at many servers |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Stay on one big server | Simplicity, low cost, fast development | Single point of failure, hard ceiling | Early products, internal tools |
| Scale out the web tier | Availability, elastic capacity | Must be stateless; load balancer to run | As soon as downtime matters |
| Sticky sessions | No code change | Uneven load, session loss on failure | Short-term stopgap only |
| Shared session store | Stateless servers | One more dependency | Default for server-side sessions |
| Read replicas | Read scale, failover | Stale reads | Read-heavy workloads |
| Cache before sharding | Cheap, huge read offload | Staleness | Almost always first |
| Multi-AZ before multi-region | Survives data center failures cheaply | Does not help distant users or region outages | Most businesses |
| Shard early | Avoids a painful migration later | Complexity from day one, risk of the wrong key | Only with very confident growth forecasts |
Common Pitfalls#
- Building the "final" architecture first and spending months on infrastructure instead of the product.
- Keeping state (sessions, uploads, in-memory caches that must be consistent) on app servers, which blocks horizontal scaling.
- Adding replicas without handling replication lag, so users see their own changes disappear.
- Sharding before trying indexes, query fixes, caching and a bigger database machine.
- Picking a shard key that creates hot shards or forces most queries to hit every shard.
- Scaling without metrics, so each change is a guess.
- Forgetting that the database, not the web tier, is usually the hardest part to scale.
- Testing backups never, and discovering during an incident that restores do not work.
- Storing uploaded files on app servers' local disks, which blocks scaling and loses files when a server dies.
- Letting every new app server open a large database connection pool until the database runs out of connections.
- Assuming a bigger cache cluster fixes a hot key; one key still lands on one node.
- Treating the queue as infinitely elastic; an in-memory queue that fills up can stop accepting and handing out work.
- Running analytical queries on the production database, so reports slow down checkout.
- Migrating data with naive dual writes and no reconciliation, so the old and new stores diverge silently.
- Restarting a whole cache cluster at once, sending the full read load to a database that cannot take it.
Real-World Examples#
Instagram's engineering blog described its early stack in 2011 as Django app servers behind load balancers, PostgreSQL, Redis, Memcached, and Amazon S3 with CloudFront for photos, run by a very small team. In 2012 it described sharding PostgreSQL into thousands of logical shards mapped onto fewer physical database servers, generating IDs that embed the shard number.
Stack Overflow's engineers have described serving a very large site from a small number of powerful SQL Server machines and web servers, a well-known example of how far vertical scaling, caching and careful query tuning can go before sharding is needed.
Typical scenario: a consumer app goes viral overnight. Teams that kept their app servers stateless and their assets on a CDN survive by raising the autoscaling limit; teams that stored sessions in server memory or files on local disk spend the night migrating under load.
Slack's engineering team has written publicly about the incident in which its Redis-based job queue filled up during a database slowdown and could not drain on its own after the database recovered. Their fix put Kafka in front of Redis as a durable buffer, with a relay that feeds Redis at a controlled rate, and left the application's queue semantics unchanged. It is a useful reminder that each scaling component, including the queue added to absorb load, has its own capacity limits and failure modes.
WhatsApp's engineers described reaching around two million concurrent connections on a single server in 2012, using Erlang on FreeBSD. It shows how far careful vertical tuning of one stage, here the connection tier, can go before horizontal scale-out is needed.
Figma's engineering team has described scaling its PostgreSQL setup by first splitting groups of tables onto separate databases (vertical partitioning), and only later sharding individual large tables horizontally. It follows this page's order: exhaust the simpler steps before taking on the cost of sharding.
In the Interview#
Scaling a design in the interview: the bottleneck walk#
When an interviewer says "now scale it", a structured walk works better than adding boxes at random. For each tier in the request path, in order, ask three questions:
- What is the load on this tier at peak? Use your estimates: requests per second, bytes per second, connections, data size.
- What is the limit of one instance? About 1,000-10,000 simple requests per second per app server, about 10k writes per second per relational primary, about 100k+ operations per second per Redis node, a NIC of 10-25 Gbps.
- If load exceeds the limit, which step from this page fixes it, and what does that step cost?
Walk from the edge inward: DNS and CDN, load balancer, app tier, cache, database reads, database writes, storage, then asynchronous work. Name the trigger for each change ("50k reads per second against a 95% cache hit ratio leaves 2,500 database reads, which two replicas handle"), and name what you are not adding yet and why. That last part matters. "Writes are 2,000 per second, so I won't shard yet" shows more judgement than sharding everything.
A second pass looks for the largest single unit of load: the hot key, the celebrity account, the biggest tenant, the on-sale moment. Totals often fit while one unit melts, and the fixes (hot-key replication, a fan-out split, a waiting room) are good deep-dive material.
Deep Dive: Why the database is the hard partShow
The web tier scales almost linearly: if one stateless server handles 1,000 requests per second, ten handle about 10,000, because they share nothing. The database is different because it holds shared, mutable state:
- Reads scale with copies (replicas, caches), at the cost of staleness.
- Writes do not scale with copies, because every copy must apply every write. Write scaling requires splitting the data (sharding), which breaks queries and transactions that span shards.
- Strong consistency costs coordination. Any operation that must see the latest value, or must update several items atomically, needs agreement between machines, which costs round trips and limits throughput.
This is why the scaling stages are mostly about avoiding the database: caches and CDNs serve reads without it, queues smooth writes into it, and replicas spread reads across copies. Sharding is the last resort because it changes the data model itself.
A useful number: a well-tuned single PostgreSQL or MySQL primary on a large machine can often handle tens of thousands of simple transactions per second and several terabytes of data. Many companies run very large products on a handful of such databases, sharded by a single key. Before sharding, check whether query optimisation, connection pooling (such as PgBouncer), partitioned tables and a larger instance would buy another year or two.
Deep Dive: The Universal Scalability Law and why adding machines stops helpingShow
Adding servers does not always add capacity. Neil Gunther's Universal Scalability Law (USL) models throughput with N machines (or threads) as:
C(N) = N / (1 + α(N − 1) + βN(N − 1))
- α (contention) is the fraction of work that must happen one at a time, such as waiting for a lock or a single primary. This is Amdahl's law: if 5% of the work is serial, you can never go faster than 20x, however many machines you add.
- β (coherency) is the cost of keeping machines in agreement: cache invalidation, cross-node coordination, gossip. Because it grows with N², it can make throughput fall after a peak: adding servers makes the system slower.
Practical lessons:
- Stateless tiers have α and β near zero, so they scale almost linearly.
- Shared locks, global counters and a single primary raise α.
- Chatty coordination (every node talking to every other node) raises β. Systems that scale to thousands of nodes avoid all-to-all communication and partition work so most operations involve one or a few nodes.
- Measure throughput at several cluster sizes and fit the curve to predict where adding machines stops paying off.
Deep Dive: A worked capacity example for the photo appShow
Assume 10 million daily active users (DAU). Each user views 30 pages and uploads 0.2 photos per day.
- Reads: 10M × 30 = 300M page views a day. Divided by 86,400 seconds, that is about 3,500 per second on average. With a peak-to-average ratio of 3, peak is about 10,000 page views per second. If each page makes 5 data reads, peak data reads are about 50,000 per second.
- Writes: 10M × 0.2 = 2M uploads a day, about 23 per second on average and about 70 per second at peak. Each upload causes a few rows of metadata writes, plus likes and comments, so the total is perhaps 2,000 writes per second at peak.
- Storage: 2M photos × 2 MB = 4 TB of new photos a day, about 1.5 PB a year (before thumbnails and replication). That is clearly object storage, not the database. Metadata is 2M rows × 1 KB = 2 GB a day, under 1 TB a year, which fits one database for years.
- Bandwidth: 10,000 page views per second × 1 MB of images is 10 GB/s, or 80 Gbit/s. This is CDN territory; the origin should serve only cache misses.
What this tells us, stage by stage:
- Web tier: at about 1,000 requests per second per server, 10 servers would handle the peak. Run 15-20 spread across zones for headroom and failures, and autoscale them.
- Cache: with a 95% hit ratio, 50,000 reads per second become 2,500 database reads. One Redis primary with a replica could serve this, but use a small cluster for headroom and to protect against hot keys.
- Database: 2,500 reads and 2,000 writes per second fit one well-sized primary with two replicas. Sharding is not needed yet. Plan the shard key (
user_id) and watch write growth. - Queue: 70 uploads per second, each needing about 2 seconds of thumbnail work, means 140 jobs are running at any moment. That is about 15 worker processes, plus headroom for spikes.
The numbers justify every component and also show what is not needed yet. That is exactly the reasoning interviewers want to hear. See Back-of-the-Envelope Estimation.
Deep Dive: Moving to a new database without downtimeShow
Several stages on this page involve moving data while the product is live: from a single database to a managed one, from one primary to shards, from a relational store to a specialised one. A large product cannot simply stop for a weekend. The standard approach copies the data in the background, keeps the copy current, checks it, and then switches traffic in small, reversible steps.
The steps, using change data capture (CDC):
- Snapshot. Copy the existing data into the new store, at a throttled rate so production is not hurt. Record the position in the old database's change log (for example, the PostgreSQL WAL position or the MySQL binlog position) at which the snapshot started.
- Catch up. Stream every change from the old database's log, starting at that position, into the new store. A CDC tool such as Debezium reads the log and publishes row changes, often through Kafka. The new store converges on the old one and then follows it with a lag of seconds.
- Verify. Compare row counts and checksums by key range. Run shadow reads: for a sample of live requests, read from both stores and log any differences, while users still see only the old store's answer.
- Switch reads gradually. Send 1%, then 10%, then 50%, then all reads to the new store, watching error rates and latency at each step.
- Switch writes. Briefly pause writes, or use a short write freeze per key range, let the CDC stream drain, then point writes at the new store. Keep a reverse stream from new to old for a while, so you can roll back.
- Retire the old store only after a period with no rollbacks.
An alternative is dual writes, where the application writes to both stores. It looks simpler, but it has a well-known flaw: if one write succeeds and the other fails, the stores diverge silently, and there is no single ordered log to repair them from. CDC avoids this because the old database's log is the one ordered source of truth for what changed. When teams do dual writes, they usually still run a background reconciliation job to find and fix divergence.
The time estimate matters as much as the technique. Copying 20 TB at a throttled 200 MB/s takes about 28 hours, plus catch-up and verification. Plan the migration in days or weeks, not hours. See Multi-Region and Global Data.
Deep Dive: How growing systems fail: capacity cliffs and metastable statesShow
Systems rarely degrade gracefully as load grows. They tend to work fine until they cross a threshold, then fail suddenly. Knowing the common cliffs helps you set triggers before you reach them.
Queueing cliffs. As a tier's utilisation approaches 100%, waiting time grows steeply. In a simple queueing model, the wait is proportional to ρ/(1 − ρ): about 1x the service time at 50% busy, 4x at 80%, 9x at 90%. A tier running at 85% at peak has almost no room for a slightly bigger peak. This is why triggers on this page say 60-70%.
Cold caches. A cache with a 95% hit ratio reduces database load twentyfold. If the cache cluster restarts, the hit ratio drops to zero and the database suddenly receives twenty times its normal read load. It probably cannot take it, so requests time out, the cache cannot fill, and the system stays down even though nothing is broken any more. Defences include warming the cache before sending it traffic, restarting cache nodes one at a time, request coalescing, and admission control that lets only part of the traffic through while the cache fills.
Retry storms. When a dependency slows down, clients time out and retry. Each retry adds load to the struggling dependency, which slows it further. With three retries per call, load can multiply several times at the worst moment. Exponential backoff with jitter, retry budgets (for example, retries may add at most 10% to normal traffic) and circuit breakers break the loop.
Metastable failures. Bronson, Charapko, Aghayev and Zhu described this family of problems in "Metastable Failures in Distributed Systems" (HotOS 2021). A system enters a bad state because of a trigger, such as a load spike, a deploy or a failover. It then stays in the bad state after the trigger is gone, because a feedback loop such as retries, cache misses or queue growth keeps it overloaded. The Slack queue incident above is an example: the database recovered, but the full queue could not drain. The paper's main lesson is that you must find and break the sustaining loop, not just the trigger. Typical fixes are load shedding, bounded queues, retry limits and the ability to drop traffic deliberately to let the system recover.
Hidden limits. Many cliffs are not CPU at all:
- database connection limits;
- file descriptors per process;
- ephemeral ports on a busy proxy;
- a NAT gateway's connection table;
- a cloud account quota;
- a third-party API's rate limit;
- the partition count of a topic.
None of these show up on a CPU graph. A good capacity review lists every limit in the request path and its current headroom.
The common thread: each scaling stage adds capacity, but also new feedback loops and new limits. Watching only averages and CPU misses most of the cliffs. Watch tail latency, queue age, connection counts, hit ratios and error rates, and test failure modes deliberately before real traffic does it for you. See Availability and Reliability.
Key Takeaways#
- Systems grow one bottleneck at a time; start with the simplest design and add each component only when a measured trigger justifies it.
- A typical path is: one server, separate database, vertical scaling, load balancer with stateless servers, shared sessions, replicas, cache, CDN, queues, multiple data centers, and finally sharding.
- Stateless app servers are the foundation of horizontal scaling; keep sessions in a shared store or signed tokens and files in object storage.
- Replicas scale reads and improve availability but introduce replication lag; caches cut database reads by 10-100x at the cost of staleness.
- CDNs and queues take work off the critical path: static bytes near users, slow work done later by workers.
- Sharding scales writes and storage but complicates queries and transactions, so it comes last.
- Logging, metrics, tracing and automation are needed at every stage, and they are how you find the next trigger.
- Get files off servers early: object storage, with pre-signed URLs so clients upload directly.
- Watch the limits that arrive before CPU: database connections, hot keys, queue memory, ports and quotas.
- Keep the backlog somewhere that cannot run out of memory, and let fast in-memory layers hold only the work in flight.
- Separate analytics from serving (OLTP vs OLAP) before reports start hurting production.
- Move data between stores with snapshot plus change data capture, shadow reads and gradual cut-over, never in one big switch.
- Expect cliffs, not slopes: cold caches, retry storms and metastable feedback loops cause sudden failures, so set triggers well below the limits.