SD·124
Scaling
How systems grow: scalability defined (and Amdahl's and the Universal Scalability Laws), vertical versus horizontal scaling, stateless services and where state goes, autoscaling, replication for reads, partitioning and sharding strategies (range, hash, consistent hashing, directory, geographic) with hot spots, resharding and cross-shard queries, caching as a scaling tool, batching, asynchronous processing and back-pressure, data locality, and a staged scaling journey from one server to a global system.
Start here: adding machines, and when it stops helping
Scaling means handling more load by adding resources. Vertical scaling buys a bigger machine; it's simple and has a ceiling. Horizontal scaling adds more machines; it has a much higher ceiling but only works for the parts of the system that can be split. This chapter is about knowing which parts those are.
Stateless services scale almost perfectly
Copies of the kitchen service (each with a capacity of 200 orders per second) behind HAProxy, each pushed to its limit:
servers throughput avg latency speed-up
1 192.7/s 82.6 ms 1.00×
2 380.2/s 83.7 ms 1.97×
4 755.9/s 84.1 ms 3.92×
Doubling the servers doubled the throughput, because the copies shared nothing: any request could go to any server. That is why designs push state out of application servers (into databases, caches and queues) and keep the servers themselves stateless.
Shared resources put a ceiling on it
A Go program modelled a request as 9 ms of independent work followed by 1 ms holding a shared lock (a hot database row, a global counter, a single-threaded component), with N requests running at once:
N serial part only (Amdahl) + cost of coordinating with everyone (USL)
1 94/s 96/s
2 186/s 186/s
4 356/s 360/s
8 724/s 598/s
16 810/s 470/s
32 853/s 450/s
64 843/s 350/s
With just a serial part, throughput rose almost linearly at first and then flattened near 1 ÷ 1 ms ≈ 1,000 per second, however much concurrency was added: that is Amdahl's law. When the shared step also got slower as more workers took part (each must coordinate with all the others, like cache-coherence traffic or a distributed lock), throughput peaked at 8 and then fell: adding capacity made the system slower. The Universal Scalability Law describes exactly that curve. Find the shared step before you buy more machines.
Splitting data: which key goes where?
To scale a database horizontally you partition (shard) the data, for example by customer ID, across several machines. The simplest rule, hash(key) mod N, has a nasty property when N changes. 100,000 customer keys, going from 4 database nodes to 5:
hash mod N: 80.1% of keys moved
consistent hashing, 1 vnode/node: 38.2% moved, busiest node 1.91× average load
consistent hashing, 10 vnodes: 17.0% moved, busiest node 1.35×
consistent hashing, 100 vnodes: 19.7% moved, busiest node 1.06×
ideal: 20% (just the new node's fair share)
With mod N, adding one node reshuffled four keys in five, which would mean moving most of the data (or emptying most of a cache) at once. Consistent hashing places nodes on a ring, so a new node takes keys only from its neighbours; with enough virtual nodes per machine, it moves almost exactly the ideal 20% and spreads load evenly.
How deep to go in scaling
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Distinguish vertical and horizontal scaling and explain why statelessness matters |
| L2 | Scale a stateless service horizontally with a load balancer and autoscaling |
| L3 | Explain Amdahl's law, the USL, partitioning strategies, consistent hashing and hot keys |
| L4 | Find what limits a system's scaling from measurements, and fix hot spots |
| L5 | Design a system's scaling path: what scales out, what partitions, what stays single, and when to change |
| L6 | Plan capacity and scaling across a large fleet and organisation |
What scalability means
A system is scalable if it can handle increased load (traffic, data, users, tenants) by adding resources, with acceptable cost and without redesign. Two related ideas:
- Scalability: the curve of throughput (or capacity) as resources increase. Ideal is linear: double the machines, double the throughput.
- Elasticity: how quickly and automatically capacity follows demand up and down.
Load has several dimensions, and a system can scale well on one and badly on another: requests per second, read/write ratio, data volume, number of concurrent connections, fan-out (followers per user), number of tenants, size of individual items (a 5 GB video vs a 1 KB message).
Why scaling is sub-linear
Amdahl's law: if a fraction s of the work is serial (can't be parallelised), the maximum speedup with N processors is 1 / (s + (1 − s)/N). With 5% serial work, the speedup can never exceed 20×, however many machines you add.
Gunther's Universal Scalability Law adds coherency cost: the work of keeping nodes consistent with each other (locks, cache invalidation, consensus, cross-shard coordination) grows with N², so throughput can actually decrease past some point:
C(N) = N / (1 + α(N − 1) + βN(N − 1)), where α is contention and β is coherency.
The practical lesson: scalable designs minimise shared mutable state and coordination. Independent shards, stateless services, asynchronous communication and data partitioned so most operations touch one partition all keep α and β small.
Vertical scaling
Scaling up: a bigger machine (more CPU cores, memory, faster disks, more network bandwidth).
| Pros | Cons |
|---|---|
| No code changes, no distributed-systems complexity | Hard ceiling (largest instance available) |
| Strong consistency and transactions stay simple | Cost grows faster than linearly at the top end |
| Excellent for databases: today's largest cloud instances have hundreds of vCPUs and multiple TB of RAM | Single point of failure unless paired with replicas |
| Fewer moving parts to operate | Resizing often requires a restart/failover |
Don't underestimate vertical scaling: a single well-tuned PostgreSQL primary on modern hardware handles tens of thousands of transactions per second and many terabytes, which covers most companies' needs for years. "Scale up first, scale out when you must" is often the most cost-effective path, especially for the stateful tier.
Horizontal scaling
Scaling out: more machines sharing the load.
| Pros | Cons |
|---|---|
| Near-unlimited capacity in principle | Requires stateless design or partitioned state |
| Redundancy: losing one node loses a fraction of capacity | Distributed-systems problems: consistency, coordination, partial failure |
| Commodity hardware, incremental growth, elasticity | More operational complexity (deploys, monitoring, networking) |
Stateless tiers scale out easily; stateful tiers (databases, caches, queues) scale out via replication (more copies for reads) and partitioning (split the data so each node owns a part).
Stateless services
A service is stateless when any instance can handle any request because no request depends on data stored in a particular instance's memory or disk. To make services stateless, move state out:
| State | Where it goes |
|---|---|
| User sessions | Signed tokens (JWT/encrypted cookies) or a shared session store (Redis, database) |
| Uploaded files, generated artefacts | Object storage |
| Caches | Optional local cache (safe to lose) + shared distributed cache |
| In-progress workflows | Database, durable workflow engine, or messages in a queue |
| Scheduled timers | A scheduler service or durable timers, not setTimeout in a process |
| WebSocket connections | Inherently stateful: a connection gateway layer with a routing directory (chapter 132) |
Benefits: horizontal scaling, rolling deploys and autoscaling without user-visible effects, trivial failure recovery (restart anywhere), simpler load balancing (no sticky sessions).
// Stateless handler: identity from a verified token, data from shared stores; nothing kept in process memory
func (h *Handler) GetCart(w http.ResponseWriter, r *http.Request) {
p := auth.PrincipalFrom(r.Context()) // from the validated JWT
cart, err := h.carts.Get(r.Context(), p.UserID) // Redis/DB, shared by all instances
if err != nil { http.Error(w, "unavailable", http.StatusServiceUnavailable); return }
writeJSON(w, cart)
}
Autoscaling
Autoscaling adds and removes capacity automatically:
- Horizontal Pod Autoscaler (HPA) in Kubernetes on CPU/memory or custom metrics (requests per second, queue length); KEDA scales on event sources (Kafka lag, SQS depth, cron) including to zero; cluster autoscalers (Karpenter, Cluster Autoscaler) add nodes when pods are pending (Vol. 6 ch. 83).
- Cloud: auto scaling groups, managed instance groups, serverless platforms that scale per request (Lambda, Cloud Run).
- Choose the right signal: CPU works for CPU-bound services; for I/O-bound services use concurrency/RPS per instance or latency; for consumers, use queue depth/lag (or better, estimated time to drain).
- Lead time matters: if new instances take 3 minutes to start and warm up, autoscaling can't save you from a spike that saturates you in 30 seconds. Keep headroom, use scheduled scaling for predictable peaks (8 pm dinner rush, Monday 9 am), reduce startup time (smaller images, AppCDS/CRaC/native images for JVM), and combine with load shedding (chapter 130).
- Scale-in carefully: drain connections, protect instances doing long jobs, avoid flapping (stabilisation windows).
# KEDA: scale order-workers on Kafka consumer lag, 0–50 replicas
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: order-workers }
spec:
scaleTargetRef: { name: order-workers }
minReplicaCount: 0
maxReplicaCount: 50
triggers:
- type: kafka
metadata:
bootstrapServers: kafka:9092
consumerGroup: order-workers
topic: orders
lagThreshold: "1000" # target lag per replica
Note: consumer replicas beyond the number of partitions sit idle in a classic Kafka consumer group (share groups relax this).
Replication for scale
Replication keeps copies of the same data on multiple nodes (Vol. 5 ch. 71):
- Read scaling: route reads to replicas, writes to the primary (leader). Works well for read-heavy workloads.
- Replication lag: asynchronous replicas may serve stale data, causing anomalies such as a user not seeing their own update. Mitigations: read-your-writes routing (read from the primary for a short time after a user writes, or until the replica has caught up to the write's position), monotonic reads (stick a user to one replica), consistent prefix reads.
- Writes don't scale with read replicas; every replica must apply every write.
- Also provides availability (failover) and locality (replicas in other regions), covered in chapters 125 and 134.
Partitioning and sharding
When data or write load exceeds one node, split the data into partitions (also called shards, regions, tablets, vnodes), each owned by one node (plus its replicas). Partitioning is the general concept (including partitioning a table within one database, e.g. PostgreSQL declarative partitioning by month); sharding usually means distributing partitions across separate database servers.
Choosing a partition key
The partition key determines which operations are cheap (single-partition) and which are expensive (scatter-gather across all partitions):
- Partition by the key most queries filter on:
tenant_idfor SaaS,user_idfor user-centric data,conversation_idfor chat messages,device_idfor IoT telemetry. - Ensure high cardinality and even distribution of both data and traffic.
- Keep things that must be transactionally consistent together on one partition (an order and its items share
order_id/customer_id).
Strategies
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Range | Contiguous key ranges per partition (A–F, G–M…; or by time) | Efficient range scans; easy to split hot ranges | Hot spots with sequential keys (timestamps, auto-increment IDs: all writes hit the last partition) |
| Hash | hash(key) mod N |
Even distribution | Range queries scatter; changing N remaps almost everything |
| Consistent hashing | Keys and nodes on a hash ring; key goes to the next node clockwise; virtual nodes for balance | Adding/removing a node moves only ~1/N of keys | Range queries still scatter; needs a ring membership mechanism |
| Fixed many partitions | Create far more partitions than nodes (e.g. 1,024); assign partitions to nodes; move whole partitions when rebalancing | Simple rebalancing without rehashing keys (Elasticsearch shards, Kafka partitions, Cassandra vnodes, Couchbase vBuckets) | Partition count chosen up front (some systems allow splitting) |
| Directory / lookup | A mapping service records which shard holds each key or tenant | Maximum flexibility (move a big tenant to its own shard) | Directory is an extra dependency to cache and keep highly available |
| Geographic | Partition by region/country | Data residency, locality | Uneven sizes; cross-region users |
# Consistent hashing with virtual nodes (illustrative)
import bisect, hashlib
class Ring:
def __init__(self, nodes, vnodes=128):
self.ring = sorted((self._h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes))
self.keys = [h for h, _ in self.ring]
@staticmethod
def _h(s: str) -> int:
return int.from_bytes(hashlib.blake2b(s.encode(), digest_size=8).digest(), "big")
def node_for(self, key: str) -> str:
i = bisect.bisect(self.keys, self._h(key)) % len(self.ring) # next point clockwise
return self.ring[i][1]
ring = Ring(["db-a", "db-b", "db-c"])
ring.node_for("user:42") # → e.g. "db-b"; adding "db-d" moves only ~1/4 of keys
Variants: rendezvous (highest random weight) hashing (each key picks the node with the highest hash(key, node)), jump consistent hash (fast, for numbered buckets), Maglev hashing (lookup tables for load balancers).
Hot spots and skew
Even with good hashing, traffic can concentrate: a celebrity user, a viral product, a huge tenant, "today's" time partition.
Mitigations:
- Key salting / splitting: append a suffix (
product:123#0..9) to spread a hot key over 10 partitions; reads gather from all splits (good for write-heavy counters). - Caching hot reads (chapter 126 covers hot-key caching).
- Dedicated shards for very large tenants (directory-based placement, chapter 133).
- Write buffering/aggregation: accumulate increments in memory and flush periodically.
- Avoid monotonically increasing keys as range-partition keys (use hashed prefixes, UUIDv7 is time-ordered and therefore hot for range-partitioned stores, while random UUIDv4 spreads writes but hurts B-tree locality: choose per store).
- Adaptive splitting: systems like DynamoDB, Bigtable, Spanner and CockroachDB split hot ranges automatically, within limits.
Rebalancing and resharding
Adding capacity means moving data:
- Systems with many fixed partitions or automatic range splitting rebalance online (Cassandra, DynamoDB, CockroachDB, Vitess with resharding workflows, Citus shard rebalancer).
- Application-level sharding requires a migration plan: double-writing or CDC-based copying to new shards, backfill, verification, switching reads, switching writes, cleanup, often driven by the shard directory. Plan for it from day one: use a shard ID layer of indirection (logical shards mapped to physical databases) so you can move logical shards without re-hashing keys.
- Rebalance gradually (throttled) to avoid overloading the cluster you're trying to relieve.
Cross-partition operations
Sharding makes some things hard:
- Queries without the partition key become scatter-gather (query all shards, merge): latency set by the slowest shard and load multiplied by shard count. Solve with secondary indexes (local per shard vs global, chapter 127), denormalised copies keyed differently, or a search engine/analytics store fed by CDC.
- Cross-shard transactions need distributed transactions (2PC) or sagas (Vol. 5 ch. 73); design keys so most transactions stay within one shard.
- Joins across shards: denormalise, or do them in an analytical store.
- Global uniqueness (usernames, emails): a dedicated uniqueness table/service partitioned by that value, or conditional writes.
- IDs: generate globally unique IDs without coordination: UUIDv7, Snowflake-style IDs (timestamp + machine ID + sequence), ULIDs.
Distributed SQL databases (Spanner, CockroachDB, YugabyteDB, TiDB, Aurora DSQL) and sharding layers (Vitess for MySQL, Citus for PostgreSQL) automate much of this, at the cost of their own complexity and latency for cross-partition work.
Caching as a scaling tool
Caching is often the cheapest scaling lever for read-heavy systems: a 99% hit ratio means the database sees 1% of reads. It also introduces staleness and invalidation problems. Layer caches: browser and CDN for public content, in-process caches for very hot small data, distributed caches for shared data. Chapter 126 covers it fully.
Batching
Many systems are limited by per-operation overhead (round trips, syscalls, fsyncs, transaction commits, HTTP request setup) rather than raw work. Batching amortises that overhead:
- Database: multi-row inserts,
COPY, batched updates,UNNESTarrays; group commit. - Network: pipelining (Redis), HTTP/2 multiplexing, batch APIs (
POST /events:batch), DataLoader-style request coalescing in GraphQL. - Messaging: producer batching (
linger.ms,batch.sizein Kafka), consumer batch processing. - Disk: write-ahead logs flush once for many commits.
Trade-off: latency vs throughput. Waiting to fill a batch adds delay; use size and time limits (flush when 500 items or 10 ms, whichever comes first).
// Go: micro-batcher with size and time limits
type Batcher[T any] struct {
in chan T
flush func([]T) error
}
func (b *Batcher[T]) Run(ctx context.Context, maxSize int, maxWait time.Duration) {
batch := make([]T, 0, maxSize)
timer := time.NewTimer(maxWait)
defer timer.Stop()
send := func() {
if len(batch) > 0 {
if err := b.flush(batch); err != nil { log.Printf("flush: %v", err) } // retry/DLQ in real code
batch = make([]T, 0, maxSize)
}
timer.Reset(maxWait)
}
for {
select {
case <-ctx.Done():
send(); return
case item := <-b.in:
batch = append(batch, item)
if len(batch) >= maxSize { send() }
case <-timer.C:
send()
}
}
}
// Java (JDBC): batch inserts — one round trip per 500 rows instead of per row
try (var ps = conn.prepareStatement("INSERT INTO clicks(link_id, ts, country) VALUES (?, ?, ?)")) {
int n = 0;
for (Click c : clicks) {
ps.setLong(1, c.linkId()); ps.setObject(2, c.ts()); ps.setString(3, c.country());
ps.addBatch();
if (++n % 500 == 0) ps.executeBatch();
}
ps.executeBatch();
}
// With PostgreSQL JDBC, reWriteBatchedInserts=true turns batches into multi-row INSERTs
# Python: PostgreSQL COPY for bulk loads (psycopg 3) — orders of magnitude faster than row inserts
with conn.cursor() as cur, cur.copy("COPY clicks (link_id, ts, country) FROM STDIN") as copy:
for c in clicks:
copy.write_row((c.link_id, c.ts, c.country))
Asynchronous processing
Move work that doesn't need to finish before responding out of the request path:
- The request handler validates, records intent durably (database row and/or message), and responds quickly (
202 Acceptedwith a status URL, or a synchronous result for the critical part only). - Workers do the rest (sending email, generating thumbnails, updating search, calling slow partners) at their own pace, with retries.
Benefits: lower and more predictable latency, load leveling (spikes become queue backlog rather than errors), independent scaling, isolation from slow dependencies. Costs: eventual consistency visible to users ("your report is being generated"), more moving parts, need for idempotency, monitoring of queue age and DLQs.
Back-pressure
Asynchrony without limits just moves the problem: an unbounded queue grows until memory or disk runs out, and latency (queue age) grows without bound. Back-pressure propagates "slow down" signals upstream:
- Bounded queues and buffers: when full, block the producer, drop, or reject (HTTP 429/503).
- Flow control built into protocols: TCP windows, HTTP/2 stream flow control, gRPC, Reactive Streams (
request(n)in Project Reactor/RxJava), Kafka consumers pulling at their own pace. - Admission control at the edge (rate limits, concurrency limits, load shedding, chapter 130).
- Monitor queue age (oldest message) as well as depth; alert when work isn't draining.
Data locality
Moving computation to data is often cheaper than moving data to computation:
- Co-locate services with their databases (same AZ/region) to avoid cross-zone latency and transfer costs; place read replicas and caches near readers.
- Partition so related data lives together: an order with its items, a conversation with its messages; queries then hit one node.
- Push computation down: filter and aggregate in the database (SQL
WHERE/GROUP BY) rather than fetching everything; predicate pushdown in Parquet/Iceberg; stored procedures for tight loops (carefully). - Edge computing for latency-sensitive logic near users (CDN workers).
- Data gravity: large datasets attract the applications that use them; moving petabytes is slow and expensive, so plan where data will live.
A staged scaling journey
Scaling is incremental; each stage solves the bottleneck you actually have:
| Stage | Architecture | Typical trigger to move on |
|---|---|---|
| 1 | One server: app + database | CPU/memory saturation; no redundancy |
| 2 | Separate database server; app scaled vertically | App tier saturation; deploys cause downtime |
| 3 | Load balancer + multiple stateless app instances; managed DB with standby | Database read load |
| 4 | Caching layer + read replicas + CDN for static and media | Write load or data size on primary; slow background work in requests |
| 5 | Queues and workers for async work; search engine for queries the DB handles badly | Single database too large/hot for writes; team size and coupling |
| 6 | Partition data (functional split per service/domain, then sharding of the hottest data); event streaming between services | Global users, regional regulations, availability targets |
| 7 | Multi-region deployment, geo-routing, data residency (chapter 134) | — |
The order matters: each step adds complexity, so take it when measurements (not fashion) say the previous architecture is the bottleneck. Many successful products run for years at stage 3–4.
Lab: linear, sub-linear and retrograde scaling
On the lab machine (2 vCPUs): HAProxy 2.8 (balance leastconn) in front of 1, 2 or 4 copies of the Go kitchen service (4 slots × 20 ms each, so 200/s per copy) under k6 with 16 virtual users per server; a Go program modelling a shared lock; and a Python simulation of key placement.
Experiment 1: horizontal scaling of a stateless service
| Servers | VUs | Requests in 10 s | Throughput | avg | p95 | Efficiency |
|---|---|---|---|---|---|---|
| 1 | 16 | 1,940 | 192.7/s | 82.6 ms | 84.3 ms | 100% |
| 2 | 32 | 3,831 | 380.2/s | 83.7 ms | 85.7 ms | 98.6% |
| 4 | 64 | 7,612 | 755.9/s | 84.1 ms | 86.4 ms | 98.1% |
These services wait (sleep) rather than compute, so they scale even on a 2-core machine; CPU-bound copies on one host would hit the core count instead. That is the honest caveat of the experiment: it shows the architecture scaling linearly, not the hardware. In production the same table, measured across real machines, is how you find each instance's capacity for autoscaling targets.
Experiment 2: Amdahl and the Universal Scalability Law
time.Sleep(9 * time.Millisecond) // independent work
mu.Lock(); time.Sleep(1 * time.Millisecond) // serial part
if coherency { spin for N × 25 µs } // coordination that grows with N
mu.Unlock()
| N | Serial only | Serial + coherency | Bound: min(N × 94/s, 1 / 1.06 ms) |
|---|---|---|---|
| 1 | 94/s | 96/s | 94/s |
| 2 | 186/s | 186/s | 188/s |
| 4 | 356/s | 360/s | 376/s |
| 8 | 724/s | 598/s | 752/s |
| 16 | 810/s | 470/s | 943/s |
| 32 | 853/s | 450/s | 943/s |
| 64 | 843/s | 350/s | 943/s |
The bound comes from two simple limits: N workers can't do better than N times one worker's rate (94/s, a 10.6 ms cycle), and nothing can pass the lock faster than once per lock hold (about 1.06 ms with sleep overhead, so 943/s). The measured serial-only column hugs the first limit up to N = 8, then bends towards the second, reaching 90% of it: queueing at the lock eats the rest. In Amdahl's terms the serial fraction is σ ≈ 1/10 and the speed-up can never exceed 1/σ ≈ 10×; here it reached 9×. The USL adds a coherency term κ·N(N − 1) to the denominator; with κ > 0 the curve has a maximum at N* = √((1 − σ)/κ) and declines after it, as the second column did after N = 8. Fitting σ and κ to a few measured points (the usl R package or a short least-squares fit) predicts where adding nodes or threads stops paying, before you buy them.
Experiment 3: placing keys on nodes
100,000 keys, MD5-based hashing, 4 → 5 nodes:
| Scheme | Keys moved | Busiest node vs average (5 nodes) |
|---|---|---|
hash mod N |
80.1% | 1.01× |
| consistent hash, 1 vnode | 38.2% | 1.91× |
| consistent hash, 10 vnodes | 17.0% | 1.35× |
| consistent hash, 100 vnodes | 19.7% | 1.06× |
| consistent hash, 500 vnodes | 19.7% | 1.04× |
With 1 vnode per node the new node happened to land in a big arc and took 38% of keys, and one node ended up nearly twice as loaded as average; with 10 vnodes it took less than its share (17%) and balance was still poor. A hundred or so vnodes per node gets both close to ideal. Alternatives in production: rendezvous (highest-random-weight) hashing, which needs no ring; jump consistent hash, which needs no memory but only supports adding nodes at the end; and range partitioning with split/merge (as in Bigtable, CockroachDB and TiDB), which supports range scans and moves ranges explicitly rather than by hashing.
Experiment 4: hot keys, the limit no partitioning fixes
Partitioning spreads keys, not load per key. If one kitchen gets 30% of all orders, the node owning that kitchen gets at least 30% of the load whatever the scheme. Remedies: split the hot key (kitchen:7#0 … kitchen:7#9, aggregated on read), cache its reads, or route it to a dedicated partition.
Try it yourself
- Fit σ and κ to the USL column with
scipy.optimize.curve_fitand compare the predicted peak N* with the measured one. - Change the serial part to 0.1 ms and rerun. Where does the Amdahl column now level off?
- Implement rendezvous hashing in the Python script and compare keys moved and balance with 100-vnode consistent hashing.
- Add a Zipf-distributed workload to the key simulation and measure the busiest node's load with and without splitting the hottest key.
Revision sheet: scaling
Key ideas
- Scalability: throughput grows with resources while meeting latency targets.
- Vertical (bigger machine: simple, ceiling, failure domain) vs horizontal (more machines: needs statelessness or partitioning).
- Stateless services + shared stores scale out linearly; state goes to databases, caches, queues and object storage.
- Amdahl's law: speed-up ≤ 1/σ for serial fraction σ. USL adds coherency κ, giving a peak and retrograde scaling.
- Autoscaling on a metric that tracks saturation (CPU, concurrency, queue depth), with headroom and warm-up.
- Read scaling: replicas and caches. Write scaling: partitioning, batching, queues.
- Partitioning: range (scans, hot ranges), hash (even, no scans), directory/lookup (flexible, extra hop); consistent hashing, rendezvous, jump hash; rebalancing and split/merge.
- Hot keys defeat partitioning; split, cache or isolate them.
Numbers to remember
- Lab: 1 → 2 → 4 stateless servers gave 1.97× and 3.92×.
- Lab: 1 ms serial in a 10.6 ms request capped throughput near 850/s; with coherency it peaked at N=8 and fell to 350/s at 64.
- Lab: 4 → 5 nodes moved 80% of keys with mod N, ≈20% with consistent hashing at ≥100 vnodes.
Pitfalls
- Scaling out a service whose bottleneck is a shared database or lock.
- Sticky in-memory state on app servers.
hash mod Nfor anything that must survive resizing.- Too few vnodes (uneven load); ignoring hot keys.
- Autoscaling on a metric that lags or doesn't reflect saturation.
- Cross-partition queries and transactions everywhere after sharding.
Glossary
- σ (contention) / κ (coherency): USL parameters.
- Shard / partition: a subset of data on its own node.
- Virtual node: one of many ring positions per physical node.
- Rebalancing: moving partitions when nodes join or leave.
- Hot key / hot partition: one key or range getting a disproportionate share of load.