Study guide · System design

Study guide: scalability

Estimate demand, find the limiting resource, scale reads and writes independently, and keep overload bounded.

Contents
  1. ·Learning objectives
  2. §1Core concepts
  3. §2Workload and capacity estimates
  4. §3Scaling compute and routing work
  5. §4Scaling reads without losing control of misses
  6. §5Scaling data and locating hot partitions
  7. §6Asynchronous work and overload
  8. §7Measuring, testing and evolving the design
  9. ·Common mistakes
  10. ·Practice questions
  11. ·Review checklist

· · Start here

Learning objectives

  1. Explain scalability in terms of growing workload, required performance and additional resources.
  2. Estimate peak request rates, concurrency, storage growth and capacity headroom from stated assumptions.
  3. Choose vertical or horizontal scaling for a service and identify the shared bottleneck that limits either choice.
  4. Decide when caching, read replicas and content delivery reduce read pressure, including the effect of cache misses.
  5. Distinguish replication from partitioning and calculate the load on a hot shard.
  6. Size asynchronous workers and bounded queues, then choose a response when arrival rate exceeds processing capacity.
  7. Use measurements and load tests to decide which part of a system to scale next.

§1 · Definitions

Core concepts

This section defines scalability, load, capacity, throughput and latency. These terms let a design state what grows and what level of service it must preserve.

A design scales only relative to a workload and a target. Doubling servers while response times rise beyond the agreed limit does not demonstrate useful scale. The workload must include its shape: a read, a payment write and a large file upload consume different resources even if each counts as one request. As load rises, a component reaches a limit in CPU, memory, storage I/O, network traffic, connection count or a downstream service. Adding capacity at another component leaves that limit in place.

Scalability is therefore a relationship, not a property that can be established by a single benchmark number. A useful claim specifies the starting workload, the increased workload, the resources added and the service target preserved. For example, an application might sustain twice as many product-page reads with twice as many application instances while keeping the 99th-percentile response time below a stated bound. The same result says nothing about checkout writes if all checkout requests must update one database leader.

Throughput counts completed work. A router can accept requests faster than the system completes them, but its acceptance rate is not useful throughput if the requests wait, fail or time out. Latency makes that distinction visible. As a resource approaches its usable limit, waiting often grows faster than the incoming rate because work competes for the same CPU time, lock, disk or connection. The resulting delay can create more in-flight work, which consumes memory and connection slots and can cause further delay. This feedback explains why a modest traffic increase can produce a disproportionate increase in the slowest response times near the resource limit.

The bottleneck can move after a successful change. If the application tier initially limits throughput, doubling it may expose a database write limit; improving the database may then expose a third-party API quota. Scaling efficiency captures the effect: if doubling an application tier yields only a small increase in completed requests, its new capacity is stranded behind another limit. Efficiency is workload-specific. A change that helps independent reads can do little for writes that coordinate through one record.

Correctness belongs in the target as well as speed. Serving a stale account balance quickly, losing an accepted job or processing an order twice can make a capacity chart look better while the system fails its purpose. A scale decision should state which data may be stale, which work can be delayed and which operations require an authoritative result before acknowledging success.

A useful capacity statement also names its boundary. Measuring only the API process excludes the database, background work and network needed for a user request to finish. Measuring an entire service path gives a more honest result, but individual component measurements remain necessary to find the limiting resource. The boundary should be consistent between the baseline and the scaled design. Otherwise a comparison can quietly move work outside the measured system, such as returning before background processing finishes, and report a throughput gain that reflects changed accounting.

A frequent confusion is that scalability means handling any number of users. A count of registered users says little about simultaneous demand, and a system may handle more read traffic while remaining unable to handle more writes. State the operation, its peak rate and the performance target before judging whether it scales.

§2 · Mechanism

Workload and capacity estimates

The first design step is to turn usage into rates for each important path. Divide daily operations by 86,400 seconds to obtain a daily average, then apply a peak factor supported by traffic history or an explicit assumption. Estimate reads and writes separately. Multiply operation count by payload size for storage and bandwidth, allowing separately for indexes, replicas, retention and protocol overhead. These are planning inputs, not universal machine limits.

Concurrency depends on both arrival rate and duration. For a stable system, Little's law gives average in-flight work as arrival rate multiplied by average time in the system: L = λW. The units must match: requests per second times seconds gives requests. A slowdown can therefore exhaust a connection or worker pool even when the arrival rate has not changed.

Specify the workload before sizing it

An operation mix is more informative than one total request rate. Record the fraction of reads, writes, searches, uploads and background jobs, because their costs differ and they may peak at different times. A typical read might use an indexed lookup; a search might scan or rank many candidates; an upload might use little CPU but substantial network bandwidth. Averages across them hide the path that runs out of capacity first. Separate successful requests from rejected and timed-out requests so a system cannot appear faster merely by discarding expensive work.

The time window changes the meaning of a peak. An hourly average can hide a brief burst that uses all available database connections or fills a waiting line for background work in seconds. Short windows are useful for admission and burst sizing; longer windows help plan sustained worker and storage capacity. The chosen peak factor must correspond to the same window as the target rate. Multiplying a daily average by a peak factor observed for five-minute windows produces a five-minute planning rate, not a universal maximum. If traffic history is unavailable, use an explicit scenario and show how the result changes with a different factor.

Data volume needs a separate estimate from request rate. Count new logical records per day, bytes per record, retention time and extra physical copies. Indexes, database logs, extra data copies and backup retention increase physical storage beyond logical payload bytes. Capacity also depends on bytes moved per second: a modest request count with large responses can saturate the network before CPU. Conversely, tiny writes that update several indexes can exhaust storage I/O before network bandwidth. The estimate should identify which multiplier is measured and which is assumed rather than rolling all overhead into an unexplained safety percentage.

Worked examplestorage and transfer growth

Consider an event service that accepts 8 million new events per day, each with an average logical size of 700 bytes. Assume two database copies, an index equal to 40% of the event payload on each copy, 30 days of online retention and no compression. Daily logical payload is 8,000,000 × 700 = 5,600,000,000 bytes, or 5.6 GB using decimal units. Per copy, payload plus index is 5.6 × (1 + 0.40) = 7.84 GB/day. With two copies, the online footprint grows by 7.84 × 2 = 15.68 GB/day; 30 days require 15.68 × 30 = 470.4 GB. The check is to compute per event instead: 700 × 1.40 × 2 = 1,960 bytes, and 8,000,000 × 30 × 1,960 = 470,400,000,000 bytes, again 470.4 GB. Backups, logs and filesystem reserve would need separate estimates.

Assume each accepted event also causes 1,200 bytes of incoming network traffic, including request overhead. The daily incoming transfer is 8,000,000 × 1,200 = 9.6 GB. The daily average is 9.6 GB ÷ 86,400 s ≈ 111,111 bytes/s, or about 0.11 MB/s. This small average does not size a burst; a peak factor of 20, explicitly assumed for the relevant short window, would make the incoming rate about 2.22 MB/s. Making extra copies and downstream exports would add other network paths.

Apply headroom to a failure scenario

Headroom is easiest to reason about as an explicit survival condition. A pool of identical instances with one-instance failure tolerance must have enough capacity in its surviving instances at expected peak. Reserving a fixed percentage without identifying the failure can be misleading: losing one of two instances removes half the pool, whereas losing one of ten removes a tenth. The reservation must also account for uneven routing, maintenance and autoscaling delay. If a database or external service has a lower limit, spare application servers do not provide end-to-end headroom.

Capacity should be budgeted along the entire request path. If each checkout request issues two database writes and one call to an external provider, a peak of 500 checkouts per second implies 1,000 database writes per second and 500 provider calls per second before retries, assuming one of each stated operation succeeds on the first attempt. The slowest budget determines what can be admitted. If the provider's sustained quota is only 400 calls per second, adding application servers cannot make 500 completed checkouts per second possible under that design. The choices are to secure more provider capacity, change the workflow or bound admission to the rate the path can complete.

Little's law assumes a stable observation period in which arrivals and completions balance on average. During an overload that continuously grows a queue, the arithmetic can describe a snapshot but does not imply a steady-state concurrency or finite waiting time. Its W includes all time in the system for the work being counted, including queueing if the boundary includes a queue. It uses averages; multiplying peak rate by the 99th-percentile latency does not calculate the 99th percentile of in-flight work. Use the law to cross-check measured averages, then inspect distributions and burst behavior separately.

Worked examplepeak load and in-flight requests

Consider a service with 2 million daily active users, each making 12 reads and 2 writes per day. Assume the busiest hour has four times the daily average rate, and assume the average read takes 80 ms at that rate.

First, daily reads are 2,000,000 × 12 = 24,000,000, so average reads are 24,000,000 ÷ 86,400 ≈ 278/s. Daily writes are 2,000,000 × 2 = 4,000,000, so average writes are 4,000,000 ÷ 86,400 ≈ 46/s. Apply the assumed peak factor to the unrounded rates: reads are 24,000,000 ÷ 86,400 × 4 ≈ 1,111/s and writes are 4,000,000 ÷ 86,400 × 4 ≈ 185/s. The total is (24,000,000 + 4,000,000) ÷ 86,400 × 4 ≈ 1,296 requests/s, which agrees with 1,111 + 185 = 1,296 after rounding.

With the assumed 80 ms, or 0.08 s, average in-flight reads are 1,111/s × 0.08 s ≈ 89. Check the dimensions: the seconds cancel, leaving requests. If latency rises to an assumed 0.40 s at the same arrival rate, in-flight reads become 1,111 × 0.40 ≈ 444. That fivefold increase can saturate a fixed pool even though traffic did not grow.

§3 · Mechanism

Scaling compute and routing work

Vertical scaling is often the simplest first response to a measured compute or memory limit, but a single machine has a finite size and remains one failure domain. Horizontal scaling increases parallel capacity when requests can be handled by interchangeable instances. Authentication sessions, uploaded files and workflow state must then live in a shared store or be otherwise available to any instance. That shared store has its own capacity limit. Adding API instances can increase its connection and query load until it becomes the bottleneck.

Find the work that can run in parallel

Horizontal scaling works best when one request can finish without waiting for another instance's private state. A stateless API can accept a request on any healthy instance if persistent data and session state are accessible through services with an explicit consistency contract. Stateless does not mean that the application uses no memory; each instance still holds code, caches and current requests. It means the correctness of the next request does not depend on reaching that same instance. Storing a user's cart only in a process's memory creates a hidden routing constraint and makes a failed instance lose the cart.

Some work cannot be divided freely. Updating a shared counter, enforcing uniqueness or writing an ordered stream may require coordination at one owner. If a fraction of a request path must remain serialized, more parallel workers reduce only the other fraction. Amdahl's law captures this limit: the serial fraction sets a ceiling on speedup even with many workers. The law is a model, not a prediction of an actual deployment, because network calls, contention and changing workload also affect measured performance.

Worked examplea serial fraction limits speedup

Consider a computation whose measured work is 20% serial and 80% independently parallel. Assume four equal workers, no communication overhead and the same amount of total work. Amdahl's law gives 1 ÷ (0.20 + 0.80 ÷ 4) = 1 ÷ 0.40 = 2.5 times the one-worker speed. The check is in time units: a one-worker job takes one unit, while four workers take 0.20 + 0.20 = 0.40 units, so 1 ÷ 0.40 = 2.5. Even if the parallel portion had unlimited workers, the serial 0.20 units would cap speedup at 1 ÷ 0.20 = 5. A real service should measure its actual shared limits rather than assuming the model's ideal workers.

Route traffic without concentrating it again

A load balancer chooses an instance, but the choice is only useful if health signals and routing behavior match the workload. Simple equal distribution is reasonable for similarly costly requests. If one request can occupy a worker for a long time, equal request counts can still produce unequal active work. Connection-level routing can also be uneven when a few long-lived clients send many requests over persistent connections. Observe per-instance active requests, latency and resource use after routing, rather than inferring balance from total instance count.

A health check must detect that an instance can serve real traffic, not merely that its process exists. A probe that depends on every downstream service can cause all instances to become unhealthy during one shared outage, leaving no place to serve a degraded response. Conversely, a probe that always succeeds while a worker pool is exhausted can keep sending traffic to an unusable instance. Separate the signal that a process should restart from the signal that it should receive new requests, and verify behavior during slow dependencies, startup and shutdown. Removing an instance from routing before stopping it lets in-flight requests finish within a bounded period.

Connections are a shared resource often missed in an instance-count calculation. Each new API instance may create its own pool of database connections. Ten instances with a maximum of 40 connections each can offer up to 400 simultaneous database connections even if the database can use only 250 effectively. The application pool limit should be chosen from the database's measured connection budget after reserving connections for administration, migrations and other clients. Per-instance limits may need to shrink as the fleet grows, or a shared pooling layer may be appropriate.

Worked examplea shared connection budget

Consider a database with a measured usable budget of 300 concurrent application connections. Assume 30 connections are reserved for other services and 20 for maintenance, leaving 300 − 30 − 20 = 250 for this API. With eight API instances, a per-instance pool of 30 allows 8 × 30 = 240 connections, leaving ten within the budget. If autoscaling grows to twelve instances without changing the limit, the maximum becomes 12 × 30 = 360, exceeding the API budget by 360 − 250 = 110. To remain within it at twelve instances, the integer per-instance maximum is floor(250 ÷ 12) = 20, giving 12 × 20 = 240 and ten spare. This does not prove that 20 connections per instance are enough for the latency target; a load test must check both limits together.

Autoscaling uses a signal and takes time to start new instances, warm caches and establish connections. A reactive rule cannot instantly supply capacity for a burst that arrives in seconds. Keep enough standing capacity for the burst window, or bound admission while capacity catches up. Scaling down also needs care: draining connections and unfinished requests prevents an apparently healthy reduction in cost from turning into errors. Vertical scaling and horizontal scaling can be combined, but the choice should follow the resource that actually saturates and the failure tolerance required.

Instance counts also need to fit the failure domains. Placing six instances on one host or in one zone may give six processes but little protection against a host or zone outage. Distribute capacity so the remaining locations can carry the required load after the failure that the target includes. This can require more total instances than a one-process-failure calculation. Confirm the scenario in a controlled test: remove the chosen location, observe rerouting and startup delays, then measure whether latency and error targets still hold while traffic remains at the planned peak.

The diagram shows how requests reach interchangeable instances and then converge on a shared database.

System flow
Clients → load balancer → API instance A ─┐
                        → API instance B ─┼→ database
                        → API instance C ─┘

Read the arrows from left to right. The API tier can gain capacity by adding instances, but every instance still uses the same database; its write and connection limits must be checked separately. A load balancer also needs a redundant deployment and health checks if requests are to survive an instance failure.

Worked examplesizing an API pool

Consider a peak of 2,400 requests per second. Assume a load test shows one instance meets its latency target at up to 500 requests per second, and assume the pool must remain within that tested limit after any one instance fails.

The arithmetic minimum while every instance is healthy is ceil(2,400 ÷ 500) = 5 instances. With one failed instance, the minimum is ceil(2,400 ÷ 500) + 1 = 6 total instances: five survivors each handle 2,400 ÷ 5 = 480/s. If seven instances are provisioned, normal load is 2,400 ÷ 7 ≈ 343/s, or 343 ÷ 500 ≈ 69% of the tested per-instance rate. After one fails, each survivor handles 2,400 ÷ 6 = 400/s, or 80% of that rate. The check is 6 × 500 = 3,000/s, above the 2,400/s target. The percentages describe use of a tested per-instance throughput; they do not establish CPU utilisation.

§4 · Mechanism

Scaling reads without losing control of misses

A cache helps when requests repeat for the same key while its entry is valid. A high volume of mostly unique searches can produce few hits, while a smaller volume concentrated on popular product pages can produce many. On a miss, the application still calls the backing store. It must size that store for plausible miss spikes, including expiry of popular entries and cache failure. Expiration or invalidation also sets the staleness the product can tolerate.

A read replica can spread database reads, but it must receive every relevant write. It therefore increases read capacity and can aid failover; it does not multiply primary write capacity. A read that must reflect a just-completed write may need to use the primary or another mechanism with the required consistency.

Place a cache where it removes the expensive work

An edge cache avoids a trip to the origin and can save bandwidth as well as computation. An application cache near the service may avoid repeated database reads while still requiring the API to parse, authenticate and route each request. A database buffer cache speeds storage access inside the database but does not remove query execution or database connections. These layers can coexist. For each layer, identify the exact work bypassed on a hit and the next component reached on a miss; otherwise a high hit ratio can be mistaken for relief of the wrong bottleneck.

A cache key must capture every input that changes the response. If a product price varies by region, a key based only on product ID can return the wrong price. User-specific or authorization-sensitive data requires particular care because a shared cache can expose one user's response to another. Key design also affects reuse: including a unique request token in every key makes repeated requests appear different and drives the hit ratio toward zero. Measure hit ratio by endpoint and key family, together with the number of requests and bytes reaching the backing store.

A time to live trades freshness for fewer origin requests. A short lifetime reduces the duration of stale results but sends more misses to the backing store. A long lifetime increases reuse but can show old values unless writes explicitly invalidate affected keys. Invalidation requires knowing every cached representation touched by a write. If one product change affects a product page, a category list and a search result, updating only one key leaves the other views stale. The required freshness contract should decide the policy: a product description might tolerate a short delay, while an inventory reservation may require an authoritative check.

A stampede can make an apparently effective cache collapse at a predictable expiry time. If thousands of clients request a popular key just after its entry expires, they may all query the database before the first response refills the cache. A single-flight mechanism allows one request to refresh that key while others wait briefly or use an acceptable older value. Varying expiry times can avoid simultaneous expiration of many keys. A stale-while-revalidate policy can keep serving an older answer while one worker refreshes it, but only for data whose freshness requirement permits that delay. Limits on concurrent fills protect the origin when it cannot absorb every miss.

Negative caching helps when clients repeatedly request nonexistent keys, but a missing result can become stale when the item is created. Its lifetime should therefore match the cost of repeated misses and the expected time until a new item must become visible. Errors are different from valid absence: indiscriminately caching a database timeout as “not found” can turn a short outage into a longer incorrect response.

Worked exampletwo layers of read relief

Consider 10,000 product-page requests per second. Assume an edge hit ratio of 60% and, for requests that miss the edge, an application-cache hit ratio of 75%. Edge hits are 10,000 × 0.60 = 6,000/s, leaving 10,000 × 0.40 = 4,000/s for the API. Application hits are 4,000 × 0.75 = 3,000/s, leaving 4,000 × 0.25 = 1,000/s for the backing read. Check: 6,000 + 3,000 + 1,000 = 10,000/s. The combined hit fraction is (6,000 + 3,000) ÷ 10,000 = 90%, not 60% plus 75%, because the second percentage applies only to edge misses.

Assume the edge is unavailable while the application cache remains at a 75% hit ratio for its now larger input. The API receives all 10,000 requests per second, and the database receives 10,000 × 0.25 = 2,500/s, or 2.5 times its normal 1,000/s. If both caches are unavailable, the database may see all 10,000/s, ten times normal. These are conditional planning scenarios, not guarantees that hit ratios stay constant under a traffic shift.

Route reads according to their consistency needs

A follower usually applies changes after the primary has accepted them. This delay can be tiny in ordinary operation and much larger during a write burst, network interruption or replay after recovery. A replica's spare CPU therefore says nothing about whether it can answer an immediate post-write read correctly. One approach routes such reads to the primary for a bounded period. Another carries a write position with the request and waits until the follower has applied at least that position. The first costs primary read capacity; the second can add waiting and needs a fallback if the follower remains behind.

Replication also has a write-side cost. Each follower must receive and apply the change stream, and adding followers can increase network traffic and operational work. It is useful to compare the reads removed from the primary with the replication cost and the freshness achieved. A follower that cannot keep up with writes may be unsuitable for a freshness-sensitive endpoint even if it handles the nominal read rate. Read routing should be verified during failover and lag spikes, not only when replicas are caught up.

Cache and replica choices interact. A replica can be the backing source for a cache, but refreshing a key from a lagging replica may place an older value back into the cache after the primary has accepted a new write. The cached result can then remain stale for its full lifetime unless invalidated again. For data with strict post-write visibility, refresh from an authoritative path or carry a version that prevents an older value from replacing a newer one. For data that permits bounded staleness, document the combined lag and cache lifetime rather than considering either delay in isolation.

Static assets can be served from a content delivery network so their bytes bypass the application and origin for most requests.

The diagram shows two ways to remove work from the primary read path.

System flow
Client → edge cache ──hit──────────────→ response
                 └──miss→ API → cache ─hit→ response
                                   └──miss→ read replica or primary

The upper paths return a cached answer. Each miss moves farther toward the backing store, so a falling hit ratio increases downstream traffic even when client traffic stays constant.

Worked examplecache misses at peak

Consider 20,000 reads per second and assume an 85% hit ratio for a cache in front of a database. Hits are 20,000 × 0.85 = 17,000/s, and misses are 20,000 × (1 − 0.85) = 3,000/s. Check: 17,000 + 3,000 = 20,000/s. If the cache is unavailable, as many as 20,000/s can reach the backing path, which is 20,000 ÷ 3,000 ≈ 6.7 times the normal miss rate. The design needs a fallback capacity plan, early rejection of excess work or a degraded response for that event.

§5 · Mechanism

Scaling data and locating hot partitions

Replication copies work and data; partitioning divides them. When a single write leader reaches its sustained capacity, adding followers generally does not remove that leader's write work. Partitioning can spread writes and storage, provided the key distributes traffic and common operations stay within one partition. Each partition can then be replicated for resilience. Cross-partition queries, joins and transactions cost more because several owners must participate.

A hash can distribute many ordinary keys evenly yet still leave one very popular key hot. Measure requests and bytes per partition and per leading key, not only record counts. For a hot key, possible remedies include splitting its work into independently addressable subkeys, moving it to dedicated capacity or changing the algorithm so one request touches fewer partitions. Each remedy changes read assembly or ordering, so its correctness cost must be stated.

Choose a key from access patterns

The partition key determines which records can be handled together cheaply. A user ID can keep one user's records and transactions near one owner, but it may concentrate a very active user. A random or hashed key may balance writes across owners while making a user's history query contact many partitions. A time-based key makes recent records easy to find and old ranges easy to retire, but current writes can all land on the newest partition. There is no key that optimizes every query. List the dominant reads, writes and transactional boundaries, then estimate their fan-out under candidate keys.

Hash partitioning tends to distribute many independent keys but makes an ordered range query contact multiple owners unless another index supports it. Range partitioning preserves locality for interval scans and retention, but a monotonic key such as creation time can send all new writes to the latest range. Splitting a range, adding a write-distribution prefix or separating hot recent data can relieve that concentration. These choices also change read assembly. For example, prefixing an order ID to spread writes means a query for all orders in a day may need to search every prefix.

Fan-out consumes capacity even when each branch is fast. If one search contacts every shard, adding shards can increase the number of calls per search. The response often waits for the slowest required branch, so one lagging shard can dominate the slowest user-visible responses. A coordinator may also need memory to merge and sort partial results. Partitioning therefore improves capacity when it divides costly work, but it can harm queries that must repeatedly reconstruct a global view. A materialized view, a dedicated search index or a different key may be justified when such queries dominate.

Secondary indexes create another tradeoff. An index that makes a read selective must be updated as relevant data changes, so it consumes write I/O and storage. A global index spanning shards may itself need partitioning and a consistency policy. Before adding one to solve a slow query, estimate its update rate and the extra writes it creates. A fast query that doubles the work of the limiting write path can reduce overall capacity. Sometimes a precomputed view updated asynchronously is sufficient; when it is, the reader must accept the view's update delay.

Worked examplefan-out and total query work

Consider 800 searches per second, each querying every shard. Assume eight shards and one database request per shard for each search. The database tier handles 800 × 8 = 6,400 shard requests per second. If the data is repartitioned into 16 shards and the search still contacts every shard once, it handles 800 × 16 = 12,800 shard requests per second. Check per shard: each handles 800 search requests per second in both arrangements, so 8 × 800 = 6,400 and 16 × 800 = 12,800. Whether each smaller shard performs less work per request depends on the query and index; doubling shard count alone does not guarantee that end-to-end search becomes faster.

Plan the movement of ownership

Resharding is a data migration as well as a routing change. A naive rule such as hash(key) mod shard_count can remap many keys when the shard count changes. An indirection map, fixed logical partitions or another stable routing scheme can limit movement to selected ranges. During a migration, readers and writers must agree which owner is authoritative. A common sequence copies a snapshot, applies changes made during the copy, validates counts and checksums, switches routing, and retires the old copy after in-flight work is safe. The steps must prevent a write from being acknowledged on an owner that later becomes invisible.

Every shard may also have replicas, so changing the number of shards changes storage, network and operational cost. Replication is useful for durability and failover only if its acknowledgement and recovery rules are clear. A follower that has not received an acknowledged write cannot safely become leader for a path that promises that write survives. The chosen durability guarantee affects write latency and capacity; it should be stated alongside the scaling design.

Distinguish a hot key from a busy partition

A busy partition may hold many ordinary keys that happened to be assigned together, or it may hold one key that dominates. Rebalancing whole key ranges helps the first case. It cannot divide the second if all of that key's operations still need one owner. A hot key may be read-heavy, write-heavy or both. Read-heavy keys may benefit from caching or replicated read serving. Write-heavy keys require a more careful change: splitting independent subrecords, batching commutative updates or assigning dedicated capacity. A single ordered balance cannot safely be split into unrelated writers without a reconciliation rule.

The diagram separates partitioning from replication: records are divided across two leaders, then each leader's records are copied to a follower.

System flow
key → partition rule ┬→ shard A leader → shard A follower
                     └→ shard B leader → shard B follower

Read across a branch to see replication and compare the branches to see partitioning. A follower can serve suitable reads or take over after failure; a new shard changes which leader owns writes.

Worked examplea hot customer key

Consider 16 shards and 16,000 requests per second. Assume one customer generates 20% of requests and the remaining 80% distributes evenly by key among the shards. Average load is 16,000 ÷ 16 = 1,000/s. The hot customer generates 16,000 × 0.20 = 3,200/s; ordinary traffic contributes 16,000 × 0.80 ÷ 16 = 800/s to each shard. Its shard therefore receives 3,200 + 800 = 4,000/s, four times the average. The other 15 receive 800/s each. Check: 4,000 + 15 × 800 = 16,000/s.

Assume the hot customer's work can be divided evenly across four subkeys that land on four distinct shards. Each of those shards then receives 3,200 ÷ 4 + 800 = 1,600/s, or 1.6 times average; the other 12 remain at 800/s. Check: 4 × 1,600 + 12 × 800 = 16,000/s. Reads that need all of that customer's data now assemble four subkeys, and any operation requiring one total order needs additional coordination.

§6 · Mechanism

Asynchronous work and overload

Moving non-immediate work to a queue shortens the foreground request, but it does not create processing capacity. Workers must drain the queue at least as fast as the long-run arrival rate; otherwise backlog and waiting time grow. A bounded queue makes overload visible before memory or storage is exhausted. Producers then need a policy: slow down, retry later with a delay, receive a rejection, or receive a reduced service. Retries require limits and spacing because immediate retries add more traffic to an overloaded path.

Define what acknowledgement means

An asynchronous path changes the contract of the foreground response. If a request returns after placing an email job in a durable queue, it can truthfully say that the job was accepted for later processing, not that the email was delivered. A product should expose an operation status or notification if the user needs the final outcome. If the queue write fails, the foreground path must not claim success unless it has another durable record from which the work can be recovered. The same distinction applies to image conversion, search indexing and payment follow-up actions.

Many queues redeliver a job if a worker crashes before acknowledging completion. That protects against lost work but requires the consumer to tolerate duplicates. A worker that sends the same payment instruction twice could create two charges unless it supplies a stable operation identifier and the receiver deduplicates or enforces a uniqueness constraint. An idempotent consumer can record the job identifier together with the side effect in one transactional boundary where possible. For an external effect that cannot be made atomic with the record, the workflow must explicitly handle uncertain outcomes and reconciliation.

A failed job should not block all later jobs or retry forever at full speed. Classify failures: invalid input may be permanently rejected, while a temporary dependency outage may justify delayed retry. Cap the number of attempts or total retry age, record the reason, and send irrecoverable jobs to a dead-letter queue for inspection and repair. The queue's oldest-job age is often more meaningful to users than its item count. Ten thousand short jobs may drain quickly, while a few very slow jobs can make the oldest work miss its deadline.

Control arrivals before a dependency collapses

Admission control protects both the queue and its downstream dependency. A queue bound by item count may still consume too many bytes if jobs vary greatly in size; a bound by bytes may still allow too many tiny jobs with high processing cost. Use the resource that actually limits the path, and consider a second bound for another important dimension. Per-caller rate limits can prevent one client from consuming the whole budget, while a global concurrency limit protects a shared database or provider quota. A fair policy needs a clear priority rule when capacity is scarce.

When a request cannot be admitted, a prompt rejection is usually better than accepting it into a queue whose predicted wait exceeds its usefulness. The response can tell a cooperative client when retrying may help, but it should not promise an exact recovery time without control over future arrivals. A retry policy uses a deadline, a maximum attempt count and randomized spacing so many clients do not retry in lockstep. A retry at every service layer can multiply load. If three layers each make three attempts, one top-level request can generate 3 × 3 × 3 = 27 calls at the bottom layer in the worst case. The check is that each of three outer attempts triggers three middle attempts, each of which triggers three bottom attempts.

Size workers from service time and quotas

Worker count is constrained by both local resources and the slowest dependency. Suppose each worker spends much of its time waiting on an external API. More concurrent workers can increase throughput until the external rate limit or connection budget is reached; beyond that, they mainly produce more failures and retries. If work is CPU-bound, the useful concurrency may be closer to available CPU capacity. Measure completed jobs per second at the required success and latency target, then leave headroom for variation and recovery. A queue can smooth a short burst when its maximum waiting time is acceptable, but cannot absorb a sustained arrival rate above completion capacity indefinitely.

Worked exampleworkers, queue bound and waiting time

Consider an image processor receiving 900 jobs per second during a five-minute promotion. Assume each worker completes 30 jobs per second at its tested target, and the dependency can sustain at most 1,000 completions per second. The arithmetic minimum for steady processing is ceil(900 ÷ 30) = 30 workers; their aggregate capacity is 30 × 30 = 900/s, leaving no spare rate to drain any queue. With 34 workers, the tested aggregate is 34 × 30 = 1,020/s, but the dependency caps useful completion at 1,000/s. The usable drain margin at the 900/s arrival rate is therefore 1,000 − 900 = 100 jobs/s.

Assume a 20-second burst at 1,200 jobs per second while completion remains at 1,000/s. Backlog grows by (1,200 − 1,000) × 20 = 4,000 jobs. If arrivals return to 900/s, clearing that backlog takes 4,000 ÷ (1,000 − 900) = 40 s. Under a first-in, first-out approximation, a new job arriving at the end of the burst sees roughly 4,000 ÷ 1,000 = 4 s of waiting from the queued work ahead of it; actual delay depends on job sizes and scheduling. A queue bound below 4,000 jobs would reject some burst work. A larger bound can hold it but does not improve the 40-second recovery time. Check the burst balance: 1,200 × 20 = 24,000 arrivals and 1,000 × 20 = 20,000 completions, leaving 4,000.

The diagram shows the feedback loop that is required when producers can outrun consumers.

System flow
Producer → admission limit → bounded queue → workers → dependency
              ↑                   │
              └── reject or slow ─┘

Follow the top line for admitted work. When the queue approaches its bound, the lower path feeds a slowing or rejection decision back toward producers; simply adding queue space postpones the same capacity problem.

Worked examplebacklog and recovery

Consider an arrival rate of 3,000 jobs per second and worker capacity of 2,000 jobs per second. Assume those rates remain constant for ten minutes. The net backlog growth is 3,000 − 2,000 = 1,000 jobs/s; over 10 × 60 = 600 s, it is 1,000 × 600 = 600,000 jobs. Check: arrivals are 3,000 × 600 = 1,800,000 and completions are 2,000 × 600 = 1,200,000, leaving 600,000.

Assume arrivals then fall to 1,500 jobs per second while capacity remains 2,000. The queue drains at 2,000 − 1,500 = 500 jobs/s, so clearing 600,000 jobs takes 600,000 ÷ 500 = 1,200 s, or 20 minutes. That recovery time may be unacceptable even if the queue has room, so admission limits or extra consumer capacity must be planned before the burst.

§7 · Mechanism

Measuring, testing and evolving the design

Measure request rate, success rate and latency by operation, alongside saturation of CPU, memory, database connections, I/O, cache, queue and downstream quotas. A percentile must be calculated from the request distribution for the relevant interval; averaging per-host percentiles does not produce a fleet percentile. Record the workload mix and key skew in load tests so a test reflects expensive operations and hot customers, not only uniform requests. Test both the normal peak and the failure or miss path that consumes reserved headroom.

Use measurements that identify the limit

A system-wide latency graph shows that users are waiting; it does not by itself show where the wait occurs. Break requests down by operation and by major dependency. Record time spent waiting for a connection, executing a query, receiving a remote response and serving from a cache. Pair these timings with the resource's own signals, such as CPU run time, disk queue depth, active database sessions, cache evictions or worker-pool occupancy. A rise in API latency with idle API CPU and a full database connection pool suggests a different remedy from rising API CPU with a responsive database.

A service-level objective gives the capacity estimate a pass criterion. An objective should name the operation, the success condition, the latency boundary and the evaluation window. For example, checkout might require a stated percentage of accepted attempts to finish within a stated time over a month. The target should also specify whether rejected requests count as failures and how planned maintenance is treated. Without those boundaries, a load test can improve a reported percentile by dropping slow requests before they complete.

Tail latency matters because users of a multi-step operation experience the slow branch, not the average branch. A page that makes several independent service calls may wait for the last required response. If each service has occasional slow requests, the chance that at least one call is slow rises with the number of calls. One should therefore inspect per-operation percentiles and end-to-end percentiles together. Fleet percentiles must be calculated from the combined request distribution or compatible histograms. Averaging the 99th percentile from a small quiet host with that from a busy host gives each host equal weight even though they served different numbers of requests.

Worked examplewhy host percentiles cannot be averaged

Consider two hosts during one interval. Assume host A handles 100 requests, with 99 responses at 10 ms and one at 1,000 ms. Assume host B handles 9,900 requests, all at 20 ms. Under the nearest-rank definition, host A's 99th percentile is its 99th ordered value, 10 ms, and host B's is 20 ms. Their unweighted average is (10 + 20) ÷ 2 = 15 ms. Across the fleet there are 99 responses at 10 ms, 9,900 at 20 ms and one at 1,000 ms, for 99 + 9,900 + 1 = 10,000 responses. The fleet's 99th ordered value is at rank ceil(0.99 × 10,000) = 9,900, which lies among the 20 ms responses. The fleet 99th percentile is therefore 20 ms, not 15 ms. The rank check shows why host-level percentile averages cannot replace the combined distribution.

Run a load test that preserves the workload

A test should state whether clients send requests at a chosen arrival rate or wait for each response before sending the next. In a closed-loop test, slow responses can reduce the number of new requests, accidentally easing the load exactly when the system struggles. A rate-driven test can keep the offered rate independent of response time, revealing queue growth and errors under overload. Both have uses, but the method must be recorded so throughput and latency are interpreted correctly. Include request timeouts in the reported result; a percentile of only completed successes omits the worst user experiences.

Coordinated omission is especially misleading for short stalls. A closed-loop client that waits two seconds for one response may send no other requests during those two seconds, so the test records one slow request rather than the delays an ongoing arrival stream would have encountered. A load generator should preserve the intended arrival schedule or explicitly account for missed arrivals. The test should also use representative payloads, key popularity, cache warmness and background work. A uniformly random key set may make a cache look ineffective, while an unrealistically tiny hot set may make it look too effective.

Ramp through several load levels and hold each level long enough to see whether queues stabilize. At each level, compare offered rate, completed rate, error rate, tail latency and resource saturation. If offered rate keeps rising while completed rate flattens and queue age increases, the system has passed its useful capacity under that workload. Repeat a targeted failure scenario, such as one instance removed, a replica delayed or a cache unavailable. The result should state both the highest passing load and the failure mode at the next level, because a single “maximum requests per second” number hides the boundary that matters.

Change one bottleneck at a time and repeat the measurement. A service might first need a larger instance, then more stateless instances, then read relief, and only later write partitioning. The order is conditional on measured limits. Define a trigger before each step, such as a rising database write latency at a known write rate, and verify that the change improves the end-to-end target rather than merely moving saturation elsewhere.

A capacity plan should be revisited as the workload changes. A new feature can replace cheap reads with expensive searches even if total request count stays constant. Growth in retained data can enlarge indexes and change query costs. A promotional event can change key popularity and defeat a previously balanced partition scheme. Record the assumptions next to every estimate and compare them with production measurements after deployment. Update the plan when a material assumption changes, then prioritize the smallest measured change that restores the required target with enough recovery headroom.

When comparing two designs, hold the workload and target constant. A test at a lower success rate, with warmer caches or with smaller response bodies is not evidence that the new design has more capacity. Compare completed operations at the same error and latency limits, and inspect the new bottleneck. A change may legitimately improve one dimension while worsening another: more read replicas may reduce primary read pressure but consume network and increase the possibility of stale reads. Reporting the dimensions together makes the tradeoff visible and tells the next test what to challenge.

Capacity forecasts should express uncertainty rather than hide it in one precise number. If peak traffic could plausibly be four to eight times the daily average, calculate both cases and identify which components cross their tested limits in each. The lower case can guide ordinary provisioning; the upper case can guide the overload response and the amount of standing reserve. Revisit the range when actual traffic arrives. A measured peak factor from last year may no longer fit a new product feature, a larger customer or a different geographic distribution. The purpose of the forecast is to expose the decision boundary, not to make an uncertain future look exact.

· · Review

Common mistakes

Each mistake pairs an appealing but incomplete scaling decision with the mechanism that makes it fail and a more reliable way to decide.

  1. Treating average daily traffic as the peak

    Why it fails
    Dividing by 86,400 s gives a precise-looking number, but traffic arrives unevenly, so the busiest hour exceeds it.
    Fix
    Apply an observed or explicitly assumed peak factor, and load-test bursts at the rate the system must admit (§2).
  2. Adding API instances when the database is saturated

    Why it fails
    More instances accept more requests and open more database connections, which worsens the shared limit.
    Fix
    Find the resource with rising latency or rejections, then scale, reduce or isolate that work (§3).
  3. Treating a cache or replica as free read capacity

    Why it fails
    Every cache miss still reaches the backing store, and a replica can lag behind accepted writes.
    Fix
    Measure hit ratio and size for a miss storm; route consistency-sensitive reads to the primary or an equivalent path (§4).
  4. Choosing a partition key from record counts alone

    Why it fails
    One popular key can send several times average traffic to one shard while storage looks balanced.
    Fix
    Size from requests and bytes per key and partition, then split or isolate the hot work (§5).
  5. Using an unbounded queue as the overload plan

    Why it fails
    When arrivals exceed consumer capacity, backlog and waiting time grow without limit, even with plentiful storage.
    Fix
    Bound admission, define the response at the limit, and size recovery from the net drain rate (§6).

· · Exercises

Practice questions

These questions mix recall, calculation and application across the whole guide; each answer is collapsed beneath its question to be opened once the reader has worked out an answer.

Question 1 (distinction)

How do vertical scaling, horizontal scaling, replication and partitioning differ in the resource they add or the work they distribute?

Answer

Vertical scaling enlarges one machine. Horizontal scaling adds machines to share work. Replication places copies of the same data on nodes, usually adding read paths and resilience while still sending writes to the relevant leader. Partitioning assigns different records to different owners, allowing write load and storage to be divided if keys are balanced.

Question 2 (calculation)

A service receives 10 million requests per day. Assume peak traffic is six times the daily average and average response time at peak is 150 ms. Estimate peak requests per second and average in-flight requests.

Answer

Average rate is 10,000,000 ÷ 86,400 ≈ 115.74/s. Peak rate is 115.74 × 6 ≈ 694.44/s. Convert 150 ms to 0.15 s; Little's law gives 694.44/s × 0.15 s ≈ 104.17, so about 104 requests are in flight on average at peak. A check using unrounded values gives 10,000,000 × 6 × 0.15 ÷ 86,400 ≈ 104.17.

Question 3 (calculation)

A database receives 12,000 reads per second. What load reaches it with a cache hit ratio of 75%, and what is the multiplier if every request misses?

Answer

Misses are 12,000 × (1 − 0.75) = 3,000/s; hits are 12,000 × 0.75 = 9,000/s. Check: 9,000 + 3,000 = 12,000/s. All misses send 12,000/s, which is 12,000 ÷ 3,000 = 4 times the normal database read rate.

Question 4 (application)

A read replica has spare CPU, but checkout sometimes reads an order immediately after creating it and reports that the order does not exist. Explain the mechanism and propose a routing change.

Answer

The replica receives writes after the primary, so replica lag can make the new order temporarily invisible. Route the immediate read to the primary, or use a read mechanism that waits for the relevant replication position. Keep eventually consistent browsing reads on replicas if their staleness contract permits it.

Question 5 (open-ended)

An online shop's promotion triples traffic. Product pages slow down, checkout writes remain correct but queue, one popular seller accounts for 30% of new orders, and email jobs accumulate. Describe the measurements, capacity changes and overload controls needed across these paths.

Answer

Measure peak reads and writes separately, latency by endpoint, cache hit ratio and miss rate, database read and write saturation, traffic by seller key, and email arrival, completion and oldest-job age. Product pages may benefit from an edge or application cache for repeated content, with the origin protected when it misses. Increase interchangeable API capacity only if that tier is saturated, and check the database connection budget after doing so. Keep checkout's correctness path on the authoritative writer; reduce its write cost or partition by a key that does not put the seller's 30% on one shard. If seller ownership requires one partition, isolate that seller or split independently safe work and state the ordering cost. Size email workers from the provider's real completion rate, bound the queue and slow or reject admissions before it grows without limit. Load-test the promotion and one-instance failure at the proposed peak, then confirm the end-to-end targets.

Question 6 (calculation)

A queue receives 1,500 jobs per second for four minutes while its workers complete 1,200 jobs per second. After the burst, arrivals fall to 900 jobs per second. Assuming the stated rates remain constant and no work is rejected, how large is the backlog and how long does it take to clear?

Answer

During the burst, backlog grows at 1,500 − 1,200 = 300 jobs/s. Four minutes is 4 × 60 = 240 s, so the backlog reaches 300 × 240 = 72,000 jobs. Check by totals: 1,500 × 240 = 360,000 jobs arrive and 1,200 × 240 = 288,000 finish, leaving 72,000. Afterward the queue drains at 1,200 − 900 = 300 jobs/s. Clearing takes 72,000 ÷ 300 = 240 s, or four minutes. The result assumes constant completion capacity throughout and says nothing about whether the oldest job's waiting time meets its target.

· · Finish

Review checklist

Define scalability against a stated workload, correctness condition and performance target. Calculate average and peak rates, storage growth, concurrency, failure headroom and queue growth with units and explicit assumptions. Distinguish scaling a stateless service from scaling a shared database, and check connection budgets when instance counts change. Explain when caching and read replicas reduce read pressure, what happens on misses and stale reads, and how cache lifetimes affect freshness. Choose between replication and partitioning, identify a hot key, and calculate its shard's load. Set a bounded overload response, make queued work safe to retry, and estimate backlog recovery time. Use representative measurements and load tests to identify the next bottleneck and confirm that a change improves completed work at the same target. A reader who can do all of these has covered the material.