Summary#
Performance is how fast the system is for one request. Scalability is whether it stays fast as load grows when you add resources. A system with a performance problem is slow even for a single user. A system with a scalability problem is fast for one user and slow under heavy load.
Three words are often confused:
- Latency is how long one operation takes, for example 40 ms for a request.
- Throughput is how many operations complete per second, for example 5,000 requests per second.
- Bandwidth is the maximum data rate a link or device can carry, for example 10 Gbps.
Measure latency with percentiles (p50, p95, p99, p99.9), never just the average, because users feel the slow tail. Little's law (L = λ × W) links concurrency, throughput and latency. Queueing theory explains why latency explodes as utilisation approaches 100%, so run resources at 50-70%.
The biggest latency wins come from:
- doing less work on the critical path: caching, precomputation, indexes and approximation;
- moving work closer to the user: CDNs, edge and geo-sharding;
- not waiting: asynchronous processing and parallel calls;
- cutting round trips: connection reuse, batching and fewer chatty calls;
- moving fewer bytes: compression, smaller payloads and pagination.
The aim is maximum throughput at acceptable latency.
Why It Exists#
Almost every non-functional requirement is phrased in these terms: "p99 under 200 ms at 50,000 requests per second". Without clear definitions, teams talk past each other.
- One engineer says "it's fast" because the average is 20 ms, while 1% of users wait 3 seconds.
- Another adds servers to fix slowness that is really one slow database query, which adding servers never fixes.
- A third runs every server at 95% CPU to save money and is surprised when latency quadruples during a small traffic spike.
Speed also matters commercially. Google engineers reported in 2009 that deliberately adding 100-400 ms of delay to search results measurably reduced how much people searched, and the effect persisted after the delay was removed. Slow systems lose users quietly.
This page gives the vocabulary, the maths and the practical toolkit. It builds on Numbers Every Engineer Should Know.
How It Works#
Performance vs scalability#
A service is scalable if adding resources increases its capacity roughly in proportion. Twice the servers should give close to twice the throughput, or let it handle twice the data, at the same latency. Werner Vogels (Amazon's CTO) described it this way in his 2006 essay "A Word on Scalability". He also noted that a scalable system must stay operationally manageable and cost-effective as it grows, not just faster.
Performance is about the efficiency of one unit of work: how much CPU, memory, I/O and waiting a single request needs.
| Symptom | Likely problem | Typical fix |
|---|---|---|
| Slow even at 1 request per second | Performance (inefficient code, missing index, too many round trips) | Profile and optimise the critical path |
| Fast at low load, slow at high load | Scalability (a shared bottleneck: one DB, a lock, a hot key) | Remove the bottleneck, partition, replicate, cache |
| Throughput stops rising when servers are added | Contention / coherency (shared state, coordination) | Reduce shared state, partition, batch |
| Throughput falls as servers are added | Coherency cost dominates (cross-node chatter) | Fewer nodes or less coordination |
The two interact.
- Improving performance improves scalability: a request that needs half the CPU lets each server handle twice as many.
- Scaling out can hurt performance: a distributed design adds network hops, serialisation and coordination to each request.
Good designs make each request efficient first, then scale by adding independent units. See Scaling Up vs Scaling Out and the Universal Scalability Law in Scaling from Zero to Millions.
Latency vs throughput vs bandwidth#
Latency is the time from the start of an operation to its result. It is usually broken into parts:
- Propagation delay: the signal travelling the distance. Light in fibre covers roughly 200 km per millisecond, so 1,000 km costs about 5 ms one way.
- Transmission (serialisation) delay: pushing the bits onto the link, which is size divided by bandwidth. 1 MB at 1 Gbps takes about 8 ms; at 10 Gbps, about 0.8 ms.
- Processing delay: CPU work, such as parsing, business logic and encryption.
- Queueing delay: waiting behind other work, in a run queue, a connection pool, a disk queue or a router buffer. Under load this is often the biggest part, and it is the part that grows without bound.
Throughput is completed work per unit of time: requests per second, messages per second, MB/s. Goodput is the useful part of throughput; retries, duplicates and protocol overhead count toward throughput but not goodput.
Bandwidth is the capacity of a link or device, the ceiling on throughput. A 10 Gbps NIC has 10 Gbps of bandwidth, but if requests are small and sequential, the throughput might be a tiny fraction of that, limited by latency instead.
The relationship:
- For one sequential client, throughput ≈ 1 / latency. A client that makes one 10 ms call at a time can do at most 100 calls per second.
- With concurrency N, throughput ≈ N / latency, up to the bandwidth or capacity limit. This is Little's law, below.
- Bandwidth limits large transfers; latency limits small ones. Sending a 1 KB message across the Atlantic is dominated by the ~80 ms round trip; sending a 10 GB file is dominated by bandwidth.
Response time, service time and waiting time#
Three more terms keep measurements honest:
- Service time is how long the work takes once it starts, such as 5 ms of CPU and I/O for a query.
- Waiting time is how long it waits in queues before it starts.
- Response time is what the client sees: service time plus waiting time plus network time.
Under light load, response time ≈ service time. Under heavy load, waiting time dominates. So optimising code (service time) helps at all loads, while adding capacity mostly helps by cutting waiting time.
Percentiles and tail latency#
An average (mean) hides how bad the slow requests are. If 99 requests take 10 ms and one takes 2,000 ms, the mean is about 30 ms, which describes nobody's experience. Percentiles describe the distribution:
- p50 (median): half of requests are faster. The typical experience.
- p95 / p99: 95% or 99% of requests are faster. The slow but common experience.
- p99.9 / p99.99: the extreme tail, which matters at high volume. At 10,000 requests per second, p99.9 is still 10 slow requests every second.
- max: the worst seen. Noisy, but useful to catch pathological stalls.
Why the tail matters more than it seems:
- Heavy users hit it most. The customers with the most data or activity make the most requests, so they encounter the slow tail most often. They are frequently the most valuable.
- Page loads fan out. A page that makes 20 backend calls, each with a 1% chance of being slow, is slow for about 1 - 0.99^20 ≈ 18% of page loads.
- Tails come from many sources: garbage collection pauses, cache misses, queueing behind a slow request, lock contention, background compaction, noisy neighbours on shared hardware, TCP retransmits (often adding about 200 ms or more), and cold starts.
How to measure percentiles correctly:
- Record a histogram of latencies (HdrHistogram, Prometheus histograms, DDSketch, t-digest), not just averages.
- Never average percentiles across servers or time windows: the average of 10 servers' p99 values is not the fleet's p99. Merge histograms instead, then compute the percentile.
- Measure at the client or load balancer as well as the server; the server does not see time spent waiting in queues before it accepted the request.
- Beware coordinated omission: a load generator that waits for each response before sending the next request under-reports tail latency during stalls. Use tools that schedule requests at a fixed rate, such as wrk2.
SLOs are normally written on percentiles: "99% of requests complete within 300 ms over 30 days". See Non-Functional Requirements.
Little's law#
Little's law says that in any stable system, on average:
L = λ × W
- L is the average number of items in the system (concurrency, in-flight requests, queue length);
- λ (lambda) is the average arrival rate, which equals the throughput when the system is stable;
- W is the average time each item spends in the system (latency).
John Little proved it in 1961. Its power is that it holds for almost any system, whatever the arrival pattern or service order, as long as the averages are taken over a long enough period and the system is not growing without bound. Uses:
- Sizing concurrency. A service handles 2,000 requests per second with an average latency of 50 ms, so it has on average 2,000 × 0.05 = 100 requests in flight. If each in-flight request holds a thread, you need at least 100 threads, plus headroom for spikes and variance.
- Sizing connection pools. 3,000 queries per second at 4 ms each means about 12 connections busy at any moment. A pool of 20-30 per database is plenty; a pool of 500 only adds contention inside the database.
- Finding the throughput ceiling. If a client can keep at most 10 requests in flight and each takes 100 ms, its maximum throughput is 10 / 0.1 = 100 requests per second, no matter how powerful the server is.
- Explaining "slow means overloaded". If latency doubles while the arrival rate stays the same, in-flight work doubles. That pressure fills thread pools, memory and connection limits, which causes more slowness. This feedback loop is how small latency increases become outages.
- Queues and backlogs. If 500 messages per second arrive and each waits 4 seconds on average, about 2,000 messages are in the queue. See Message Queues.
Utilisation vs queueing delay#
Utilisation (ρ, rho) is the fraction of time a resource is busy: arrival rate × service time, or for c servers, divided by c. Queueing theory shows that waiting time grows non-linearly as utilisation approaches 1.
For the simplest model, a single server with random (Poisson) arrivals and random (exponential) service times, called M/M/1, the average time in the system is:
W = S / (1 − ρ), where S is the average service time.
| Utilisation ρ | Average response time (multiples of service time) | With S = 10 ms |
|---|---|---|
| 10% | 1.1x | 11 ms |
| 50% | 2x | 20 ms |
| 70% | 3.3x | 33 ms |
| 80% | 5x | 50 ms |
| 90% | 10x | 100 ms |
| 95% | 20x | 200 ms |
| 99% | 100x | 1,000 ms |
Practical lessons:
- The "knee" sits around 70-80% utilisation. Above it, small load increases cause large latency increases. Plan capacity so that normal peaks run at 50-70%, leaving room for spikes and for the loss of a server or zone.
- Variability makes it worse. Bursty arrivals and service times with long tails (some requests 100x slower than others) increase queueing at the same utilisation. Kingman's formula for a single-server queue with general distributions captures this: waiting time ≈ (ρ / (1 − ρ)) × ((Ca² + Cs²) / 2) × S. Here Ca and Cs are the coefficients of variation of inter-arrival and service times. Halving variability can matter as much as adding capacity.
- Pooling helps. One shared queue served by c servers (M/M/c) waits far less than c separate queues each with one server, at the same total utilisation. That is why load balancers that pick the least-loaded server, or "power of two random choices", beat random assignment. It is also why supermarkets with one snake queue feel faster.
- Utilisation is per resource. A server at 30% average CPU can have one disk at 95% or one lock held 90% of the time. Find the bottleneck resource; it alone determines the knee.
Amdahl's law: the limit of parallelism#
If a fraction p of a task can be parallelised and the rest (1 − p) is serial, then N workers give a speedup of at most 1 / ((1 − p) + p / N). Gene Amdahl stated this in 1967.
- With 95% parallel work, the maximum speedup is 20x, even with infinite workers.
- With 50% parallel work, it is only 2x.
For latency this means a request's response time can never drop below its serial critical path. If a page must call service A, then B with A's result, then C with B's result, parallelism cannot help those three steps. Only making each step faster, or redesigning the dependency so the steps no longer depend on each other, will.
The critical path and latency budgets#
The critical path is the longest chain of dependent steps in a request. Only work on the critical path determines latency; work off it (logging, analytics, notifications) affects throughput and cost but not response time, provided it is genuinely asynchronous.
A latency budget divides the SLO among the steps on the critical path:
p99 target: 300 ms for "load product page" (users mostly same-continent)
Network user <-> edge (TLS reused) : 40 ms
Edge/CDN + load balancer : 10 ms
API gateway (auth, rate limit) : 10 ms
Product service logic : 20 ms
Parallel fan-out (slowest branch):
price service ~30 ms | inventory ~40 ms | reviews (cached) ~10 ms
=> 40 ms
Render / serialise : 20 ms
Sum ~140 ms at typical latency; leave ~2x headroom for p99 effects.
Rule: any new synchronous dependency must fit inside the remaining budget.Note that percentiles do not add: the p99 of a sum is not the sum of p99s. Budgets based on typical values need generous headroom, and real p99 must be measured end to end.
Top ways to reduce latency#
Every latency technique does one of five things: do less, do it closer, do it earlier, do it in parallel, or do it without waiting.
- Cache. Serve repeated reads from memory: in-process (~100 ns), Redis/Memcached (~0.5-1 ms), instead of a database (~1-10 ms) or a computation (100s of ms). Cache the results of expensive aggregations and rendered fragments, not only rows. See Caching Fundamentals.
- CDN and edge. Static assets, images, video segments and cacheable API responses are served from a point of presence near the user. A 150 ms intercontinental round trip becomes 10-30 ms. TLS also terminates at the edge, so the expensive handshakes are short. See CDN.
- Move data and compute closer: geo-sharding and regional replicas. Store each region's data in that region, and route users to the nearest region. A ride-hailing service, for example, can shard location data and matching services by geographic area. Most queries stay in one region and one shard, and only searches near a shard boundary need a scatter-gather across two shards. Read replicas in each region serve local reads. This cuts both latency (shorter distance) and load per shard (higher throughput). See Multi-Region Data.
- Do it asynchronously. Anything the user does not need to see right now leaves the critical path: send the email, resize the image, update the search index, write analytics events via a queue. The request returns in milliseconds. See Message Queues.
- Parallelise independent calls. If a page needs data from four services that do not depend on each other, call them concurrently; latency becomes the slowest call, not the sum. Watch fan-out width, since tail probability grows with it.
- Reuse connections. A new TCP connection costs one round trip and TLS 1.3 adds another; across a continent that can be 150-300 ms before the first byte. Keep-alive, connection pools, HTTP/2 multiplexing, and TLS session resumption remove this cost. Inside a data center, pooled database connections avoid both handshake and authentication costs on every query.
- Compress. Text payloads (JSON, HTML) often shrink 70-90% with gzip, Brotli or zstd, which matters on slow mobile links. Compression costs CPU, so skip it for tiny payloads (under ~1 KB) and already-compressed media.
- Batch. Combine many small operations into one: multi-get from a cache, bulk inserts, batched producer sends in Kafka. Ten round trips of 1 ms become one round trip of ~1.2 ms. Batching trades a little latency per item for much higher throughput; for latency-sensitive paths, batch with a short time limit such as 5-10 ms (Nagle-style or linger settings).
- Precompute. Build results before they are requested: materialised views, feed fan-out on write, pre-rendered pages, search indexes, rollup tables. Reads then become simple lookups. The cost moves to write time and storage.
- Index and optimise queries. Most "slow database" problems are a missing or wrong index, or a query that scans too much. See the API section below.
- Approximate. If the product can accept a small error, approximate data structures replace huge exact ones (see the Deep Dive below).
- Choose efficient protocols and formats. Binary formats such as Protobuf parse faster and are smaller than JSON. HTTP/2 and HTTP/3 remove head-of-line blocking at different layers. gRPC streams avoid per-call setup. See Networking Fundamentals.
- Avoid the tail. Use hedged requests, timeouts with sensible limits, GC tuning, warm-up before taking traffic, and isolation of slow tenants.
Common ways to improve API performance#
APIs get slow for a small set of reasons. Check these in order, because most fixes are cheap:
- Fix N+1 queries. Loading a list of 50 orders and then making one query per order for its items is 51 queries. Use a join, an
IN (...)batch query, or a data loader that batches lookups within a request. - Add the right indexes and inspect the plan. Use
EXPLAIN/EXPLAIN ANALYZEto see whether a query scans the whole table. Index the columns used inWHERE,JOINandORDER BY, and use composite indexes that match the query's column order. Indexes speed up reads but cost storage and slow down every write, so add them for real query patterns, not speculatively. See Database Indexing. - Write efficient queries.
- Select only the columns you need instead of
SELECT *. - Use
LIMITand keyset pagination. - Avoid functions on indexed columns in
WHEREclauses. - Sometimes rewrite an
ORacross different columns as aUNIONof two indexed queries.
- Select only the columns you need instead of
- Use the right tool for text search.
WHERE name LIKE '%taylor%'cannot use a normal B-tree index because of the leading wildcard, so it scans every row. There are three levels of fix:- Database full-text indexes: PostgreSQL
tsvectorwith a GIN index, or MySQLFULLTEXT. These are fast for word matches with no new infrastructure. - Trigram indexes (PostgreSQL
pg_trgm) for substring and fuzzy matches. - A search engine (Elasticsearch, OpenSearch, built on Lucene's inverted index), which maps each term to the documents containing it. It supports relevance ranking, typo-tolerant fuzzy matching and facets at high query rates. It is kept in sync with the database via change data capture. The cost is another system to run and keep consistent.
- Database full-text indexes: PostgreSQL
- Paginate. Never return unbounded lists. Cursor (keyset) pagination (
WHERE id > last_seen ORDER BY id LIMIT 50) stays fast at any depth, whereasOFFSET 100000makes the database read and discard 100,000 rows. - Trim payloads. Return only the fields clients need, through sparse fieldsets, GraphQL selections or dedicated endpoints for mobile. A 300 KB JSON response that the app uses 10% of wastes bandwidth and parse time.
- Pool connections. Use database connection pools (HikariCP, PgBouncer) and HTTP client pools to downstream services.
- Cache at every sensible layer. HTTP caching headers (
Cache-Control,ETagfor conditional304 Not Modifiedresponses), CDN caching for public responses, and application caching for expensive reads. - Move slow work off the request path. Return
202 Acceptedwith a job ID for long operations, and do the work in background workers. - Log and trace asynchronously. Synchronous logging to disk or a remote collector on every request adds latency; buffer it.
- Compress responses, and support HTTP/2 or HTTP/3 at the edge.
- Protect performance with limits. Apply rate limits, timeouts, and request size limits, so one abusive client or one huge request cannot slow everyone else.
- Pre-aggregate for analytics. Dashboards over weeks of data should not scan raw events on each load. Maintain rollups such as per-minute and per-hour aggregates, downsample older data, and use a columnar or time-series store designed for range scans. Alerts that must fire within seconds are better evaluated by a stream processor as data arrives than by repeatedly polling a database.
Ways to raise throughput#
Throughput improvements overlap with latency ones but are not identical:
- Scale out stateless tiers: more app servers behind a load balancer. Throughput rises nearly linearly if there is no shared bottleneck.
- Partition stateful tiers: shard data so each node handles a fraction of writes. See Partitioning and Sharding.
- Replicate for reads: read replicas and caches multiply read capacity. See Replication.
- Batch and pipeline: amortise per-operation overhead, such as syscalls, round trips and fsyncs. Group commit in databases and batched sends in Kafka can raise throughput by 10x or more.
- Reduce contention: avoid hot rows and global locks; use sharded counters and optimistic concurrency.
- Use asynchronous I/O: event loops and non-blocking I/O let one server hold many in-flight requests without one thread each.
- Shed load gracefully: when overloaded, reject excess work quickly (HTTP 429/503) so the work you accept still completes. Throughput under overload should plateau, not collapse.
Where the time goes: one request, cold and warm#
Consider a user in Mumbai calling an API hosted only in US-East (Virginia). The round-trip time (RTT) between the two is roughly 190-200 ms, set mostly by the speed of light in fibre along a cable route of well over 13,000 km. On a cold connection, every protocol step costs at least one round trip before any useful bytes arrive:
| Step | Round trips | Approximate cost |
|---|---|---|
| DNS lookup (resolver cache miss) | 1+ to the resolver, which may recurse | 20-100 ms |
| TCP handshake (SYN, SYN-ACK) | 1 | ~195 ms |
| TLS 1.3 handshake | 1 (TLS 1.2 needed 2) | ~195 ms |
| HTTP request and first byte of response | 1, plus server time | ~195 ms + 30 ms |
| Rest of a 100 KB response (TCP slow start) | ~2 more | ~390 ms |
| Total | about 1.1 seconds |
The last row surprises people. A new TCP connection starts with a small congestion window, ten segments by default on modern Linux, or about 14.6 KB. The window roughly doubles each round trip while there is no loss: 14.6 KB, then 29 KB, then 58 KB. Delivering 100 KB therefore takes about three round trips of data (14.6 + 29 + 58 KB), even on a gigabit link. On a fresh connection, latency, not bandwidth, limits how fast a medium-sized response arrives.
The same request on a warm connection, reused through keep-alive or HTTP/2 with a congestion window that has already grown, needs a single round trip: about 225 ms.
Now terminate TLS at a CDN edge in Mumbai, 5 ms away, and keep a pool of warm, long-lived connections from the edge to the origin:
- The handshakes run over a 5 ms RTT, so they cost about 10 ms instead of 390.
- The edge-to-origin leg reuses an already-open connection with a large window, so it costs one origin RTT.
- The total is roughly 10 ms of handshakes plus about 200 ms for the origin leg plus server time: about 240 ms instead of 1.1 seconds, before any caching.
- If the response is cacheable at the edge, the origin leg disappears and the total is about 20 ms.
The lessons for design:
- Count round trips, not just milliseconds of CPU. On long paths, each protocol round trip dominates everything the server does.
- Keep connections warm and reuse them: keep-alive, HTTP/2 multiplexing, connection pools, TLS session resumption, and 0-RTT resumption in TLS 1.3 or QUIC (HTTP/3) for repeat visitors. 0-RTT data can be replayed by an attacker, so only allow it for idempotent requests.
- Terminate close to the user and let the provider's backbone carry the long leg.
- Make the first response small: fitting the critical part of a page into the first 14 KB lets it arrive in one round trip after the handshakes.
Bandwidth-delay product: why a fast link can still be slow#
The bandwidth-delay product (BDP) is the amount of data that must be "in flight", sent but not yet acknowledged, to keep a link full:
BDP = bandwidth × RTT
A 1 Gbps link with a 100 ms RTT has a BDP of 10⁹ bits/s × 0.1 s = 100 megabits, about 12.5 MB. TCP can only have one window of unacknowledged data in flight, so its throughput is at most window ÷ RTT:
- With the old 64 KB maximum window (before the window-scaling option), throughput is capped at 64 KB ÷ 0.1 s ≈ 5 Mbps, half a percent of the link.
- With window scaling and buffers sized to at least the BDP, throughput can approach the full gigabit.
This is why cross-region replication, backups and bulk copies often run far below the "bandwidth" you pay for. Fixes include larger socket buffers, several parallel streams, and congestion-control algorithms such as BBR (published by Google engineers in 2016), which estimates bottleneck bandwidth and RTT directly instead of reacting only to packet loss.
Packet loss caps throughput too. For classic loss-based TCP, the Mathis model (Mathis, Semke, Mahdavi and Ott, 1997) gives the steady-state limit:
throughput ≈ (MSS ÷ RTT) × (1.22 ÷ √loss rate)
With a 1,460-byte segment, a 100 ms RTT and 0.01% loss: (11,680 bits ÷ 0.1 s) × (1.22 ÷ 0.01) ≈ 14 Mbps, whatever the link speed. Halving the RTT doubles it. That is another reason why moving data closer to the user, or splitting a long path into shorter TCP legs through edge proxies, raises throughput and not only latency.
Batching: the dial between latency and throughput#
Batching works because most operations have a fixed cost per call (a round trip, a syscall, an fsync, a lock acquisition) plus a small cost per item. If the fixed overhead is o and each item costs c, a batch of n items gives:
- throughput = n ÷ (o + n × c) items per second;
- added latency per item of up to the time spent waiting for the batch to fill.
A worked example with database commits. A durable commit needs an fsync, which costs about 1 ms on a typical cloud SSD volume.
- One commit per fsync: at most about 1,000 commits per second, however fast the CPU is.
- Group commit, where the database flushes all transactions that arrived during the previous fsync together: with 50 transactions per flush, about 50,000 commits per second, and each commit waits at most about one extra fsync.
The same shape appears everywhere:
| Where | Batching knob | Typical trade |
|---|---|---|
| Kafka producer | batch.size (16 KB by default) and linger.ms | A few ms of linger for far fewer, larger requests and better compression |
| Database writes | Multi-row INSERT, COPY, group commit | One round trip and one fsync for hundreds of rows |
| Cache reads | MGET or pipelining | 100 keys in one round trip instead of 100 |
| TCP | Nagle's algorithm | Fewer small packets, but can add delay to interactive traffic |
| Disk and SSD | I/O queue depth | Higher IOPS at slightly higher per-I/O latency |
Two cautions:
- Nagle plus delayed ACKs. Nagle's algorithm holds back a small write until earlier data is acknowledged, and the receiver's delayed-ACK timer (often 40 ms on Linux) may hold the acknowledgement. Together they can add tens of milliseconds to request-response protocols. Latency-sensitive clients set
TCP_NODELAYand batch in the application instead. - Batch with a deadline, not just a size. "Send when 500 items or 10 ms, whichever comes first" bounds the latency cost under light load, when a size-only batch might wait seconds to fill.
Throughput limits of common components#
Rough single-node limits help you decide early whether one box is enough or partitioning is needed. They vary a lot with hardware, payload size and configuration, so treat them as orders of magnitude and confirm with benchmarks.
| Component | Rough capacity per node | What usually limits it |
|---|---|---|
| Stateless API server (Go, Java, Node) | 1,000-20,000 simple requests per second | CPU for serialisation, TLS, business logic |
| Nginx or Envoy as a proxy | Tens of thousands of requests per second per core | TLS handshakes, connection count |
| Redis (one instance, single-threaded command execution) | About 100,000 simple operations per second; more with pipelining | One CPU core, network round trips |
| PostgreSQL or MySQL, indexed point reads | 10,000-50,000+ queries per second on a large instance | CPU, buffer-cache hit ratio, connections |
| PostgreSQL or MySQL, durable writes | Thousands to tens of thousands per second | fsync latency, index maintenance, locks |
| Kafka broker | Hundreds of MB per second | Disk and network bandwidth |
| NVMe SSD, random 4 KB reads | Hundreds of thousands of IOPS | Queue depth, controller |
| Hard disk, random reads | About 100-200 IOPS | Seek time and rotation, around 5-10 ms each |
| 10 Gbps network interface | About 1.25 GB per second | Wire speed, packets per second for small packets |
Two habits follow:
- Find the per-node limit of the bottleneck, then divide. A design that needs 200,000 writes per second to PostgreSQL needs partitioning or a different write path. One that needs 2,000 does not.
- Use the limit at your target utilisation, not at 100%. A Redis node that can do 100,000 operations per second should be planned at about 50,000-70,000 to keep latency flat and leave failover headroom.
Case study: making event search fast#
A ticketing site's search illustrates almost every technique on this page. Users search events by keyword, date range and city. Traffic is read-heavy and spiky around big on-sales, and the requirement is p99 search latency under about 500 ms.
Step 1: stop scanning. The first version runs WHERE name LIKE '%taylor%' OR description LIKE '%taylor%'. The leading wildcard defeats a B-tree index, so every search scans every event row, and the OR across two columns makes it worse. Fixes, in order of effort:
- Index the columns used for filters and sorting (date, city, venue). Use
EXPLAINto confirm the plan, select only needed columns,LIMITthe result, and sometimes turn an OR across columns into a UNION of two indexed queries. - Add a full-text index in the database (PostgreSQL
tsvectorwith a GIN index, or MySQLFULLTEXT) for word matches. - Move to a search engine (Elasticsearch or OpenSearch) with an inverted index, relevance scoring and fuzzy matching, so "Tayler Swift" still finds "Taylor Swift". Keep it in sync with the database through change data capture, and accept that the index lags the source by a second or so.
Step 2: cache repeated queries. Search traffic is highly repetitive during an on-sale: thousands of users type the same artist's name.
- Build the cache key from every parameter that changes the result, normalised so equivalent queries share an entry: lowercase the keyword, sort the parameters, round date ranges to whole days. Without normalisation, "Taylor Swift" and "taylor swift" miss each other's entries and the hit rate falls.
- Set a TTL that matches how fast results change, from minutes for event lists down to seconds for anything showing availability.
- Invalidate using cache tags: tag each cached result with the IDs of the events it contains, and when an event changes, delete every entry with that tag. Pure TTL expiry cannot do this, because a query string says nothing about which events it returned.
- Use request coalescing so that a thousand simultaneous misses for the same key produce one backend query, not a thousand.
Step 3: use the engine's own caches. Elasticsearch caches filter results per shard (the node query cache) and can cache whole search responses per shard (the shard request cache), which is especially effective for aggregation-heavy queries such as facet counts.
Step 4: cache at the edge if results are not personalised. A public "events in Mumbai this weekend" response can be cached at a CDN for 30-60 seconds with Cache-Control: s-maxage, so a viral query is answered at the edge and never reaches the origin. Personalised results, such as "recommended for you", cannot be shared this way.
The cache-hit arithmetic shows why this works, and also where it stops working:
- With a 90% hit rate, a 2 ms cache and a 120 ms search engine, the mean latency is 0.9 × 2 + 0.1 × 120 ≈ 14 ms, and the engine sees only 10% of the traffic.
- The tail is set by the misses. If 10% of requests miss, the overall p99 is roughly the p90 of the miss path. The cache improves the median enormously but cannot fix a slow backend's tail. To improve p99 you still need a fast engine, or a hit rate above 99%.
- Cache failure is a load event. If the cache disappears, the engine suddenly receives 10 times its normal load. Size the engine for that, or protect it with rate limits, as described in Availability and Reliability.
Performance at scale: when bigger machines stop helping#
A ride-hailing service receives a constant stream of driver location updates and runs proximity searches ("available drivers within 2 km") on every ride request. Its options for more throughput and lower latency show the general pattern.
Vertical scaling (a bigger database server) is the quickest fix and the weakest long-term answer:
- it gets expensive quickly, because the largest machines cost disproportionately more;
- upgrades often need downtime or a failover;
- there is a hard ceiling, the biggest machine available;
- one machine is still one failure domain, and replicas only partly fix that.
Geo-sharding with read replicas fixes throughput and latency together:
- Partition by geography: each city or region has its own shard of location data, its own matching service and its own queues.
- Users and drivers talk to the nearby region, so the network distance shrinks as well as the load per shard.
- Read replicas in each region spread the heavy read traffic of proximity searches.
- Almost every query touches one shard. Only a search near a shard boundary needs a scatter-gather across neighbouring shards.
- The costs are operational: uneven shards (a big city versus a small town), rebalancing as demand moves, and replication within each shard for availability. Consistent hashing or a directory of geographic cells helps distribute and move the data.
Two other performance moves from the same problem:
- Keep the hot data in memory with the right structure. Driver positions change every few seconds and are only useful for minutes, so an in-memory geospatial index (for example Redis geospatial commands over geohashes) serves proximity queries in about a millisecond, where a disk-based database would struggle with the write rate.
- Reduce the work instead of only scaling it. Adapting how often drivers send location updates, more often when moving fast or near a pickup and less often when parked, can cut write throughput several-fold with no loss of matching quality.
See Partitioning and Sharding and Scaling Up vs Scaling Out.
A performance triage procedure#
When a system is "slow", the fastest route to a fix is a fixed sequence of questions, not intuition:
- Is it slow for everyone, or only under load? Run one request on an idle system. If it is slow, this is a performance problem: profile and trace it. If it is fast, it is a scalability or saturation problem: look at utilisation.
- Which part of the request is slow? A distributed trace shows the critical path. Look at the longest span and at gaps between spans, which are usually waiting time.
- Is the slow span waiting or working? CPU time close to wall-clock time means working: profile the code. Wall-clock time far above CPU time means waiting on I/O, locks, a pool or a queue.
- Which resource is saturated? Apply the USE method to each resource on the path: CPU, memory, disk, network, connection pools, thread pools and locks.
- Is it the median or the tail? A slow median points to the common path (a query, a missing cache). A slow tail with a fast median points to GC, contention, noisy neighbours, retries or one slow dependency.
When to Use It#
- Whenever you write or check a non-functional requirement: express it as percentile latency at a stated throughput.
- When a system is "slow": decide first whether it is a performance problem (slow at low load) or a scalability problem (slow under load).
- When sizing thread pools, connection pools, worker counts and queue lengths: use Little's law.
- When planning capacity: target 50-70% utilisation on the bottleneck resource.
- When adding a dependency to a request path: check that it fits the latency budget, and that the fan-out tail is acceptable.
When NOT to Use It#
- Do not chase microseconds on paths dominated by network or user think-time; optimise the biggest term first.
- Do not optimise without measurement: guesses about bottlenecks are usually wrong. Profile first.
- Do not over-provision to keep 10% utilisation everywhere "for latency"; that wastes money. Find the knee for the bottleneck resource instead.
- Do not apply single-queue formulas as precise predictions for complex systems; use them for intuition and confirm with load tests.
How to Implement It#
- Define targets as percentiles at a stated load: "p99 < 250 ms at 20,000 RPS, measured at the load balancer".
- Instrument every service with latency histograms, request rate, error rate and saturation. The RED method (Rate, Errors, Duration) applies to services; the USE method (Utilisation, Saturation, Errors, from Brendan Gregg) applies to resources.
- Trace requests end to end (OpenTelemetry) to see the critical path and the slowest spans.
- Profile hot services with CPU, allocation and lock profilers, and flame graphs.
- Load-test at and beyond expected peak with a constant-rate generator; find the knee where latency rises.
- Fix the biggest term first, re-measure, repeat.
- Set capacity alerts on the bottleneck resource well below the knee, and latency SLO alerts on burn rate.
# Example: Prometheus histogram-based p99 latency SLO check (illustrative)
- record: job:http_request_duration_seconds:p99_5m
expr: |
histogram_quantile(0.99,
sum by (le, job) (rate(http_request_duration_seconds_bucket[5m])))
- alert: HighP99Latency
expr: job:http_request_duration_seconds:p99_5m{job="checkout"} > 0.3
for: 10m
labels: { severity: page }| Technology | Fits when |
|---|---|
| OpenTelemetry + Jaeger / Tempo / Zipkin | Distributed tracing of the critical path |
| Prometheus histograms, HdrHistogram, DDSketch | Accurate percentile measurement and merging |
| k6, Gatling, Locust, wrk2 | Load tests (wrk2 for constant rate without coordinated omission) |
| async-profiler, perf, pprof, py-spy | CPU and allocation profiling, flame graphs |
| PgBouncer, HikariCP | Connection pooling |
| Elasticsearch / OpenSearch, PostgreSQL GIN full-text | Fast text search instead of LIKE '%x%' |
See Observability.
Trade-offs#
| Technique | Gain | Cost | Pick when |
|---|---|---|---|
| Caching | Large latency and load reduction | Staleness, invalidation complexity, memory cost | Read-heavy, repeated reads |
| CDN / edge | Removes long-haul round trips | Cache invalidation, cost per GB | Public, cacheable content; global users |
| Geo-sharding | Lower latency, more throughput | Cross-shard queries at boundaries, rebalancing complexity | Data naturally tied to location |
| Async processing | Fast responses, spike absorption | Eventual results, more infrastructure | Work the user need not wait for |
| Parallel fan-out | Latency = slowest branch, not sum | More load, tail amplification | Independent calls |
| Batching | Much higher throughput | A little added latency per item | High-volume small operations |
| Precomputation | Reads become lookups | Write amplification, storage, staleness | Read-heavy, predictable queries |
| Approximation | Huge memory and CPU savings | Bounded error in results | Trends, counts, top-K, distinct counts |
| Lower utilisation | Lower, more stable latency | Higher cost | Latency-critical paths |
| Compression | Fewer bytes on the wire | CPU on both ends | Text payloads over slow links |
| Edge TLS termination and warm origin pools | Removes handshake round trips on long paths | CDN cost, another hop to operate | Users far from the origin |
| Larger TCP windows, BBR | Fills long, fast links | Tuning effort, more memory per connection | Cross-region replication and bulk transfer |
| Hedged requests | Much shorter tail | A few percent extra load | Idempotent reads with wide fan-out |
| Vertical scaling | Quick, no code change | Cost grows steeply, hard ceiling, one failure domain | Early stages, a short-term fix |
| Partial results with a deadline | Bounded latency under stragglers | Less complete answers | Search, ranking, recommendations |
Common Pitfalls#
- Reporting averages instead of percentiles, or averaging percentiles across hosts.
- Load-testing with a closed-loop tool that hides tail latency (coordinated omission).
- Running the bottleneck resource above ~80% utilisation and being surprised by latency spikes.
- Adding servers to fix a slow query; the query is still slow on every server.
- Sequential calls to independent services, so their latencies add up.
- Huge connection pools that overload the database instead of protecting it.
- Unbounded result sets, deep
OFFSETpagination, andLIKE '%term%'scans. - Ignoring the tail of fan-out requests: the overall request waits for its slowest dependency.
- Optimising code off the critical path, which does not change response time.
- Ignoring round trips on long paths: new connections per request, TLS 1.2 handshakes, and TCP slow start on cold connections.
- Cache keys that are not normalised, so equivalent queries miss each other and the hit rate collapses.
- Assuming a cache fixes the tail; the misses still set p99, and losing the cache multiplies backend load.
- Bulk transfers across regions on default socket buffers, capped far below link bandwidth by the bandwidth-delay product.
- Prometheus summaries averaged across instances, or histogram buckets far from the SLO threshold.
Real-World Examples#
Dean and Barroso's "The Tail at Scale" (Communications of the ACM, 2013) describes how Google's large fan-out services suffer from rare per-server slowdowns. It introduced hedged and tied requests as practical tail-tolerance techniques.
Brendan Gregg's USE method, developed from performance work at Sun and later Netflix, is widely used to find bottleneck resources systematically: check utilisation, saturation and errors for every resource.
Count-Min Sketch, introduced by Graham Cormode and S. Muthukrishnan in 2005, is used in stream-processing systems to estimate item frequencies in a small fixed amount of memory. Redis supports it in its probabilistic data structures module.
Google's work on TCP has made the cost of round trips visible: it led the push to raise TCP's initial congestion window to ten segments (standardised as RFC 6928 in 2013), developed QUIC, which became HTTP/3, to cut handshake round trips, and published the BBR congestion-control algorithm in 2016.
Kafka's high throughput comes largely from designing around the machine: sequential appends to log files, reliance on the operating-system page cache, batching with compression in the producer, and zero-copy transfer from the page cache to consumer sockets.
A typical scenario: a product page took 800 ms because it called five services in sequence and issued an N+1 query for reviews. Parallelising the calls, batching the review query and caching reviews brought the p99 to about 150 ms with no new servers.
In the Interview#
Deep Dive: Queueing theory you can use without a PhDShow
Why the curve bends. In the M/M/1 model, the probability that an arriving request finds the server busy is ρ. Each waiting request ahead of you adds a full service time. As ρ → 1, the expected queue length ρ / (1 − ρ) grows without limit, because there is never enough idle time to drain bursts. Random arrivals always produce bursts, even when the average rate is below capacity.
Variability is the hidden enemy. Kingman's approximation, W_q ≈ (ρ / (1 − ρ)) × ((Ca² + Cs²) / 2) × S, separates three factors:
- utilisation, through ρ / (1 − ρ);
- variability, through the squared coefficients of variation of arrival gaps (Ca) and service times (Cs);
- the service time itself, S.
Some numbers:
- Perfectly regular arrivals and service (Ca = Cs = 0) give no waiting at all, even at 95% load.
- Random arrivals and exponential service (both coefficients 1) give the M/M/1 result.
- Very variable service times (Cs = 3, which is common when a few requests are 10-100x slower) give five times the M/M/1 wait at the same utilisation.
Practical moves that reduce variability:
- separate slow and fast request types into different pools, so fast requests never queue behind slow ones;
- cap request sizes;
- paginate;
- smooth bursty producers with token buckets.
Multiple servers and pooling. With c servers sharing one queue (M/M/c), a request waits only if all c are busy. At the same per-server utilisation, waiting drops sharply as c grows. That is why a pool of 64 workers can run at 85% utilisation with modest waits, while a single worker at 85% has long ones. The Erlang C formula, developed for telephone exchanges in the early twentieth century, gives the exact probability of waiting. The design lesson is to avoid partitioning a server pool into many small, separate queues unless isolation requires it.
Open vs closed systems. In an open system, new requests arrive regardless of how slow you are (internet users). In a closed system, a fixed number of clients wait for each response before sending the next (a batch job with 10 threads). Closed systems self-throttle as they slow down, so a closed-loop load test can make an open-world service look healthier than it is. Schroeder, Wierman and Harchol-Balter explored this in "Open Versus Closed: A Cautionary Tale" (NSDI 2006).
Overload and congestion collapse. When load exceeds capacity in an open system, queues grow without bound and every request's latency rises until clients time out. If clients retry, effective load rises further, a positive feedback loop. Remedies:
- bounded queues with fast rejection;
- deadlines propagated through calls, so servers drop work whose caller has already given up;
- retry budgets with exponential backoff and jitter;
- LIFO or adaptive LIFO under overload, so that the newest requests (whose callers are still waiting) get served first. Facebook described using adaptive LIFO and controlled delay (CoDel-style) queueing in "Fail at Scale" (ACM Queue, 2015).
Deep Dive: Tail-tolerance techniquesShow
You cannot remove every source of slowness, such as GC pauses, background compaction, network retransmits and noisy neighbours. So large systems are designed to tolerate the tail rather than eliminate it.
- Hedged requests: send the request to one replica; if no reply arrives within the p95 latency, send a second copy to another replica and use whichever answers first. Only about 5% of requests are duplicated, but the tail shrinks dramatically. Dean and Barroso reported a large reduction in tail latency for a modest increase in load in a Google benchmark.
- Tied requests: enqueue the request on two servers at once, each knowing about the other; when one starts executing, it tells the other to cancel. This avoids the hedging delay at small extra cost.
- Micro-partitioning: split data into many more partitions than machines (say 20 per machine), so load can be rebalanced finely and recovery after a failure is spread across many machines.
- Selective replication: keep extra replicas of hot items, so their load is spread.
- Latency-induced probation: temporarily remove consistently slow servers from rotation; outlier detection in Envoy does this.
- Good-enough results: in search and recommendation, answer with the shards that replied in time, rather than waiting for stragglers.
- Canary requests: for very wide fan-out, send to one or two leaves first. A request that crashes servers then takes down one or two, not thousands.
Within one service, tails often come from the runtime:
- garbage collection, fixed by tuning heap sizes, choosing low-pause collectors (ZGC, Shenandoah) or reducing allocation;
- JIT warm-up, fixed by warming up before taking traffic;
- lock convoys, fixed by sharding locks;
- page-cache misses, fixed by pre-warming files.
Measure p99.9, not just p99, for services that are fanned out to: their p99.9 becomes the callers' p99.
Deep Dive: Approximation as a performance toolShow
Exact answers can be very expensive. Many products do not need them: "trending videos", "about 1.2M views", "unique visitors this week". Approximate data structures trade a small, bounded error for orders of magnitude less memory and CPU.
Count-Min Sketch (frequencies).
- Structure: a small 2D array of counters with d rows, each row using its own hash function and w counters.
- Adding an item: increment one counter in each row.
- Estimating an item's count: take the minimum of its d counters. Collisions only ever add to a counter, so the estimate never undercounts. With w ≈ e/ε and d ≈ ln(1/δ), the overcount is at most ε × (total count) with probability 1 − δ.
- Memory: a few hundred kilobytes to megabytes replace a hash map keyed by every item, which could be hundreds of GB for billions of IDs.
Top-K with a sketch.
- On each event, add it to the sketch and immediately estimate the item's count.
- Keep a min-heap or sorted set of the K highest estimates. If the item beats the smallest entry, replace that entry.
- For time windows, keep one sketch and heap per tumbling window.
- As an optimisation, remember the smallest count currently in the top K and skip the heap update for any item whose estimate is below it. Most events then cost only the sketch increment.
- For sliding windows, subtract expired events. This works only if you decrement exactly what you previously added; some implementations do not support decrements.
Where the state lives matters for durability:
- In Redis, using its Count-Min and sorted-set commands. This is simple, but if an update reaches the sketch and not the heap, they drift. Recovering state consistently with the event log's offsets is awkward.
- In a stream processor's managed state (for example Apache Flink). This is checkpointed together with input offsets, so after a failure the job restores the checkpoint and replays events from the log consistently.
HyperLogLog (distinct counts). It estimates the number of unique items, such as unique visitors, in about 12 KB per counter with a standard error around 0.8%. It works by observing the maximum number of leading zeros in hashed values. Philippe Flajolet and colleagues introduced it in 2007. Redis exposes it as PFADD / PFCOUNT, and sketches merge across shards by taking register-wise maxima.
Bloom filters (membership). They answer "definitely not present" or "probably present". They are used to skip disk reads in LSM-tree databases and to block lookups of nonexistent keys before they hit a database.
Sampling. Process 1% of events and scale the result. This is fine for aggregate metrics, but dangerous for rare events and per-user answers.
Rules for using approximation:
- Confirm with the product owner that the error is acceptable.
- Keep the exact path for money, billing and anything legally significant.
- State the error bound in the design.
Deep Dive: Fan-out and order statisticsShow
When a request fans out to n backends in parallel and must wait for all of them, its latency is the maximum of n random latencies. Maxima behave very differently from averages.
The probability view. If each backend is slow (above some threshold T) with probability q, independently, then:
P(request is slow) = 1 − (1 − q)ⁿ
Dean and Barroso's example in "The Tail at Scale": a server whose p99 is 1 second, so q = 1%. A request that touches 100 such servers is slower than 1 second with probability 1 − 0.99¹⁰⁰ ≈ 63%. A rare event for one server becomes the common case for the request.
Working backwards to a per-leaf target. To keep the whole request's p99 below T with n leaves, each leaf must be below T with probability 0.99^(1/n):
| Fan-out n | Each leaf must meet T at | In other words |
|---|---|---|
| 1 | 0.99 | leaf p99 |
| 10 | 0.999 | leaf p99.9 |
| 100 | 0.9999 | leaf p99.99 |
| 1,000 | 0.99999 | leaf p99.999 |
This is why services that are fanned out to must be measured and tuned at p99.9 or p99.99, not p99.
The expected maximum. For exponentially distributed latencies with mean m, the expected maximum of n independent samples is m × (1 + 1/2 + 1/3 + ... + 1/n), which grows like m × ln n. With n = 100, the expected slowest reply is about 5.2 times the mean. Real latency distributions usually have heavier tails than exponential, so the real penalty is larger.
What reduces it:
- Lower n. Fewer, larger partitions per query; route queries only to shards that can hold matches; denormalise so one service can answer.
- Hedging. Re-sending to a second replica after the leaf's p95 converts the maximum of n leaf latencies into the maximum of n "minimum of two" latencies, which is much tighter.
- Partial results. For search, ranking and recommendations, answer with the leaves that replied within a deadline, and record how complete the answer was.
- Correlation awareness. The formula assumes independence. Synchronised GC, a shared noisy neighbour or a cron job on every host at the top of the minute makes leaves slow together, which helps the formula and hurts the user: all of them are slow at once. Add jitter to periodic background work.
Deep Dive: Measuring latency without fooling yourselfShow
Histograms, not averages, and the right kind.
- HdrHistogram (Gil Tene) records values in buckets with fixed relative precision, for example 0.1%, over a wide range in a few kilobytes. It is the standard for benchmarks.
- Prometheus classic histograms use buckets you choose. A percentile is interpolated within a bucket, so if the buckets are 100 ms and 250 ms, a reported p99 of "180 ms" could be anything between them. Choose bucket edges around your SLO threshold, or use the newer native (exponential) histograms.
- Prometheus summaries compute quantiles on each instance and cannot be aggregated across instances. Prefer histograms for fleet-wide percentiles.
- DDSketch (Masson, Rim and Lee, VLDB 2019) guarantees a relative error on every quantile and merges exactly across machines. t-digest (Ted Dunning) is accurate in the tails and also mergeable. Both are used in monitoring systems to compute fleet percentiles from per-host sketches.
Coordinated omission. Most simple load generators send a request, wait for the response, then send the next. If the server stalls, the generator stops sending, so it records one slow request where real users, who keep arriving, would have experienced many.
A worked example: a test at 100 requests per second for 10 minutes sends 60,000 requests. Normally each takes 1 ms, but the server stalls once for 1 second.
- The closed-loop tool records one request of 1 second and 59,999 of 1 ms. Its p99 and p99.9 both show 1 ms. The stall appears only in the max.
- In reality, about 100 requests would have arrived during the stall, waiting from 1 second down to 10 ms, about 0.5 seconds on average. That is about 0.17% of all requests above 10 ms, so the true p99.9 is hundreds of milliseconds.
Tools such as wrk2 schedule requests at a fixed rate and measure from the intended send time, which records the stall correctly. Gil Tene's talk "How NOT to Measure Latency" popularised the problem.
Other measurement traps:
- Measuring in the wrong place. Server-side timers start when the server begins processing, so time spent in the accept queue, the load balancer and the kernel is invisible. Compare server histograms with load balancer and client-side measurements.
- Averaging over windows. A 5-minute average p99 hides a 30-second spike. Alert on burn rates over several windows instead.
- Survivorship. Requests that timed out are often logged as errors without a latency, so latency charts look better precisely when things are worst. Record timeouts at the timeout value, or track them as part of the same SLI.
- Warm benchmarks. A benchmark that runs the same query in a loop measures a fully cached system. Production has cold caches, varied keys and background work.
Deep Dive: Mechanical sympathy: performance inside one machineShow
Distributed design dominates system design interviews, but many real performance wins come from respecting how a single machine works. Martin Thompson popularised the term mechanical sympathy for this.
The memory hierarchy. Approximate access times on a modern server:
| Level | Latency | Notes |
|---|---|---|
| L1 cache | about 1 ns | 32-64 KB per core |
| L2 cache | about 3-5 ns | hundreds of KB to a few MB per core |
| L3 cache | about 10-20 ns | tens of MB shared by cores |
| Main memory (DRAM) | about 80-100 ns | plus more on another NUMA socket |
| NVMe SSD read | about 20-100 µs | |
| Same-zone network round trip | about 100-500 µs |
Memory moves in cache lines of 64 bytes. The consequences:
- Sequential access is fast; random access is slow. Scanning an array streams cache lines that the CPU prefetches. Following pointers through a linked list or a tree can miss the cache at every step, at about 100 ns each. A sequential scan of 1 million integers can beat a hash lookup per item.
- Data layout matters. Storing fields that are read together side by side, or using columnar layouts for analytics, means each cache line loaded is fully useful. This is one reason columnar databases are so fast for aggregation.
- False sharing. Two threads updating different variables that happen to sit in the same cache line force that line to bounce between cores, which can slow both by an order of magnitude. Padding hot counters onto separate lines, or sharding counters per core, fixes it.
Threads and context switches. A context switch costs a few microseconds directly, and more through cache pollution. A service that runs thousands of threads, each blocking on I/O, spends a large share of its CPU switching. This is why event loops (Nginx, Node.js, Netty), lightweight threads (Go goroutines, Java virtual threads) and thread-per-core designs (Seastar, used by ScyllaDB) sustain far more concurrent connections per core.
Allocation and garbage collection. Allocating many short-lived objects per request raises GC frequency, and GC pauses show up directly in the tail. Reusing buffers, avoiding needless copies in serialisation, and choosing a low-pause collector all reduce p99.
Syscalls and copies. Every read or write call crosses into the kernel. Batching I/O (writev, sendmmsg), using sendfile to move file data to a socket without copying through user space, and newer interfaces such as io_uring cut this overhead. Kafka's use of the OS page cache and zero-copy transfer for consumers is a well-known example of designing around the machine.
The practical rule is the same as at the distributed level: measure first. CPU profilers and flame graphs show where time goes; hardware counters (perf stat) reveal cache misses and branch mispredictions when the profile says "time is spent here" but the code looks cheap.
Key Takeaways#
- Performance is speed for one request; scalability is staying fast as you add load and resources.
- Latency is time per operation, throughput is operations per second, and bandwidth is the capacity ceiling; aim for maximum throughput at acceptable latency.
- Measure latency with percentiles from merged histograms; fan-out turns rare slow responses into common slow pages.
- Little's law (L = λW) sizes threads, pools and queues; latency increases mean more in-flight work and more pressure.
- Queueing delay grows non-linearly with utilisation (W = S/(1−ρ)); keep bottlenecks at 50-70% and reduce variability.
- Reduce latency by caching, edge and geo-placement, async work, parallel calls, connection reuse, compression, batching, precomputation, indexes and approximation.
- Most API slowness comes from N+1 queries, missing indexes, unbounded results,
LIKEscans and sequential calls. - On long network paths, round trips dominate: reuse warm connections, terminate TLS at the edge, and keep first responses small.
- Throughput is capped by window ÷ RTT and by loss; the bandwidth-delay product explains slow cross-region transfers.
- Batching trades bounded latency for throughput; always batch with a size and a time limit.
- Caches cut the median and backend load, but misses still set the tail; with fan-out of n, each leaf must meet a far stricter percentile.