How do you scale an API?
Find the bottleneck first, then use the cheapest lever that removes it: fix the query, cache the read, pool the connections, add replicas, queue the slow writes, limit each client. Each lever measured on one machine: what it bought, and what it cost.
Short answer: the culprit, as we’ll prove, is whatever runs out first, and the fix is the cheapest technique that removes that one limit. Usually that means, in order:
- fix the slow query;
- cache the reads that repeat;
- put a pooler in front of the database;
- run more copies of a stateless API behind a load balancer;
- move slow writes onto a queue;
- limit each client so one can’t take the capacity everyone shares.
Read replicas, partitioning and sharding come last, because each one changes what your application can assume about its data. Adding servers before you know the bottleneck mostly adds cost.
Here is the case. Traffic climbs, the API slows, and the instinct is to reach for the wallet: more servers, a bigger database. But scaling rewards curiosity over spending. Each lever below is a small, well-understood idea, and the real detective work is finding the one that fits the limit you actually have.
I gathered the evidence on one laptop with latency-debugging-lab; make scaling reruns it. The queue numbers come from my event-driven reference. One machine can’t show what a fleet does, so read the numbers as ratios between setups, and see the caveats at the end.
Case file
The case Traffic climbs and the API slows Suspects A slow query, API CPU, repeated reads, database connections, slow writes, one noisy client Culprit Whatever runs out first The fix The cheapest lever that removes that one limit Evidence One laptop, latency-debugging-lab ( make scaling) and the event-driven reference
Step 0: identify the suspect #
Every investigation starts here, and it’s the step people most often skip. These are the usual suspects, and the fingerprints each one leaves:
| What runs out | How it shows | First fix | Section |
|---|---|---|---|
| A slow query | One long database span; the database busy | Index or rewrite it | the slow-query post |
| CPU in the API | API CPU near 100%; latency rising with traffic | More replicas, or bigger instances | 2 |
| Repeated reads | The same queries, thousands of times a minute | A cache, as far forward as freshness allows | 1 |
| Database connections | too many clients; long waits for a pooled connection |
A pooler | 3 |
| A slow dependency or slow writes | Requests waiting on work the user doesn’t need to see happen | A queue | 4 |
| One client’s traffic | One API key or IP dominating the logs | Per-client rate limits | 5 |
| The database itself, after all of the above | Writes or the data size outgrow one machine | Replicas, then partitioning, then sharding | 6 |
The slow-page debugging post shows what each of these looks like in a trace. Measure first: every technique below costs something, and the cost is wasted if you’ve arrested the wrong suspect.
The line-up at a glance #
| Technique | What it fixes | What it costs | How it fails | Pick it when |
|---|---|---|---|---|
| Fix the query | Database time per request | An index, a rewrite | Plans change as data grows | Always first |
| Cache (CDN, proxy, Redis, in-process) | Repeated reads | Stale data, invalidation bugs | Wrong data; stampedes on expiry | Reads repeat and can be a little old |
| Connection pooler (PgBouncer) | Too many connections | One more component; session features need care | Pool too small: queueing; too big: no protection | Many app instances or serverless functions |
| Replicas of the API | CPU in the API | More instances; state must live elsewhere | Shared state in memory; uneven balancing | The API is CPU-bound and stateless |
| Queue the slow part | Write spikes, slow dependencies | Eventual consistency, a worker to run | Backlogs nobody notices | The user doesn’t need the result in the response |
| Per-client rate limits | One client starving the rest | Some legitimate bursts get 429 |
Limits keyed wrongly (one office behind one IP) | Any API with more than one client |
| Read replicas | Read load on the primary | Replication lag | A user doesn’t see their own write | Reads dominate and can be slightly behind |
| Partitioning / sharding | Data or write volume beyond one machine | Cross-shard queries, rebalancing | A hot shard | Nothing else is left |
Diagram source
flowchart TD
A["The API slows"] --> B{"One long database span?"}
B -- yes --> B1["Fix the query"]
B -- no --> C{"Same reads repeating?"}
C -- yes --> C1["Cache, as far forward as freshness allows"]
C -- no --> D{"too many clients?"}
D -- yes --> D1["Put a pooler in front"]
D -- no --> E{"API CPU saturated?"}
E -- yes --> E1["More replicas or a bigger instance"]
E -- no --> F{"Waiting on slow work?"}
F -- yes --> F1["Queue the slow part"]
F -- no --> G{"One client dominating?"}
G -- yes --> G1["Per-client rate limits"]
G -- no --> H["Replicas, then partitioning, then sharding"]
1. The reads that repeat #
The case: a read-heavy public API. For example, a dashboard endpoint that runs a 20 ms aggregate per tenant, called over and over for the same 10 tenants. One replica with one CPU, caching for 1 second:
| Cache (1 s TTL) | Sustained req/s | p50 there | p99 there |
|---|---|---|---|
| None | 100 | 43 ms | 66 ms |
| In-process map in the app | 800 | 0.5 ms | 78 ms |
| Redis | 800 | 0.8 ms | 69 ms |
| nginx micro-cache in front of the app | 6,400 (highest rate tried) | 0.3 ms | 1.3 ms |
Diagram source
xychart-beta
title "p99 latency with a 1 s cache (ms, lower is better)"
x-axis ["None", "In-process", "Redis", "nginx micro-cache"]
y-axis "p99 (ms)"
bar [66 , 78 , 69 , 1.3]
“Sustained” means the highest rate I tried at which the p99 stayed under 100 ms with under 1% errors.
Three clues stand out, and the first one still surprises me:
- A one-second cache multiplied capacity by 8× in the app, and by 64× or more in front of it. With 10 tenants and a 1 s TTL, the database sees roughly 10 queries per second, plus the extra misses at each expiry (below), however many requests arrive. That’s the quiet beauty of it: the load on the database stops depending on the traffic at all.
- Caching in front of the app beats caching in it. With the in-process or Redis cache, every request still goes through nginx, the app’s HTTP handling and a cache lookup, and that work saturated the one CPU at 1,600 req/s. The nginx micro-cache answered from nginx’s own memory, and the app never saw the repeats. A CDN does the same thing one step further out, close to the user. That only works for responses that are the same for everyone, or for everyone in a cache key you control. The app marks them with
Cache-Control: public, max-age=1. - The p99 stayed at 60-80 ms with the app-level caches, even at low traffic. This one is a little mystery inside the mystery. Every second, each tenant’s entry expires, and the requests that arrive in that moment all miss together and run the 20 ms query at once. nginx’s
proxy_cache_locklets one request through and makes the rest wait for it: one setting, and the stampede is gone. That’s why its p99 dropped to 1.3 ms once traffic was high enough. The cache post measures this stampede and its fixes.
Where to cache: at the CDN or proxy for public responses that can be seconds old; Redis for data shared across replicas, or too big to keep in each one; in-process for small, hot, read-only data (configuration, feature flags). And remember a cache is a second copy of your data. Freshness bugs come with it.
2. More replicas, or a bigger instance? #
The case: the API itself is CPU-bound (rendering, serialisation, authentication), with no shared state in memory. Each request needed about 1 ms of CPU. Replicas sat behind nginx, each limited to one CPU:
| Setup | Sustained req/s | p99 there | At the next rate tried |
|---|---|---|---|
| 1 replica, 1 CPU | 1,000 | 26 ms | 1,250 req/s: p99 2 s, errors |
| 2 replicas, 1 CPU each | 1,500 | 24 ms | 1,750 req/s: p99 445 ms |
| 3 replicas, 1 CPU each | 1,500 | 27 ms | 1,750 req/s: p99 136 ms |
| 1 replica, 3 CPUs | 2,000 | 45 ms | 2,250 req/s: p99 435 ms |
Read this clue carefully, because it can mislead: the second replica added 50%, and then the laptop ran out. The load generator, nginx and every replica shared 4 cores. Going from 2 replicas to 3 only made the next step less bad (p99 136 ms instead of 445 ms). That’s the laptop talking, not the technique. In production each replica has its own machine, and horizontal scaling is close to linear for a stateless, CPU-bound API, until something shared (the database, a cache, a lock) becomes the limit.
What the table does show:
- Past one CPU, capacity collapses suddenly. It went from a 26 ms p99 at 1,000 req/s to 2 s and errors at 1,250. Scale before you reach the edge. CPU around 60-70% at peak is a common target for autoscaling.
- Vertical scaling is a real option. One process with 3 CPUs did as well as anything else here, because it avoids splitting load across processes. Bigger instances are simpler to operate, until one instance is too big to fail or to deploy.
- Horizontal scaling only works for stateless APIs. Sessions, rate-limit counters, caches and uploads need to live somewhere shared (Redis, the database, object storage), or each replica sees a different world.
Load balancer: on AWS, an Application Load Balancer is the default (managed, scales itself, health checks). nginx is a fine self-hosted choice, but open-source nginx (1.29) only takes servers out of rotation passively, after failed requests; active health checks are in NGINX Plus. Envoy brings dynamic configuration, retries, circuit breaking and outlier detection, at the price of more to operate. Pick it when you need those features across many services.
3. “Too many connections”: a false lead, and a pooler #
The case: more app instances, and the database starts refusing connections. The tempting suspect is the database’s size, and the tempting fix is a bigger one. Every instance has its own pool, and PostgreSQL’s default max_connections is 100 (PostgreSQL 17). I simulated 4 and 6 app instances with pools of 20, each running queries that need about 5 ms of database CPU:
| Path | Instances × pool | Server connections (peak) | Queries/s | p50 | p99 | Errors |
|---|---|---|---|---|---|---|
| Direct | 4 × 20 | 90 | 968 | 84 ms | 199 ms | 0 |
| Direct | 6 × 20 | 99 | 803 | 113 ms | 234 ms | 1,003 × too many clients already |
| PgBouncer, transaction mode, pool 20 | 4 × 20 | ~30 | 792 | 99 ms | 149 ms | 0 |
| PgBouncer, transaction mode, pool 20 | 6 × 20 | ~30 | 793 | 152 ms | 197 ms | 0 |
Two lessons, and the first surprises most people:
- More connections didn’t mean more work done. 90 direct connections did 968 queries/s; about 30 through PgBouncer did 792-793. The database had 4 cores, and once they were busy, extra connections only added queueing and memory (each PostgreSQL connection is a separate process). Throughput is set by what the database can run in parallel, roughly a small multiple of its cores, not by how many connections you open.
- The pooler turned failures into waiting. With 6 instances, direct connections failed over a thousand times, while PgBouncer queued the extra demand and kept going. A bigger instance only raises the ceiling; the next deploy or autoscaling event hits it again. A pooler removes the ceiling from the app’s side, which is a far more satisfying answer than buying a taller room.
Transaction pooling has rules: anything that lives in a session doesn’t survive between transactions. That includes SET without LOCAL, session-level advisory locks, LISTEN, and temporary tables. Prepared statements work in PgBouncer 1.21+ with max_prepared_statements set (1.26 here). On AWS, RDS Proxy does the same job as a managed service.
4. Queue the slow part #
The case: write spikes, or a slow step the user doesn’t need to wait for (an email, a sync to another system, an invoice PDF). Accept the request, commit it with an outbox row, and let workers do the rest.
The evidence comes from my event-driven reference: one Node.js API process with a transactional outbox in front of a queue, on one laptop.
- At 300 req/s, the API answered at p95 14.5 ms, and orders were confirmed 338 ms later at p95.
- At 450 req/s, the API still answered at p95 151 ms, while the asynchronous side fell behind. Confirmations lagged by about 15 s and then drained. The queue absorbed the spike instead of failing requests, which is exactly the behaviour you want, and lovely to watch.
- At about 540 req/s that single process saturated.
The cost is that the result is no longer in the response, so you need a status the client can check, and an alarm on queue age. When should a write go through a queue? covers the trade-offs, and when not to queue (payment authorisation, anything the user must see succeed).
Which queue:
- SQS for work queues, if you’re on AWS and want nothing to operate (the AWS messaging post compares it with SNS and EventBridge);
- Kafka when several consumers need to replay the same ordered stream of events;
- RabbitMQ when you need routing rules and are happy to run a broker.
5. Limit each client #
The case: one client sends ten times its usual traffic (a retry loop, a scraper, a customer’s batch job). 10 normal clients sent 300 req/s in total, while one client sent 1,500 req/s, to a replica that can serve about 1,000:
| Per-client limit | Normal clients: served/s | Their p50 | Their p99 | Noisy client: served/s | Noisy client: rejected (429) |
|---|---|---|---|---|---|
| None | 200 of 300 | 2.6 s | 5.0 s (timeouts) | 1,016 | 0 |
| 50 req/s per client (token bucket) | 300 of 300 | 1.1 ms | 10 ms | 56 | 11,551 |
Without limits, the noisy client took most of the capacity and everyone else waited seconds or timed out. With a per-client token bucket, the noisy client got its share and fast 429 Too Many Requests responses for the rest. Rejecting a request costs almost nothing, so the normal clients didn’t notice anything had happened. That asymmetry is the elegant part: the defence is far cheaper than the attack it absorbs, which is what makes the token bucket so effective.
Where to limit: at the edge (a WAF rule, API Gateway usage plans, nginx limit_req) for crude per-IP floods, before they cost you anything. In the app for limits that need to know who the client is: per API key, per tenant, per plan. Key limits on the authenticated identity where you can, because a whole office or mobile carrier can share one IP. The rate-limiting post shows how to keep the limiter’s memory bounded.
6. When the database itself is the culprit: replicas, partitions, shards #
Not measured here; the replicas, partitioning and sharding post measures the first two.
- Read replicas take read load off the primary. They cost replication lag: a user who just saved something can read the old version from a replica. Send a user’s reads to the primary for a short while after they write, or for anything they just changed.
- Partitioning (one table split by time or tenant, still on one server) keeps indexes small and makes old data cheap to drop. It doesn’t add capacity, but it delays the need to.
- Sharding (data split across servers) is the only one that adds write capacity, and the most expensive. Queries across shards, transactions across shards, rebalancing, and a hot shard for your biggest customer all become your problem. Choose the shard key from your access patterns (usually the tenant), and do it only when everything above has been used.
Remember this
- Find what runs out first, then pick the cheapest lever for that one limit.
- Cache in front of the app, and use a pooler before the second app instance.
- Replicas, partitioning and sharding come last.
Case closed: what I’d do on Monday #
- Measure first: traces, the database’s slowest queries (
pg_stat_statements), CPU per tier, connection-pool waits. - Fix the slow queries, then cache what repeats, as far forward (CDN, proxy) as freshness allows, with request collapsing.
- Put a pooler in front of PostgreSQL before the second app instance, not after the first
too many clients. - Keep the API stateless so adding replicas is a configuration change, and autoscale on CPU with headroom.
- Queue anything the user doesn’t need to wait for, and alarm on queue age.
- Limit every client by identity, at the edge for floods and in the app for fairness.
- Only then add read replicas, partitioning, and finally sharding.
None of these levers is exotic, and that’s the encouraging part of how this case resolves. A careful look at what runs out, and a cheap fix aimed squarely at it, goes a long way before you need anything grand.
Measured Nov 2026 on one laptop (Intel i7-8550U, 4 cores / 8 threads) with Go 1.27, PostgreSQL 17.11, PgBouncer 1.26.1, nginx 1.29.8 and Redis 7.4. The load generator shared the machine with everything it tested, so the numbers are this machine’s: the differences between rows are the point, not the absolute rates. Queue numbers: multi-tenant-event-driven-ref, measured with k6 on the same laptop. Code and full results: latency-debugging-lab/scaling.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.