Summary#
There are two ways to add capacity:
- Scaling up (vertical scaling): move to a bigger machine with more CPU, RAM and faster disks. It is simple, needs no code changes, and today's largest machines are huge. But it has a ceiling, the price rises steeply near the top, resizing often needs a restart, and one machine is still a single point of failure (SPOF).
- Scaling out (horizontal scaling): add more machines and spread the work across them. It has no fixed ceiling, it tolerates failures, and it can grow and shrink with demand (autoscaling). But it brings distributed-systems complexity.
Scaling out is easy for stateless services, which keep no client-specific data between requests, so any instance can serve any request. So the core design move is to push state out of the app servers:
- sessions go to Redis or a signed token;
- files go to object storage;
- durable data goes to databases;
- shared hot data goes to a cache.
Then the hard part is scaling the stateful tiers. The usual order of tools is:
- cache reads;
- add read replicas;
- move slow work to queues;
- serve static content from a CDN;
- split services by function;
- finally shard data when one primary cannot keep up.
Remove every SPOF with redundancy across failure domains.
Why It Exists#
Every successful system outgrows its first machine. The question is not whether to scale but how, and the choice shapes the architecture for years. Teams often go wrong in one of two ways:
- Too early: they shard a 50 GB database or build twenty microservices for a few thousand users. This adds months of complexity and new failure modes for no benefit.
- Too late: they keep session state in server memory and files on local disk. When traffic arrives, they cannot add a second server without logging everyone out and losing uploads.
Knowing how each approach works, and when it runs out, lets you scale just in time and keep options open. This page builds on Scaling from Zero to Millions.
How It Works#
Performance versus scalability#
These two words are often mixed up, and keeping them apart tells you which tool to reach for.
- A performance problem means the system is slow for a single user, even when it is idle. A request takes 3 seconds because of a missing index, an N+1 query loop or a slow algorithm. More machines will not help; every machine is just as slow.
- A scalability problem means the system is fast for one user but slows down or fails under load. One request takes 50 ms at 100 requests per second, but 2 s at 5,000 per second, because a CPU, a lock, a connection pool or a database is saturated.
A common definition (Werner Vogels, Amazon's CTO, in a 2006 essay on scalability) is that a service is scalable if adding resources increases its capacity in proportion to the resources added. Capacity can mean more requests, more data or larger units of work. Two measures make "in proportion" precise:
- Speedup S(N) is the throughput with N nodes divided by the throughput with one node.
- Efficiency E(N) = S(N) / N. Perfect linear scaling gives E = 1. A system at E = 0.5 pays for twice the hardware it would need if scaling were perfect.
Amdahl's law (Gene Amdahl, 1967) is the simplest model of why speedup falls short. If a fraction s of the work is serial and cannot be spread out, then:
S(N) = 1 / (s + (1 − s) / N)
With s = 5%:
| Nodes N | Speedup | Efficiency |
|---|---|---|
| 2 | 1.9x | 95% |
| 8 | 5.9x | 74% |
| 16 | 9.1x | 57% |
| 64 | 15.4x | 24% |
| Infinite | 20x (the ceiling, 1/s) | 0% |
Even 5% serial work caps the system at 20x, whatever you spend. In a web system, the serial part is anything every request must pass through one at a time: a global lock, a single-row counter, one primary database, a single-threaded queue consumer, or a leader that orders all writes.
Gustafson's law (John Gustafson, 1988) gives the more hopeful view that applies to most online services. Amdahl assumes a fixed amount of work divided across more machines. Gustafson observes that, in practice, when you add machines you also add more work: more users, more independent requests. If the serial fraction stays per request instead of global, the scaled speedup is S(N) = N − s(N − 1), nearly linear: about 15.3x for 16 nodes at s = 5%. This is why a stateless web tier scales almost perfectly. Each request is independent, and the parallel work grows with the user base. The danger is any component shared by all requests, because that turns per-request serial work back into global serial work.
The Universal Scalability Law in the Deep Dive below extends Amdahl's law with a second term for cross-node coordination. With that term set to zero it is exactly Amdahl's law.
Practical rule: first check whether you have a performance problem: profile one request, read the query plans and fix the slow code. Only then treat it as a scalability problem and add capacity. See Latency, Throughput and Performance.
Vertical scaling (scaling up)#
You replace a machine with a larger one, or resize a cloud instance to a bigger type.
Why it is attractive:
- No code or architecture change. The application, the database and its transactions, joins and constraints all work as before.
- No distributed-systems problems. There is no network partition between nodes, no cross-shard query, and no replication lag between partitions.
- Modern machines are enormous. Cloud instances reach 128-192+ vCPUs and 0.5-4 TB of RAM in general and memory-optimised families, and specialised high-memory instances go up to about 24 TB. Local NVMe storage reaches tens of terabytes. One such machine runs workloads that would have needed a cluster a decade ago. See Numbers Every Engineer Should Know.
- Often the best first move for databases. A relational primary is the hardest component to distribute, so giving it a bigger machine buys years of growth cheaply.
Its limits:
- A hard ceiling. Eventually there is no bigger machine. Suppose a workload needs 1 million CPU-seconds per minute, for example 10,000 simultaneous jobs each running 100 tasks of 100 ms of CPU. That is about 1,700 cores busy, far beyond any single server.
- Cost rises faster than capacity near the top. The very largest instance types, high-core-count CPUs and huge-memory machines carry a premium per unit of capacity, while mid-sized commodity machines are cheapest per core.
- Diminishing returns inside one box. More cores help only if the software uses them. Lock contention, a single-threaded component (Redis's command loop, one hot table lock) or memory bandwidth can stop a 192-core machine from going faster than a 32-core one.
- Downtime to resize. Changing an instance type usually means a restart or a failover to a resized replica. It is rarely instant and cannot follow minute-by-minute demand.
- Paying for peak all the time. A machine big enough for the Black Friday or exam-day peak sits mostly idle the rest of the year, and you cannot shrink it easily between peaks.
- Still a single point of failure. One huge machine is one failure domain. Its hardware, kernel, power supply and zone all take the service down together. You still need at least a standby.
Vertical scaling for writes. Before distributing a write-heavy database, check the vertical options. Faster NVMe storage and more RAM for the buffer pool reduce I/O. Tuning settings such as group commit, WAL settings and checkpoint intervals helps too. Picking an engine suited to write-heavy work, such as LSM-tree stores (Cassandra, ScyllaDB, RocksDB-based systems) or time-series databases, can raise sustained writes per node several-fold. See Storage Engines.
Horizontal scaling (scaling out)#
You run many machines and spread the work across them, usually behind a load balancer.
Why it is attractive:
- No fixed ceiling. Need more capacity? Add nodes. Large web services run thousands of instances of a single service.
- Fault tolerance. With N instances, losing one removes 1/N of capacity instead of all of it. Spread them across availability zones and a whole data center can fail.
- Elasticity. Capacity can follow demand: scale out for the evening peak and in overnight. This is autoscaling, and it is the main reason cloud workloads use many smaller instances.
- Commodity hardware. Many mid-sized machines are cheaper per unit of capacity than one giant. Operational skills for them are also widely available.
- Rolling deploys. Updating one instance at a time keeps the service up during releases.
Its costs:
- Statelessness is required for easy scaling, which is the next section.
- Distributed-systems complexity: networks fail and nodes disagree on time and membership. Data spread over nodes needs replication, partitioning and coordination. See Distributed Systems Fundamentals.
- Downstream pressure. Every new app server opens connections to databases and caches. 200 app servers with 50 database connections each is 10,000 connections, more than most relational databases handle well. Use connection poolers (PgBouncer, RDS Proxy) and caches to protect them.
- More moving parts to operate: service discovery, health checks, deploy orchestration, and observability across many instances.
- The work must be divisible. Horizontal scaling helps only if requests or jobs are independent. A single huge transaction or one global lock does not get faster with more machines.
The scale cube: three ways to scale out#
Martin Abbott and Michael Fisher's "The Art of Scalability" (2009) describes the AKF scale cube. It gives three independent axes, each of which can be pushed further:
| Axis | What you split | Example | Main cost |
|---|---|---|---|
| X-axis: clone | Nothing; run N identical copies behind a load balancer | 40 identical web servers | Needs statelessness; does not reduce data size per node |
| Y-axis: functional split | By function or service | Separate search, checkout and user services, each with its own data | Service boundaries, network calls, distributed workflows |
| Z-axis: data partition | By customer, key or region | Users A-M on shard 1, N-Z on shard 2; EU users in the EU | Shard key choice, cross-shard queries, rebalancing |
Most systems scale along the X-axis first because it is cheapest. They add Y-axis splits when teams or workloads need independence, and Z-axis partitioning when data or write volume outgrows one node.
Stateless vs stateful services#
State is any data a server remembers between requests that affects how it answers future requests. Examples:
- a logged-in user's session;
- items in a shopping cart;
- a file uploaded to local disk;
- an open WebSocket connection;
- a partially completed multi-step workflow;
- an in-memory counter.
A stateless service keeps none of this locally. Each request carries, or can fetch, everything needed to answer it, so any instance can serve any request. You can add, remove, restart or replace instances at will. The Twelve-Factor App methodology, published by Heroku co-founder Adam Wiggins around 2011, puts it as "processes are stateless and share-nothing; any data that needs to persist must be stored in a stateful backing service".
A stateful service holds data that matters: databases, caches, message brokers, search indexes, WebSocket gateways, game servers and stream processors with local state. Scaling them out is harder:
- Data must be partitioned (each node holds part of it), replicated (copies for availability and reads) or both.
- A client request must reach the right node: the one holding that user's shard, or that user's open connection.
- Adding or removing nodes means moving data or connections, which takes time and must be done carefully.
- Losing a node loses whatever was only on that node, unless it was replicated.
The standard architecture therefore concentrates state in a few specialised, well-understood systems (databases, caches, object stores, queues). It keeps everything else stateless, so the large, fast-changing application tier scales trivially.
Sticky sessions are a halfway house. The load balancer sends each user to the same server, using a cookie or IP hash, so in-memory sessions keep working. They are fine as a short-term crutch. However:
- load becomes uneven;
- a server failure logs its users out;
- deploys and scale-in drop sessions;
- autoscaling is less effective.
Prefer external state.
Where to keep state#
| State | Where it should live | Why |
|---|---|---|
| Login sessions | Redis or another shared session store; or a signed token (JWT) in a cookie | Any server can validate it; survives server restarts |
| Shopping carts, drafts | Database (durable) with a cache in front, or Redis with persistence | Users expect them to survive; often needed across devices |
| User uploads (images, video, documents) | Object storage (S3, GCS, Azure Blob) plus a CDN | Unlimited, durable, cheap; app servers never store files locally |
| Durable business data (orders, accounts) | Relational or NoSQL database with replication | Correctness, transactions, durability |
| Shared hot data (profiles, product pages) | Distributed cache (Redis/Memcached) | Sub-millisecond reads shared by all servers |
| Small, rarely changing reference data (config, feature flags) | In-process cache with a short TTL, refreshed from a config service | Fastest possible reads; tolerates seconds of staleness |
| Long-running workflow progress | Workflow engine or database table (step, status, references) | Survives restarts; any worker can resume |
| Real-time connections | Connection gateway tier plus a shared registry of user to gateway (Redis) | Connections are inherently stateful; isolate them in one tier |
| Background work | Message queue | Durable hand-off; any worker can process |
| Client UI state, offline data | The client (browser storage, mobile database), synced later | Saves round trips; works offline |
Two refinements:
- Store references, not blobs. A session, queue message or workflow record should contain IDs and small fields, never a 5 MB file or a full API response. This keeps state stores fast and small: put the payload in object storage and pass its key. The same applies to long-running workflows, whose saved state should stay small to keep checkpoints and replays cheap.
- Tokens vs server-side sessions. A signed token (for example a JWT) lets any server validate the user without a lookup, which is fully stateless. But revoking it before expiry needs a deny-list or short lifetimes plus refresh tokens. A server-side session in Redis is easy to revoke but adds a lookup of about 1 ms per request. See Authentication and Authorization.
Single point of failure (SPOF)#
A single point of failure is any component whose failure alone takes down the whole system. Obvious ones are:
- a single app server;
- a database with no replica;
- one load balancer.
Less obvious ones cause many real outages:
- DNS with one provider or a misconfigured record.
- A shared configuration or feature-flag service that every request depends on synchronously.
- A directory or lookup service, for example the table that maps users to shards. If every request must ask it, it is a SPOF even when all the data shards are healthy.
- A single availability zone holding everything.
- TLS certificates that expire, or credentials and secrets in one store.
- The deploy pipeline: one bad config pushed everywhere at once.
- A single human who knows how something works.
How to remove SPOFs:
- Redundancy: run at least two of everything critical (N+1), across failure domains such as zones, racks and power. For stateful components, replicate with automatic failover: primary plus standby for databases, replicas for caches, a replication factor of 3 for brokers.
- Active-active vs active-passive: active-active spreads load over all copies and fails over instantly. Active-passive is simpler but wastes the standby and fails over in seconds to minutes.
- Health checks and automatic failover: load balancers remove dead instances, and orchestrators replace them.
- Cache or degrade around dependencies: if the config service is down, serve the last known config from local memory.
- Limit blast radius: deploy gradually (canaries) and isolate customers into cells (independent copies of the stack), so one failure affects a fraction of users. AWS describes this approach in its guidance on cell-based architecture.
See Availability and Reliability.
Overview of scalability strategies#
Once the app tier is stateless, the remaining bottlenecks are almost always in the data and in slow work. Here is the toolkit, roughly in the order teams reach for it:
| Strategy | What it fixes | How it works | Main cost | Deep page |
|---|---|---|---|---|
| Load balancer + horizontal app tier | App CPU and memory limits, availability | Clone stateless servers | Needs external state | Load Balancing |
| Caching | Read load and latency | Keep hot data in memory: in-process, Redis, CDN, client | Staleness, invalidation | Caching Fundamentals |
| CDN | Static and media delivery, global latency | Edge servers near users cache content | Invalidation, cost per GB | CDN |
| Read replicas | Read load on the database | Copies of the primary serve reads | Replication lag | Replication |
| Async processing via queues | Slow work in requests, write bursts | Hand work to workers; buffer spikes | Eventual results | Message Queues |
| Autoscaling | Variable demand, cost | Add or remove instances by metric | Lag, cold starts, over-provisioning | This page |
| Functional split (services) | Team and workload coupling | Separate services and databases per domain | Network calls, distributed workflows | Monolith vs Microservices |
| Sharding / partitioning | Write throughput and data size beyond one node | Split data by key across nodes | Cross-shard queries, rebalancing | Partitioning and Sharding |
| Write techniques: batching, aggregation, load shedding | Very high write rates | Batch writes, pre-aggregate, drop low-value work under overload | Latency per item, approximate results | Partitioning and Sharding |
| Multi-region | Global latency, regional disasters | Deploy and replicate across regions | Consistency, cost, complexity | Multi-Region Data |
Caching happens in several layers, each with a different reach:
- Client-side: the browser's HTTP cache, a mobile app's local store, or client libraries that cache cluster metadata such as Redis Cluster slot maps. There are no network calls at all, but the server has little control over staleness.
- CDN: edge servers near users. An image served from a far-away origin can cost 200-300 ms per request for an intercontinental user; from a nearby edge it is a few tens of milliseconds.
- External cache (Redis, Memcached): shared by all app servers, with eviction (LRU) and TTLs. This is the default cache in most designs.
- In-process cache: memory inside each app server, fastest of all, for small, hot, rarely changing values such as config, feature flags, reference data and hot keys. Each instance has its own copy, so invalidation is per instance; use short TTLs.
- Database caches: buffer pools and page caches inside the database itself.
Sharding is the last resort for the data tier, not the first. Bring it up only when the numbers prove one primary cannot cope:
- storage beyond a few terabytes, or growing towards it fast;
- sustained writes beyond what one primary handles (tens of thousands per second);
- reads that replicas and caches cannot absorb.
When you do shard:
- Pick the shard key from the main access pattern. In a social app most queries are about one user, so
user_idkeeps a user's data together. - Prefer hash-based distribution for even load (with consistent hashing or many virtual slots so you can add shards later).
- Use range-based sharding when range scans matter and load is naturally spread, such as tenants in a SaaS product.
- Use directory-based sharding (a lookup table) only when you need per-key placement, because it adds a lookup and a critical dependency.
- Avoid time-based shards for write-heavy data: all current writes land on the newest shard.
- Expect cross-shard queries (global trending, search) to need precomputation, caching or a separate index.
See Partitioning and Sharding and Consistent Hashing.
Autoscaling#
Autoscaling adjusts the number of instances to demand.
- Reactive (target tracking): keep a metric near a target, such as average CPU at 60%, requests per instance at 500, or queue depth per worker at 100. Kubernetes' Horizontal Pod Autoscaler, AWS Auto Scaling groups and ECS Service Auto Scaling all work this way.
- Scheduled: scale out before known peaks, such as 9 a.m. on weekdays, a product launch or a registered competition start time.
- Predictive: forecast from history and scale ahead of the curve. AWS offers predictive scaling for EC2 Auto Scaling.
- Queue-driven workers: scale on backlog. Little's law gives the target: workers needed ≈ arrival rate × processing time ÷ concurrency per worker. KEDA brings this to Kubernetes.
Practical concerns:
- Lag: a new VM can take minutes to boot and warm up; a container can take seconds to tens of seconds. Keep headroom (target 50-70%) and consider warm pools or pre-pulled images.
- Scale-in safely: drain connections and in-flight work before terminating, and use cooldowns to avoid flapping.
- Protect downstream: a fleet that doubles in a minute can double database connections and cold-cache misses. Cap maximum size and pool connections.
- Over-provisioning risk: aggressive scale-out wastes money. Set maximums and alert on cost.
- Buffer with a queue when work can be asynchronous. Bursty compute jobs (code execution, video transcoding, report generation) are pushed to a queue, and autoscaled workers pull from it. The API returns a job ID immediately, and the client polls a status endpoint or receives a push notification. Polling every second or two is often simpler than holding WebSockets open for short jobs. See Pattern: Long-Running Tasks.
Load balancing the scaled-out tier#
Scaling out needs something that spreads requests across instances. That is the job of a load balancer, and how it is set up affects both capacity and availability.
Layer 4 versus layer 7.
- A layer 4 (transport) load balancer looks only at IP addresses and ports. It forwards TCP or UDP connections without reading the content. It is very fast and cheap per connection, which suits raw TCP services, WebSocket gateways at huge connection counts, and databases. Examples are AWS Network Load Balancer and Linux IPVS.
- A layer 7 (application) load balancer terminates the connection and reads the HTTP request: path, headers, cookies. It can route
/video/*to video servers and/billing/*to hardened billing servers. It can also retry, rewrite and authenticate, and it can balance per request, not just per connection, which matters for HTTP/2 and gRPC where one connection carries many requests. Examples are AWS Application Load Balancer, Envoy, NGINX and HAProxy in HTTP mode. It costs more CPU per request, but on modern hardware the difference rarely matters.
Algorithms. Choosing well matters more as instances become uneven:
| Algorithm | How it picks | Good for | Weakness |
|---|---|---|---|
| Round robin | Next server in turn | Identical servers, uniform requests | Ignores current load |
| Weighted round robin | In turn, in proportion to weights | Mixed instance sizes, canaries at 5% | Static weights |
| Least connections or least outstanding requests | Server with the fewest active requests | Requests of very different cost | Needs accurate counts; herding after a restart |
| Power of two choices | Pick 2 servers at random, send to the less loaded | Large fleets, many load balancers | Slightly more work per request |
| Consistent hash on a key | Same key to the same server | Cache locality, sticky routing | Uneven when keys are hot |
The power of two choices result (analysed by Michael Mitzenmacher around 2001) is striking. Sending each request to the less loaded of two random servers, instead of one random server, cuts the worst server's excess load dramatically: from roughly log n / log log n to log log n for n servers. It is used in Envoy and Finagle, and it works well when many independent load balancers each have only a partial view of load.
The load balancer must not become the new SPOF or bottleneck.
- Managed cloud load balancers run across several zones and scale themselves. They scale over minutes, though, so for a known sudden event most providers let you request pre-provisioned capacity in advance.
- Self-run load balancers (HAProxy, NGINX, Envoy) run as at least a pair. They are active-passive with a floating virtual IP moved by VRRP (for example keepalived), or active-active behind DNS or anycast, with several IPs announced from many locations.
- Health checks must test what matters. A check that returns 200 while the database connection is broken keeps sending traffic to a broken server. A check that fails whenever a downstream dependency is slow can mark every server unhealthy at once. A shallow liveness check plus a separate readiness check is the common compromise.
- Connection draining. When an instance is removed for a deploy or scale-in, stop new requests, let in-flight requests finish (typically within 30-300 s), then terminate it.
Sizing a scaled-out fleet: headroom and zone loss#
"Add more servers" needs a number. The calculation has three parts: per-instance capacity, a utilisation target, and spare capacity to survive losing a failure domain.
Step 1: measure one instance. Load test a single instance with a realistic request mix and find the throughput where latency stays within the SLO. Suppose one instance serves 1,000 requests per second before p99 latency rises above the target.
Step 2: choose a utilisation target. Do not plan to run at 100%. Queueing delay rises sharply near saturation, and autoscaling needs time to react. A target of 60-70% is common. At 70%, each instance is planned for 700 requests per second.
Step 3: add spare capacity for losing a zone. If you spread the fleet across Z zones and must survive one zone failing, the remaining Z − 1 zones must carry the whole peak. The fleet therefore needs a factor of Z / (Z − 1) more capacity.
Worked example at a peak of 30,000 requests per second:
| Setup | Instances for the peak at 70% | Zone-loss factor | Total instances |
|---|---|---|---|
| 1 zone (no zone tolerance) | 30,000 ÷ 700 ≈ 43 | 1 | 43 |
| 2 zones | 43 | 2 / 1 = 2 | 86 (43 per zone) |
| 3 zones | 43 | 3 / 2 = 1.5 | 65 (about 22 per zone) |
| 4 zones | 43 | 4 / 3 ≈ 1.33 | 58 (about 15 per zone) |
Two lessons:
- Three zones are cheaper than two for the same resilience, because each survivor only absorbs half of the lost zone's load, not all of it. This is one reason three-zone deployments are standard.
- Small fleets carry a high percentage of spare capacity. With 2 instances, losing one removes 50% of capacity, so each must be able to run at double load. With 50 instances, losing one removes only 2%.
Autoscaling can lower the steady-state cost, since the extra zone capacity can be added after a failure. That only works if new instances start faster than users give up, and if the cloud still has capacity during a zone-wide event, when every customer is trying to scale at the same time. For critical services, keeping static spare capacity, sometimes called being statically stable, is safer. See Availability and Reliability.
Scaling the database tier step by step#
The application tier is the easy part. The database is usually the real limit, and there is a well-worn ladder of steps. Climb it only as far as the numbers require.
Step 0: query fixes. A missing index can make a query 1,000 times slower than it should be. A loop issuing one query per item (the N+1 pattern) multiplies load by the page size. These are performance problems, and fixing them is free capacity.
Step 1: scale up. Most relational databases are fastest when the working set fits in memory. Moving from 64 GB to 512 GB of RAM can turn disk reads into memory reads for most queries. NVMe storage sustains hundreds of thousands of IOPS. A well-tuned single primary on modern hardware commonly handles tens of thousands of simple writes per second and far more reads. See Numbers Every Engineer Should Know.
Step 2: connection pooling. Scaling the app tier out multiplies connections, and each PostgreSQL connection is a separate process using several megabytes of memory. A pooler multiplexes thousands of client connections onto a few hundred database connections.
Step 3: caching. With a 90% cache hit rate, the database sees one tenth of the read traffic.
Step 4: read replicas. Replicas scale reads roughly linearly, but not writes, since every replica must apply every write. Reads that must see the latest write, such as "show me the order I just placed", go to the primary or use read-your-writes routing.
Step 5: asynchronous and batched writes. If writes are bursty or need not be immediate, put them on a queue and have workers write in batches. A batch of 100 rows in one transaction costs far less than 100 separate transactions. Pre-aggregating, such as counting likes in memory and writing a total every second, can cut writes by orders of magnitude.
Step 6: vertical partitioning. Move whole tables or domains into separate databases: users in one, messages in another, analytics in a third. Each gets its own primary, and nothing in the code needs sharding logic, but joins across those domains now happen in the application. Figma has written publicly about splitting its PostgreSQL database by groups of tables first, before later moving to horizontal sharding.
Step 7: horizontal sharding. Split the rows of a table across many databases by a shard key. This is the most powerful step and the most expensive one to build and run.
Step 8: specialised stores. Some workloads should never have been in the main database: full-text search, high-volume time series, large blobs. Moving them out is often cheaper than sharding.
When is sharding actually justified? Make the case with numbers, in three steps: identify the bottleneck, show why one database cannot handle it, then propose sharding.
- Storage: 500 million users with 5 KB each is 2.5 TB. One PostgreSQL instance handles that, so there is no need to shard for storage. If growth will reach 25 TB in two years, plan for it.
- Write throughput: 50,000 writes per second sustained at peak is beyond a comfortable single primary, even after batching, so this is a reason to shard.
- Read throughput: if replicas and caches still cannot absorb the reads, for example because the data is too large to cache and each replica is saturated, that is a reason too.
The most common mistake is sharding first and justifying it later.
What to say when you do shard:
- Choose the shard key from the access pattern. For a social app, most queries are about one user (their posts, followers, likes), so shard by
user_id. - Choose the distribution. Hash-based placement with consistent hashing, or a fixed number of logical shards, spreads users evenly.
- Call out what gets harder. Global queries such as "trending across all users" must query every shard. Precompute them with a background job and cache the result.
- Plan for growth. Start with many logical shards (for example 64 or more) mapped onto fewer physical machines, so adding capacity means moving whole logical shards rather than rehashing every row.
See Partitioning and Sharding for shard-key choice, hot keys and resharding in depth.
Worked example: a code-execution service for a 100,000-user contest#
An online coding-practice platform, similar to LeetCode, runs user-submitted code against test cases inside isolated containers. Most of the time load is modest. During a contest, up to 100,000 users may submit within minutes. The API servers are stateless and scale out easily; the question is the CPU-heavy execution tier.
Do the maths first. Assume a peak of 10,000 submissions in flight at once, about 100 test cases each, and a conservative 100 ms of CPU per test case (most finish in 10-50 ms):
- 10,000 × 100 = 1,000,000 test-case runs.
- 1,000,000 × 0.1 s = 100,000 CPU-seconds, about 28 hours on a single core.
- To finish within one minute, you need 100,000 ÷ 60 ≈ 1,667 cores busy at once.
Option 1: scale up (a poor fit). Run the containers on the largest machine available. Even the biggest cloud instances top out at a few hundred vCPUs, so one machine cannot reach 1,667 cores. And even if it could, it would sit mostly idle between contests while being paid for at full price. It is also a single point of failure during the event that matters most.
Option 2: dynamic horizontal scaling (good). Run a pool of execution containers per language and let an autoscaler change the count with demand, based on CPU utilisation or the number of submissions waiting. On AWS this could be ECS services with Service Auto Scaling, or a Kubernetes deployment with an autoscaler. The main risk is over-provisioning cost, which is controlled with maximum limits and quick scale-in after the contest.
Option 3: horizontal scaling with a queue (also good, and often preferred). Put a queue such as SQS between the API and the execution workers:
- The API enqueues each submission and returns a submission ID at once.
- Workers pull submissions when they have capacity, so a spike becomes a backlog instead of overloaded containers.
- If a worker crashes mid-run, the message becomes visible again and another worker retries it, so no submission is lost.
- The autoscaler scales workers on queue depth, using the Little's-law relation on this page: workers ≈ arrival rate × time per job ÷ jobs per worker.
The queue makes the flow asynchronous. The client polls a status endpoint such as GET /check/:id about once a second until the result is ready. LeetCode itself works this way: open the browser's network tab while submitting and you will see the polling. A WebSocket could push the result instead, but for jobs that finish in a few seconds, one poll per second is simpler and cheap.
Is the queue over-engineering? At this volume, possibly. Contests are scheduled and users register in advance, so the platform could simply pre-scale the execution pool before the start time (scheduled scaling). The strongest arguments for the queue are retries after container failures and a buffer against an unexpected spike, not raw volume. In an interview, showing this weighing of options matters more than the final choice.
Worked example: event pages during a ticket on-sale#
When tickets for a popular concert go on sale, millions of people open and refresh the same event page at the same moment. The non-functional requirement is clear: viewing and searching must stay available under tens of millions of requests. The design combines three tools: a stateless, horizontally scaled service, load balancing and aggressive caching.
Horizontal scaling. The event service holds no user state, so it runs as many identical instances behind a load balancer. Round robin or least connections spreads traffic; least outstanding requests is better when some requests, such as seat maps, are much heavier than others.
Caching by how often data changes.
- Rarely changes: event name, date, venue location and capacity, performer bios. Cache these heavily with long TTLs, under keys like
event:EVENT_IDholding the full event object, in Redis or Memcached. - Changes constantly: seat availability. Give it a very short TTL, or serve it from a separate, purpose-built path.
- Read-through caching: on a miss, the cache layer loads from the database and stores the result, so the application code stays simple.
Keeping the cache correct. When an event's date or line-up changes, the cached copy must be invalidated. Database triggers, or better, change data capture (CDC) from the database log, publish change events, and a small consumer deletes the matching cache keys. TTLs remain as a safety net in case an invalidation message is lost.
Search results. Repeated searches can be cached too. The key must include every parameter that changes the result, for example search:keyword=taylor swift&start=2025-01-01&end=2025-12-31, normalised so equivalent queries share an entry. Invalidating search results is hard, because a new event may belong in many cached queries. Use TTLs plus cache tags (for example, all entries mentioning a given artist) so related entries can be dropped together. Search engines also cache internally: Elasticsearch has a shard-level query cache for filters and a shard request cache for whole responses, especially aggregations. If results are not personalised, a CDN can cache them near users as well.
Challenges to call out. Cache and database can disagree for a short time after updates, which is acceptable for event descriptions but not for seat availability. Running many instances also means deploys and rollbacks must be automated and gradual.
The booking path is the opposite case. It needs strong consistency to prevent double booking, and protects itself from the crowd with a virtual waiting room, not with more caching.
Scaling stateful real-time tiers: connection gateways#
Chat, live comments, multiplayer games and collaborative editors keep a long-lived connection to every active user. Connections are state that cannot be moved to Redis: the socket exists on one particular machine. The standard design isolates them in a dedicated tier:
- Gateway servers hold the WebSocket or long-poll connections and do little else. Tuned servers hold very many idle connections; WhatsApp reported more than 2 million TCP connections on a single server in 2012. More typical services plan for tens to hundreds of thousands per gateway, depending on message rate and memory per connection.
- A connection registry (often Redis) maps user to gateway. Any backend service that needs to reach a user looks up the gateway, or publishes to a channel the gateway subscribes to.
- Business logic stays in stateless services behind the gateways, so it scales independently of the connection count.
- Layer 4 load balancing often fronts the gateways, because connections last for hours and the load balancer only needs to place each connection once.
Scaling in and deploying are harder than for stateless tiers. Removing a gateway disconnects its users. They must reconnect elsewhere, and if 200,000 clients reconnect at the same instant, they can overload the remaining gateways and the authentication service. Clients therefore reconnect with randomised backoff (jitter). Servers drain gradually by closing connections in small batches. Autoscaling uses connection count and memory, not CPU alone. See Polling, Long Polling, SSE, WebSockets and Webhooks.
Serverless and managed services as scale-out#
Serverless functions (AWS Lambda, Google Cloud Run, Azure Functions) and managed databases with automatic scaling (DynamoDB on-demand, Aurora Serverless) take scale-out a step further: the provider adds and removes capacity for you, often per request.
| Benefit | Cost |
|---|---|
| No servers to size; scales from zero to thousands of concurrent executions | Cold starts: a new execution environment can add tens of milliseconds to several seconds, depending on runtime and package size |
| Pay per use; cheap for spiky or low traffic | Expensive per unit at high, steady load compared with long-running instances |
| Built-in redundancy across zones | Concurrency limits per account and region; bursts can be throttled |
| Little operational work | Fan-out can overwhelm a database that does not scale the same way; use pooling proxies |
Serverless does not remove the need to think about state. Functions must be stateless, and the database behind them becomes the bottleneck even faster, because a burst of 1,000 concurrent functions can open 1,000 database connections. Use serverless for spiky, event-driven or low-volume workloads. Use long-running instances or containers for high, steady throughput and for latency-critical paths that cannot accept cold starts.
When to Use It#
- Scale up first when:
- load grows gradually;
- the component is hard to distribute (a relational primary, a single-threaded engine);
- you need the simplest change with no code impact;
- a larger instance is still well within catalogue limits.
- Scale out when:
- you need availability beyond one machine (almost always for production);
- demand varies and elasticity saves money;
- load exceeds the biggest reasonable machine;
- the work is naturally divisible (independent requests, jobs, or keys).
- Make services stateless from the first day; it is cheap early and expensive later.
- Shard only when measured or estimated numbers exceed one primary with headroom.
When NOT to Use It#
- Do not scale out a component that is slow because of an inefficient query or algorithm; fix the performance problem first.
- Do not shard or split into microservices for a dataset and team that one database and one deployable can serve.
- Do not rely on vertical scaling alone for production availability; one machine is one failure domain.
- Do not autoscale stateful databases by adding and removing nodes frequently; rebalancing is slow and risky. Scale them deliberately.
How to Implement It#
- Externalise state in the app tier: sessions to Redis or tokens, uploads to object storage, background work to queues, and no local files that matter.
- Put a load balancer in front with health checks; run at least two instances across two zones.
- Add caching: Redis for shared hot data, a CDN for static assets and media, and in-process caching for small hot config.
- Scale the database vertically and add read replicas; route read-only queries to them, accepting lag where safe.
- Move slow or bursty work to queues with autoscaled workers.
- Set autoscaling on a metric that tracks load, with headroom, minimums across zones, maximums and safe scale-in.
- Hunt SPOFs: draw the request path and ask, for each box, "what happens if this dies?". Add redundancy and failover, and test them.
- Shard when numbers demand it, choosing a key from the main access pattern and planning resharding.
# Kubernetes: stateless deployment with autoscaling (illustrative)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: api }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: api }
minReplicas: 4 # at least 2 per zone across 2 zones
maxReplicas: 60 # cap protects the database and the budget
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 60 }
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # avoid flapping| Technology | Fits when |
|---|---|
| Kubernetes HPA, KEDA | Autoscaling containers on CPU, custom metrics or queue depth |
| AWS Auto Scaling groups, ECS Service Auto Scaling, GCP Managed Instance Groups | Autoscaling VMs and containers on the major clouds |
| Redis / Valkey, DynamoDB | Shared session and ephemeral state stores |
| Amazon S3, Google Cloud Storage, Azure Blob | Files and uploads instead of local disk |
| PgBouncer, RDS Proxy | Protecting databases from connection explosions as app tiers scale |
| Vitess, Citus, managed sharded stores | Scaling a relational tier out when one primary is not enough |
Trade-offs#
| Scale up (vertical) | Scale out (horizontal) | |
|---|---|---|
| Simplicity | High; no code changes | Lower; needs stateless design, LB, coordination |
| Ceiling | Largest available machine | Practically none |
| Cost curve | Rises steeply at the top; pays for peak all the time | Roughly linear; can follow demand |
| Availability | One failure domain unless paired with standby | Survives node and zone loss |
| Elasticity | Poor; resizing needs restarts | Good; autoscaling |
| Data consistency | Easy; one node | Harder; replication and partitioning |
| Best for | Databases, single-threaded or hard-to-split components, early stages | Stateless app tiers, workers, caches, large-scale stateful systems built for it |
| State placement | Gain | Cost |
|---|---|---|
| In-process memory | Fastest | Lost on restart, not shared, blocks scaling |
| Sticky sessions | Quick fix for legacy apps | Uneven load, lost sessions on failure |
| Shared store (Redis) | Any server serves any user | Extra ~1 ms hop, another component to run |
| Signed tokens | No lookup, fully stateless | Hard to revoke early; size limits |
| Scaling choice | Gain | Cost | Pick when |
|---|---|---|---|
| Layer 4 load balancer | Very cheap per connection, protocol-agnostic | No per-request routing or retries | Long-lived connections, raw TCP, huge connection counts |
| Layer 7 load balancer | Path routing, retries, per-request balancing for HTTP/2 and gRPC | More CPU per request | Most HTTP APIs |
| Three zones instead of two | 1.5x spare capacity factor instead of 2x | More cross-zone traffic and cost | Production services that must survive a zone loss |
| Static spare capacity | Survives a zone loss without waiting for autoscaling | Paying for idle instances | Critical paths |
| Synchronous execution scaled out | Simple request-response API | Spikes hit workers directly | Short, predictable jobs |
| Queue in front of workers | Absorbs spikes, retries failed jobs | Asynchronous API, polling or push | Bursty or CPU-heavy jobs |
| Vertical partitioning of the database | No sharding logic; each domain gets its own primary | Cross-domain joins move to the application | Several large, loosely related domains |
| Horizontal sharding | Scales writes and storage almost without limit | Shard key, cross-shard queries, resharding | Numbers prove one primary cannot cope |
| Many logical shards on fewer servers | Resharding by moving shards, not rehashing rows | Per-shard overhead | Any sharded system expected to grow |
| Serverless functions | No capacity planning, pay per use | Cold starts, concurrency limits, cost at steady load | Spiky, event-driven, low-volume workloads |
Common Pitfalls#
- Storing sessions or uploads on local disk or memory, then discovering that a second server breaks logins and loses files.
- Sharding before proving one database cannot cope, or picking a shard key that does not match the main queries.
- Scaling the app tier out while the database stays the hidden bottleneck, and adding connections that overload it.
- Forgetting hidden SPOFs: one load balancer, one zone, a mandatory directory or config service, expiring certificates.
- Autoscaling without headroom, caps or connection pooling; scaling in without draining connections.
- Treating vertical scaling as "bad": it is often the cheapest, safest first step, especially for databases.
- Putting large payloads in session or workflow state instead of storing references.
- Treating a performance problem (a slow query, an N+1 loop) as a scalability problem and adding servers that are all equally slow.
- Ignoring the serial fraction: one global lock, counter or single-threaded consumer caps the whole system, as Amdahl's law shows.
- Planning capacity without zone-loss headroom, so losing one of two zones overloads the survivor.
- Load balancer health checks that are too shallow (pass while the app is broken) or too deep (fail everywhere when one dependency is slow).
- Using
hash mod Nplacement, so adding one shard moves most of the data. - Letting thousands of clients reconnect at the same instant after a gateway restart, without jittered backoff.
- Moving to serverless without pooling database connections, so a burst of functions exhausts the database.
Real-World Examples#
Stack Overflow's engineers have described serving one of the most visited sites on the web from a small number of large SQL Server machines and a modest web tier for many years. It is a well-known case of deliberately scaling up and caching instead of distributing early.
The Twelve-Factor App guidelines (published by Heroku co-founder Adam Wiggins around 2011) made "stateless, share-nothing processes plus backing services" the default for cloud applications, which is what makes horizontal scaling and autoscaling straightforward.
AWS publishes guidance on cell-based architecture: splitting a service into many independent cells, each a full copy of the stack serving a subset of customers, to limit the blast radius of failures and scale by adding cells.
Martin Abbott and Michael Fisher's "The Art of Scalability" (2009) introduced the AKF scale cube (clone, functional split, data partition) that many teams use to plan growth.
Instagram's 2012 engineering post on sharding and IDs described mapping thousands of logical shards, implemented as PostgreSQL schemas, onto a much smaller number of physical servers. Each generated ID embeds a timestamp and the logical shard ID, so any object can be routed without a lookup.
Notion's 2021 write-up on sharding its PostgreSQL database described 480 logical shards over 32 physical databases, partitioned by workspace ID, and an online migration that used double writes, a backfill and verification before switching reads.
Figma has described scaling its PostgreSQL setup first by vertical partitioning, moving groups of related tables to their own databases, and only later by horizontal sharding. This follows the ladder on this page.
WhatsApp's engineering blog reported in 2012 that a single tuned server, running Erlang on FreeBSD, held more than 2 million concurrent TCP connections. It shows how far one well-tuned machine can go for a connection-holding tier.
In the Interview#
Answering "how does this scale?" in an interview#
When the interviewer asks how the design handles 10 or 100 times more load, walk the request path from the outside in and give each tier a mechanism and a number:
- Edge: "Static assets and media come from the CDN, so the origin sees maybe 10% of the bytes."
- Stateless tiers: "API servers hold no state, so they scale horizontally behind the load balancer. At about 700 requests per second per instance, the 30,000 peak needs about 43 instances, or 65 across three zones so we survive losing one."
- Caches: "Hot reads such as event pages come from Redis; with a 95% hit rate the database sees one twentieth of those reads."
- Database: "Writes are about 3,000 per second, which one primary handles, plus two replicas for reads. If writes grow tenfold, we'd shard by user ID across 64 logical shards."
- Asynchronous work: "Image processing and notifications go through a queue with autoscaled workers, so spikes become backlog rather than errors."
- Single points of failure: "Every tier runs in at least two zones, and the database has a synchronous standby with automatic failover."
This structure shows that you know scaling is not "add servers" but a different answer for each tier, sized with numbers.
Deep Dive: The economics of up versus outShow
Why mid-sized machines are cheapest per unit. On public clouds, instance prices within a family scale roughly linearly with size across the mid-range: twice the vCPUs costs about twice as much. The premium appears at the extremes: the largest memory-optimised machines, bare-metal hosts and special high-core-count parts. On-premises, the curve is steeper still, because high-end CPUs, large DIMMs and multi-socket boards cost disproportionately more. So the classic argument "scale out because commodity hardware is cheaper" is strongest at the top end, and weaker across the middle of a cloud catalogue.
Utilisation decides the real cost. A fixed large machine sized for peak runs at perhaps 20-30% average utilisation if traffic has a 3-4x daily swing. An autoscaled fleet of small instances can track the curve and run at 50-60% average. For the same peak, it may cost about half as much. The trade-off is engineering effort and the risk of scaling lag.
Coordination is the hidden tax. Splitting work across N machines adds network hops, serialisation and coordination. Gunther's Universal Scalability Law models throughput as C(N) = N / (1 + α(N − 1) + βN(N − 1)), where α is contention (serialised work) and β is coherency (cross-node agreement). With α = 0.05 and β = 0, sixteen nodes give only about 9x. With β = 0.001, throughput peaks around 31 nodes and then falls. So a scale-out design must keep shared state and cross-node chatter tiny. That is exactly why stateless tiers scale so well (α and β near zero) and why stateful systems are partitioned so that each request touches one node.
Engineer time is part of the cost. Sharding a relational database can occupy a team for months and adds permanent operational load: resharding, cross-shard queries, backups per shard. If one larger instance, priced in thousands of dollars per month, defers that work by two years, it is usually the right call. At very large scale the balance flips: a 10% efficiency gain across thousands of machines pays for a dedicated team.
A useful rule: scale stateless tiers out from day one, which is cheap because they are stateless, and scale stateful tiers up until the numbers force you out.
Deep Dive: Scaling stateful services outShow
When state cannot be pushed elsewhere, as in databases, caches, WebSocket gateways, game servers and stream processors, scaling out needs three mechanisms.
1. Routing: send each request to the node holding its state.
- Hash-based: node = f(hash(key)), using consistent hashing or a fixed set of virtual slots (Redis Cluster's 16,384 hash slots). Clients or proxies compute it with no lookup.
- Range-based: a sorted map of key ranges to nodes. This is good for scans and needs a metadata service; Bigtable, HBase and CockroachDB work this way.
- Directory: an explicit lookup table, which allows any placement (move a big tenant to a dedicated shard). The directory is a dependency on every request, so it must be replicated and cached aggressively.
- Connection registries: for WebSockets, a shared map of user to gateway node lets any service push a message to the node holding the user's socket.
2. Rebalancing: move state when nodes are added or removed.
- Move small units (slots, ranges or virtual nodes), not whole datasets, so the work spreads across many nodes and each move is short.
- Copy, then catch up from the log, then switch ownership atomically, then delete the old copy. Writes during the move are double-written or redirected (Redis Cluster's
ASKandMOVEDredirects). - Throttle rebalancing so it does not starve foreground traffic.
- For connection-holding tiers, drain instead of moving: stop sending new connections to a node, ask clients to reconnect elsewhere with jittered backoff, then terminate it.
3. Replication and failover: survive node loss.
- Keep replicas in different zones. Synchronous replication gives no data loss at higher write latency; asynchronous gives low latency at the risk of losing the last moments of writes on failover.
- Use leader election (Raft or a coordination service) to promote a replica, with fencing so the old leader cannot keep writing after it is replaced.
Hot keys break even partitioning. One celebrity account or flash-sale item can overload the node that owns it, whatever the total cluster size. Fixes:
- replicate hot read keys, including caching them in-process;
- split hot write keys into N sub-keys (counter#0..counter#N-1) and aggregate on read;
- detect hot keys dynamically and split only those.
Workflow and session state should stay small. Long-running workflows and sessions that accumulate large payloads make every checkpoint, replay and migration slower. Keep IDs and status in the state and store payloads in object storage.
See Partitioning and Sharding, Replication and Consistent Hashing.
Deep Dive: What stops a bigger machine from going fasterShow
Scaling up assumes that a machine with 4 times the cores and memory does 4 times the work. Several effects inside one box break that assumption long before you reach the largest instance type.
NUMA (non-uniform memory access). Large servers have two or more CPU sockets, each with its own memory. A core reading memory attached to the other socket pays roughly 1.5-2 times the latency of local memory, and uses the limited link between sockets. Software unaware of this, such as a database whose buffer pool is spread across sockets with threads scheduled anywhere, can lose a large share of the expected gain. Databases and JVMs offer NUMA-aware settings, and some teams run one process per socket instead of one huge process.
Memory bandwidth. Adding cores does not add memory bandwidth in proportion. Scan-heavy work, such as analytics or large sorts, often hits the memory-bandwidth ceiling while cores sit idle waiting for data.
Locks and shared structures. Any lock taken by every request, such as a global mutex, a hot row, a single-writer log or a shared counter, is serial work in the Amdahl sense. On 8 cores a lock held 2% of the time is invisible. On 128 cores, threads queue for it constantly and adding cores makes throughput worse, because cores waste time handing the lock's cache line back and forth.
Single-threaded engines. Some popular components execute commands on one thread by design. Redis runs commands on a single main thread (newer versions use extra threads for network I/O); the Node.js event loop runs JavaScript on one thread. A bigger machine does not make them faster per instance. You scale them out instead: more Redis shards, more Node.js processes.
Kernel and network limits. A single NIC has a fixed bandwidth, commonly 25-100 Gbps on cloud instances. Interrupt handling can pin a few cores. Default kernel settings cap open file descriptors and the ephemeral port range; Linux's default range of 32768-60999 gives about 28,000 outgoing ports per destination address and port. These are fixable, but only if someone knows to fix them.
Garbage collection with huge heaps. A JVM or Go process with a 500 GB heap may suffer long collection pauses or high collection CPU, unless it uses a low-pause collector such as ZGC or Shenandoah and is tuned carefully. Several medium processes are often more predictable than one giant one.
Restart and recovery time. A database with a 1 TB buffer pool takes a long time to warm up after a restart. Until the cache is warm, it serves from disk at a fraction of normal speed. Restoring or rebuilding a replica of a 20 TB node takes hours. Bigger nodes mean longer recovery, which lowers availability through MTTR even if they fail no more often.
The practical result: scale up while the measured speedup is close to linear, and watch per-core efficiency as you go. When doubling the machine gives you 1.3 times the throughput, the next step is out, not up.
Deep Dive: Resharding without downtimeShow
The hardest part of sharding is not the first split; it is the second. Data keeps growing, and you need to add shards while the system keeps serving traffic.
Why hash(key) mod N is a trap. With plain modulo placement, changing N from 4 to 5 moves about 80% of all keys, since a key stays put only if hash mod 4 equals hash mod 5. Moving 80% of a multi-terabyte dataset while serving traffic is a project measured in weeks.
Logical shards (virtual buckets). The usual fix is to separate logical shards from physical machines:
- Hash each key into one of a large, fixed number of logical shards, for example 4,096. This number never changes.
- Keep a small mapping from logical shards to physical database servers, such as 16 servers with 256 logical shards each.
- To add capacity, move whole logical shards to new servers and update the map. No key ever changes its logical shard, so nothing is rehashed.
Instagram described this design in 2012: thousands of logical shards stored as PostgreSQL schemas on far fewer physical servers, with the logical shard ID embedded in each generated ID so any ID can be routed without a lookup. Notion's 2021 write-up on sharding PostgreSQL described 480 logical shards spread across 32 physical databases, keyed by workspace ID. Redis Cluster's 16,384 hash slots and Cassandra's virtual nodes are the same idea built into the database.
Moving a logical shard online. A typical procedure:
- Copy a snapshot of the shard to the new server.
- Catch up by replaying changes from the source's replication stream or change log until the copy is only seconds behind.
- Briefly pause writes for that shard only, typically for seconds, and let the copy apply the final changes.
- Switch the routing map so the shard now points to the new server, then resume writes.
- Verify, for example with row counts and checksums, then delete the old copy after a safety period.
An alternative to the pause is dual writing: the application writes to both old and new locations during the move, a backfill copies historical rows, a verifier compares them, and reads switch over once they match. Dual writing avoids the pause but is harder to get right, because the two writes can fail independently, so it needs reconciliation.
Choosing the number of logical shards. Too few, and you cannot spread load finely; with 16 logical shards you can never use more than 16 machines. Too many, and per-shard overhead grows: connection pools, schemas, monitoring and migrations that run once per shard. Hundreds to a few thousand is common, sized so the largest expected cluster still has several logical shards per machine.
Hot shards. Even with even key placement, one shard can be hot because one key is hot: a celebrity account, a viral post, a huge tenant. Logical shards let you move that shard to a dedicated server. For a single hot key, split it into sub-keys or cache it heavily; for one huge tenant, give it its own physical shard through a directory entry that overrides the hash.
Key Takeaways#
- Scaling up is simple and powerful but has a ceiling, a steep price at the top, poor elasticity and a single failure domain.
- Scaling out has no fixed ceiling, tolerates failures and follows demand, but needs stateless services and brings distributed-systems complexity.
- Make app servers stateless: sessions in Redis or tokens, files in object storage, data in databases, slow work in queues.
- Concentrate state in a few specialised systems and scale them deliberately: cache, replicas, queues, CDN, then shard when numbers demand it.
- Shard by the main access pattern, prefer hash-based placement with consistent hashing, and avoid premature sharding.
- Find and remove SPOFs, including hidden ones like DNS, directories and single zones; redundancy must span failure domains.
- Autoscale with headroom, caps, connection pooling and safe scale-in; buffer bursty compute behind a queue.
- Separate performance problems (slow for one user) from scalability problems (slow under load); fix the first before scaling.
- Any serial work shared by all requests caps speedup (Amdahl's law); independent requests scale nearly linearly (Gustafson's law).
- Size fleets as peak ÷ (per-instance capacity × target utilisation) × Z ÷ (Z − 1); three zones need less spare capacity than two.
- Climb the database ladder in order: fix queries, scale up, pool, cache, replicas, async writes, vertical partitioning, then sharding.
- Shard into many logical shards on fewer servers so you can reshard by moving shards; never use plain
hash mod N. - Connection-holding tiers are stateful: isolate them in gateways with a registry, drain slowly and make clients reconnect with jitter.