API Performance (API Design #10)
Checkout conversion drops 12% after a “routine” release. Nothing is down — every endpoint returns 200. But POST /orders went from 180 ms to 1.9 s at the 95th percentile, because the new fraud check runs three queries sequentially inside the request. The dashboards showed green averages the whole time; the p95 graph told the truth a day later.
Performance work starts with measuring the right thing, and “average latency” is almost never it. This chapter covers the metrics that matter (percentiles, throughput, error rate), where request time actually goes, caching strategies, load balancing and the queueing math behind it, rate limiting as both protection and fairness, sync vs async design, and how to test performance before your users do it for you.
By the end you will be able to read a latency distribution, size a fleet with Little’s law, build a token bucket, and know which work has no business happening inside a request.
Metrics that matter: percentiles, not averages
Averages hide pain. If 95 requests take 10 ms and 5 take 2 s, the average is a reassuring 105 ms — while one in twenty users waits two seconds. Percentiles state it honestly: p50 is the typical experience, p95 the unlucky tail, p99 the tail’s tail. Tail latency dominates at scale because a user-facing action often fans out to many internal calls; if each call has a 1% chance of being slow, an action touching \(k\) calls sees a slow one with probability
\[ P(\text{some call slow}) = 1 - (1 - 0.01)^{k} \]
At \(k = 50\) internal calls, that’s 39% of user actions hitting a straggler — the tail is the experience. Track the RED triplet per endpoint: Rate (requests/s), Errors (fraction failing), Duration (p50/p95/p99). Everything else is commentary.
Where the time goes
A request’s budget decomposes the way Chapter 1’s formula said: network in, your work, network out. The “your work” part has its own anatomy, and in most APIs it is dominated by waiting on other systems:
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum height=0.6cm, align=center, font=\rmfamily\scriptsize}]
\fill[blue!20] (0,0) rectangle (0.9,0.6); \node[align=center] at (0.45,0.3) {TLS\\10};
\fill[green!20] (0.95,0) rectangle (1.5,0.6); \node at (1.22,0.3) {auth 8};
\fill[orange!30] (1.55,0) rectangle (5.9,0.6); \node at (3.7,0.3) {database queries 62};
\fill[red!20] (5.95,0) rectangle (8.4,0.6); \node at (7.2,0.3) {fraud API 35};
\fill[gray!20] (8.45,0) rectangle (9.4,0.6); \node at (8.9,0.3) {render 12};
\node[font=\rmfamily\scriptsize, anchor=west] at (9.6,0.3) {ms (p95)};
\draw[->, thick] (0,-0.25) -- (9.4,-0.25);
\end{tikzpicture}
The profile dictates the fix: 62 ms of database time wants indexes and query review, not a faster JSON serializer. Profile before optimizing — every hour spent on the wrong segment is visible in the trace (Chapter 13’s tooling makes this cheap to see).
Caching: the three strategies
Caching trades freshness for speed, and the strategy is the trade’s fine print:
- Cache-aside (lazy): read checks the cache first; on miss, hit the database and populate. Simple, cache holds only what’s requested, but a miss costs a full read and a cold cache after deploy is a database stampede.
- Read/write-through: the cache sits in front of the database and handles both — writes update cache and store synchronously. Always-warm reads, at the cost of write latency and caching things nobody reads.
- TTL and invalidation: every entry expires (
max-agefrom Chapter 1). Short TTL = fresher, less effective; long TTL = fast, staler. The honest slogan: there are only two hard things — naming and off-by-one errors, and cache invalidation.
import time, redis
def get_invoice(iid: str, ttl: int = 60):
key = f"inv:{iid}"
if (cached := r.get(key)) is not None:
return json.loads(cached) # hit: ~1 ms
inv = db.get(Invoice, iid) # miss: ~60 ms
r.setex(key, ttl, json.dumps(inv)) # populate for next time
return inv
Watch for the stampede: a hot key expires and 500 concurrent requests all miss and all query the database at once. The fix is a per-key lock (one request recomputes, the rest wait or serve stale) — “stale-while-revalidate” as a policy, not just an HTTP header.
And don’t forget the cache you don’t run: CDNs honor your Cache-Control at edge locations worldwide. A cacheable GET /products served from a PoP 10 ms from the user beats your optimized origin 150 ms away — and absorbs traffic spikes you’d otherwise autoscale through. Design GETs to be cacheable (no per-user data in public responses) and the edge does free work for you.
Little’s law and load balancing
Sizing a fleet is arithmetic, not vibes. Little’s law connects concurrency \(L\) (requests being served), arrival rate \(\lambda\), and service time \(W\):
\[ L = \lambda W \]
At 2,000 req/s with \(W = 150\) ms, you are serving \(L = 300\) requests concurrently. If each instance handles 50 concurrent requests comfortably, you need 6 instances at zero headroom — run 9–12, because service time inflates non-linearly as utilization climbs toward 100% (queueing eats you alive long before you hit the theoretical limit).
The load balancer distributes arrivals across those instances. Round-robin is fine when requests are uniform; least-connections wins when some requests are slow (long polls, exports) — a busy instance stops receiving new work while round-robin keeps feeding it. Sticky sessions (routing a user to the same instance) re-introduce state by the back door; Chapter 1’s statelessness exists so the balancer doesn’t have to care.
Rate limiting: the token bucket
Rate limiting is performance’s immune system: it keeps one client from converting everyone else’s latency into their throughput. The standard algorithm is the token bucket: a bucket holds up to \(B\) tokens, refills at \(r\) tokens/second, and each request spends one token. Burstiness up to \(B\) is free; sustained rate above \(r\) is rejected with 429 + Retry-After:
import time
class TokenBucket:
def __init__(self, rate: float, burst: int):
self.rate, self.capacity = rate, burst
self.tokens, self.updated = burst, time.monotonic()
def allow(self) -> bool:
now = time.monotonic()
self.tokens = min(self.capacity,
self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
Design decisions: limit per API key (Chapter 7) rather than per IP (NATs punish innocents), tier limits by scope (reads generous, writes tight), and return Retry-After so well-behaved clients back off automatically instead of hammering. In a fleet, the bucket state lives in Redis or the gateway (Chapter 11), not in per-instance memory.
Sync vs async: the 202 pattern
Some work does not belong inside a request. Generating a PDF report, re-encoding video, sending 10,000 emails — anything beyond your latency budget (say 500 ms) should be deferred: accept the request, enqueue the work, return immediately:
POST /reports → 202 Accepted
Location: /reports/r-91 (poll for status, or)
Retry-After: 5
GET /reports/r-91 → 200 {"status": "running"} ... later ...
GET /reports/r-91 → 303 See Other, Location: /reports/r-91/download
202 Accepted is the honest status: “I heard you; the answer isn’t ready.” The client polls the status resource (or you push completion via webhook — Chapter 4’s pattern server-to-server). Sync vs async is a user-experience decision backed by math: if p95 of the work is 200 ms, do it inline; if it’s 30 s with high variance, inline means timeouts and retried duplicates.
One more sync/async nuance worth naming: async is not “faster.” The queue adds latency (enqueue, wait, worker) to the operation; it removes latency from the request. The user gets an honest acknowledgment now and the artifact when it’s ready — and your web tier stays sized for requests, not for the day’s heaviest job.
Test it before your users do
Performance regressions are found by load tests or by customers. Tools like k6 make the test a script with assertions:
// k6: ramp to 200 rps, assert the SLO holds
export const options = {
stages: [{ duration: "2m", target: 200 }],
thresholds: {
http_req_duration: ["p(95)<500"], // p95 under 500 ms or the test fails
http_req_failed: ["rate<0.01"],
},
};
Run it in CI against staging on every release, and the 180 ms → 1.9 s regression from the opening story becomes a red build instead of a conversion graph. Complement with profiling (flame graphs on the hot path) and monitoring (RED dashboards with p95 alerts — Chapter 13 operationalizes this).
Pitfalls
- Optimizing the average. The average looked fine while 5% of users suffered. Alert and optimize on p95/p99.
- Caching without a stampede plan. A hot key expires and the database takes 500 simultaneous misses. Per-key locks or stale-while-revalidate.
- N+1 queries. Serializing a list of 100 invoices, each lazily fetching its customer, is 101 queries per request. The ORM won’t warn you; the trace will. Eager-load or batch.
- Scaling to 100% utilization on paper. Little’s law gives the minimum; queueing delay explodes near saturation. Run at 50–70%.
- Long work inside requests. A 30 s export inline means gateway timeouts and duplicate retries. 202 + queue + webhook.
- Rate limiting per IP. One corporate NAT, 5,000 employees, one shared limit. Limit per key/identity.
Why can the average latency look healthy while users suffer? At 1,500 req/s and 200 ms service time, how many concurrent requests are in flight, and why isn’t “exactly that many capacity” enough? When does work deserve the 202/async pattern instead of an inline response?
ASolution
Averages compress the distribution: a few multi-second stragglers barely move the mean but wreck the tail — and fan-out makes the tail the norm (a 1% slow-call rate across 50 internal calls makes ~39% of user actions slow), so measure p95/p99. Little’s law: \(L = \lambda W = 1500 \times 0.2 = 300\) concurrent requests — but that’s the steady-state mean; utilization near 100% makes queueing delay explode, so provision for 50–70% utilization with headroom for bursts. Use 202 + async when the work’s duration or variance exceeds the latency budget of an interactive request (seconds-to-minutes, spiky): the client gets an immediate honest acknowledgment and polls or receives a webhook, instead of timing out and retrying duplicates.
Next: API Integration Patterns (API Design #11) — gateways, BFFs, microservices, events, and the retry discipline that keeps them from cascading.