One request has a budget of 50 ms. A missing index can spend 300 ms of it on one query. The backend engineer builds the API, the data path and the limits that keep every request inside its budget.
Turn on the index, the cache and connection reuse. Watch one request drop under its budget and the database load fall. Then we build each piece from zero: the contract, safe retries, pagination, indexes, caches, rate limits, capacity, tail latency and error budgets.
You need a little Python, a rough idea of HTTP (a client sends a request, a server sends a response) and what a database table is. We build the rest from zero.
Illustrative numbers for GET /v1/orders?customer=42 at 2,000 requests per second. The parts: 10 ms of fixed work, a 30 ms TLS handshake on a new connection, a 300 ms full-table scan or a 2 ms index lookup, and a cache with an 80% hit rate at 1 ms.
Chapter 0
Follow one request from the client to the database and back, and see where its milliseconds go
A script calls GET /v1/orders?customer=42. Somewhere a server checks the caller's key, finds the orders and sends back JSON. The caller sees one number: how long it waited. A backend and API engineer builds and runs everything behind that number.
The job has five parts. Each one is a chapter of this lesson.
| Part | What you build | What goes wrong without it |
|---|---|---|
| The contract | endpoints, methods, status codes, error bodies | clients guess, and retries create duplicates |
| The data path | tables, indexes, pagination, caches | fast at 1,000 rows, unusable at 10 million |
| The limits | rate limits, connection pools, timeouts | one caller's loop takes down every caller |
| The numbers | latency budgets, percentiles, capacity plans | the average looks fine while 1 in 100 users waits seconds |
| The promise | SLOs, error budgets, alerts | either no change ever ships, or nobody notices an outage |
A latency budget is the time a request may take, split among the stages it passes. Say the target is 50 ms for a read. Every stage spends part of it. Trace one request and see which stage spends the most.
Each bar is one stage, in order. Pick a case and find the stage that breaks the 50 ms line.
Illustrative stage times on a warm connection. The normal read is 2 + 3 + 10 + 1 + 20 + 2 = 38 ms. The timeout case stops the query at a 1,000 ms statement timeout and returns an error.
Worked number for the normal read. Load balancer 2 ms, gateway and auth 3 ms, handler 10 ms, cache check 1 ms, database 20 ms, serialize 2 ms. The sum is 38 ms, so 12 ms of the budget is left. The database alone spends 53% of the total. That is why most chapters here are about the data path.
The failure. Symptom: the median time is normal but 1 request in 100 takes a second. Measure: break each slow request into stages with a trace (one timed record per stage). Fix: work on the stage that grew, not on the whole system.
Chapter 1
Name resources, pick the method that says what a retry does, and return errors a developer can fix
A developer writes code against your API once and runs it for years. Every path, field and status code is a promise. The API contract is that set of promises, written down in a spec such as OpenAPI.
A REST API names resources (nouns: orders, customers) and lets the HTTP method carry the verb. POST /v1/orders creates an order. GET /v1/orders/ord_81 reads one. A path like /v1/createOrder hides the verb in the name, so clients and caches cannot reason about it.
The method matters because HTTP gives each one a meaning. RFC 9110, the HTTP semantics standard, defines two properties. A safe method asks only to read: GET, HEAD, OPTIONS and TRACE. An idempotent method has the same intended effect whether you send it once or many times: PUT, DELETE and the safe methods. POST is neither. PATCH (RFC 5789) is not idempotent in general.
The first response is lost, so the client sends the same request again. Pick a method and press Send twice. Watch the server's orders.
The safe and idempotent sets are from RFC 9110, sections 9.2.1 and 9.2.2. The PATCH body here is "add 1 to quantity", one common non-idempotent patch.
Worked case: a client sends PUT /v1/orders/ord_81 with {"qty": 3}, and the connection drops. Two copies arrive. The quantity is 3 after the first and still 3 after the second. Now send POST /v1/orders twice. The server creates ord_82 and ord_83: two orders, one intent. Chapter 2 fixes POST.
| Code | Meaning | Use it when |
|---|---|---|
| 201 Created | a new resource exists | a POST created it; send its id |
| 202 Accepted | work started, not done | a long job; send a job id to poll |
| 400 / 422 | bad syntax / valid syntax, wrong content | a field is missing / a value is out of range |
| 401 / 403 | who are you? / you may not | no valid key / the key lacks the scope |
| 409 Conflict | clashes with current state | a version mismatch or a reused key with a new body |
| 429 | Too Many Requests (RFC 6585) | a rate limit; add Retry-After |
| 503 | Service Unavailable | overloaded; add Retry-After |
An error body is documentation the developer reads at 3 a.m. Give it a stable machine code, the field at fault, a sentence a person can act on and a request id for your logs:
json{ "error": { "code": "qty_out_of_range", "param": "qty", "message": "qty must be between 1 and 100. You sent 250.", "request_id": "req_7f3a" } }
The failure. Symptom: a client sends qty: 250, the server quietly clamps it to 100, and the client ships the wrong order. Measure: search logs for inputs that differ from what you stored. Fix: reject the value with a 422 that names the field. Never change input silently.
Chapter 2
Make a POST safe to resend, and space the retries so they do not pile up
A checkout script sends POST /v1/payments. The server charges the card. Then the response is lost on the way back. The script cannot tell "charged" from "never arrived", so it retries. Without protection the server charges the card twice.
The fix is an idempotency key: a unique string the client makes once per intent and sends in an Idempotency-Key header on every retry. The server stores the first response under that key. A retry with the same key gets the stored response, and nothing runs twice.
Stripe's API works this way. It saves the status code and body of the first request for a key and returns them to retries. It rejects a reused key with different parameters, and it may prune keys after they are at least 24 hours old. An IETF draft proposes the same header for any HTTP API; it is not yet an RFC.
If 1,000 clients retry the moment a server fails, the server gets 1,000 more requests while it is down. So clients wait longer after each failure. Call the retry number n (0 for the first retry). Call the first wait the base, and the longest allowed wait the cap. The ceiling on the wait before retry n is:
w-n equals the minimum of cap and base times two to the n.
Double the base once for each failed retry n. If that is more than the cap, use the cap. With full jitter, the client then sleeps a random time between 0 and w-n, so clients spread out instead of retrying in step.
With base 100 ms and cap 10,000 ms, the ceilings are 100, 200, 400, 800 and 1,600 ms for retries 0 to 4. Their sum is 3,100 ms. With full jitter the average wait is half of that, 1,550 ms, and retry 7 reaches the cap.
Each tick on the timeline is one attempt. The first responses are lost. Turn the key on or off and press Send.
Illustrative: base 100 ms, cap 10,000 ms. Every attempt reaches the server and runs; only the response is lost. A seeded generator draws the jitter, so the run repeats.
The failure. Symptom: two retries with the same key arrive 5 ms apart, both miss the stored response, and both run. Measure: count rows that share a key. Fix: take the key's lock (or insert the key under a unique constraint) before you run the work, not after.
Chapter 3
Return a long list in pages, and keep the pages correct while new rows arrive
A customer has 100,000 orders. No response should hold them all. So the API returns a page of 20 and a way to ask for the next. There are two common ways, and one of them breaks on a busy table.
Offset pagination asks "skip o rows, return the next l": ?limit=20&offset=40. Cursor pagination (also called keyset pagination) asks "return 20 rows after this one". The server sends an opaque cursor that encodes the last row's sort key, and the next query is WHERE (created_at, id) < (last_ts, last_id) ORDER BY created_at DESC, id DESC LIMIT 20.
The list is newest first, 8 rows per page. Page 1 is already shown. Add new orders, then fetch page 2 each way.
Illustrative list of 30 orders. New orders arrive at the top, the newest end, between the two page requests.
Offset has a second cost. To skip o rows the database still reads them. Call the offset o and the page size l. The rows the database reads for one page are:
R equals o plus l.
The database walks past all o skipped rows, then reads the l it returns. The cost R grows with how deep the page is. A cursor seeks straight to its row through the index, then reads l rows, so its cost does not grow with depth.
With l = 20: page 1 has o = 0 and R = 20. Page 51 has o = 1,000 and R = 1,020. Page 5,000 has o = 99,980 and R = 100,000. A cursor reads a few index pages plus 20 rows on every one of them.
Worked case for the bug: page 1 shows orders 30 down to 23. Three new orders arrive. Now the offset query for page 2 skips the 8 newest rows, which are the 3 new orders and orders 30 to 26. It returns orders 25 to 18. Orders 25, 24 and 23 appear on both pages. With a cursor, page 2 starts after order 23 and returns 22 to 15, with no repeat.
The failure. Symptom: a developer reports rows that appear twice, or vanish, while they page through a busy list. Measure: page through while a test inserts rows, and compare the ids with a full export. Fix: switch to a cursor on a unique sort key. Add the id as a tie-breaker, since two rows can share a timestamp.
Chapter 4
Turn a scan of every row into a walk down a short tree, and order the columns to match the query
The hero's slow query was SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20. With no index, PostgreSQL runs a sequential scan: it reads every page of the table and keeps the matching rows. EXPLAIN shows this as Seq Scan.
A B-tree index is a sorted tree of keys, each pointing at its row. It is the default index type in PostgreSQL. Each tree page holds many keys, so the tree is short. Call the number of rows N. Call the fan-out f the number of children of one tree page. The height h is the number of pages you read from the root down to a leaf:
h equals the ceiling of log base f of N.
Each level of the tree splits the keys into f groups. Count how many splits it takes to get from all N rows down to one. That count, rounded up, is h.
With made-up fan-out f = 200: N = 1 million gives log = 2.61, so h = 3. N = 10 million gives 3.04, so h = 4. Even N = 1 billion gives h = 4. A scan of 10 million rows at 50 rows per page reads 200,000 pages. The index reads 4, plus about one table page per matching row.
The index is on (customer_id, created_at). Pick a query and drag the table size. The bars use a log scale.
Illustrative: fan-out 200, 50 rows per table page, 20 rows returned. The planner can sometimes use a skip scan for the third query, when the first column has few distinct values. The device ignores that case.
Column order matters. The PostgreSQL docs say a multicolumn B-tree index is most efficient with constraints on its leading (leftmost) columns. An index on (customer_id, created_at) serves "customer 42, newest first" and "customer 42 after time t". It does not narrow "after time t" for all customers, because those rows are spread across every customer's part of the tree.
The failure. Symptom: an endpoint was 3 ms at launch and is 900 ms a year later, with no code change. Measure: run EXPLAIN ANALYZE on the query and look for Seq Scan on a big table. Fix: add the index that matches the query's equality columns first, then its range or sort column. Build it with CREATE INDEX CONCURRENTLY so writes keep flowing.
(customer_id, created_at). Which query can it NOT narrow well?Chapter 5
Keep hot answers close, measure what the hit rate buys, and stop a stampede when a hot key expires
The same order page is read 5,000 times a second and changes once an hour. Asking the database each time wastes it. A cache stores recent answers in fast memory, such as Redis. In the cache-aside pattern the handler checks the cache first. On a miss it reads the database and writes the answer back with a TTL (time to live).
What does a cache buy? Call the share of reads it answers the hit rate h. Call the time of a hit thit and the time of a miss tmiss. The average read time T is:
T equals h times t-hit, plus one minus h times t-miss.
Weight the fast time t-hit by how often you hit, h. Weight the slow time t-miss by how often you miss, 1 minus h. Add them. The database also sees only the misses: 1 minus h of the traffic.
With made-up times t-hit = 1 ms and t-miss = 20 ms: h = 0.9 gives T = 0.9 + 2 = 2.9 ms. At 5,000 reads a second the database gets 500. Raise h to 0.99 and T = 1.19 ms, and the database gets 50, ten times fewer.
So the last few points of hit rate matter most. From 90% to 99% the latency barely moves, but the database load drops tenfold.
Now the hot key expires. Every request in the next 20 ms misses, and every one of them queries the database for the same row. At 5,000 reads a second that is 5,000 × 0.020 = 100 identical queries at once. This is a cache stampede (also called a thundering herd). The fix is single-flight: the first miss takes a short lock and refills the key; the others wait a moment or serve the stale value.
Drag the hit rate and watch the database bar. Then press Expire and count the queries that reach the database.
Illustrative: 5,000 reads per second, 1 ms hits, 20 ms database reads. The stampede count is reads per second times the refill time.
The failure. Symptom: a customer renames an order, gets 200 OK, and still reads the old name for 5 minutes. Measure: compare the cached value with the database row and note the TTL. Fix: delete the key (and every list key that holds the row) when you write, and keep the TTL as a safety net.
Chapter 6
Give each caller a steady rate plus a small burst, and turn the excess away with a 429
A customer's script has a bug: it calls your API in a tight loop, 3,000 times a second. Your servers serve everyone from one pool. Without a limit, that one script slows every other customer. A rate limit caps how many requests one caller may send in a period. Requests over the cap get 429 Too Many Requests and a Retry-After header.
The most common shape is the token bucket. Each caller has a bucket that holds up to b tokens. Tokens drip in at a rate r per second. Each request takes one token. With none left, the server refuses it.
Call the tokens in the bucket k and the time since the last refill Δt. On each request the bucket refills first:
k-prime equals the minimum of b, and k plus r times delta-t.
Add r tokens for each second that passed, delta-t. Stop at the capacity b. If k-prime is at least 1, take one token and serve the request. If not, send a 429.
With r = 10 per second and b = 20: an empty bucket that waits 0.5 s has k-prime = min(20, 0 + 10 × 0.5) = 5 tokens. Over a full minute a caller can send at most b + r × 60 = 20 + 600 = 620 requests.
The bucket refills on its own. Press Burst to send 10 requests at once, or Send for one. Then lower the capacity and try again.
Illustrative rates. The bucket runs in this page in real time, the same code as the field guide's TokenBucket.
| Shape | How it counts | Weak spot |
|---|---|---|
| Fixed window | one counter per clock minute | 600 at 12:00:59 and 600 at 12:01:00 is 1,200 in 2 seconds |
| Sliding window counter | this minute's count plus the last minute's, weighted by overlap | an estimate; 25% into the minute, 600 last minute and 100 now count as 600 × 0.75 + 100 = 550 |
| Token bucket | tokens refilled by elapsed time | a full bucket allows a burst of b at once, by design |
Where the count lives matters too. If each of 8 servers keeps its own bucket of 100 per second, a caller spread across all 8 gets up to 800 per second. A shared counter in Redis, updated with one atomic command per request, gives one limit for the whole fleet.
The failure. Symptom: a developer sends 10 requests a minute and still gets 429s. Measure: count requests per key across all their workers, including retries. Often 6 workers share one key, or the client retries 429s at once. Fix: send Retry-After, and document backoff with jitter (Chapter 2).
Chapter 7
Size a connection pool with Little's law, then watch a queue explode as the pool fills
PostgreSQL starts one server process for each client connection, and opening one costs a network handshake and authentication. So each API server keeps a connection pool: a fixed set of open connections that requests borrow and return. A request that finds every connection busy waits in a queue.
How many connections are busy? Call the arrival rate of database queries λ, per second. Call the time one query holds a connection W, in seconds. The average number in use, L, is Little's law:
L equals lambda times W.
Multiply how many queries arrive each second, lambda, by how long each one stays, W. The result L is how many are inside at once. It holds for any stable system, whatever the order of service.
With made-up numbers: lambda = 2,000 queries per second and W = 5 ms = 0.005 s give L = 10. A pool of 20 is then 50% busy. If a bad plan makes W = 15 ms, L = 30. That is more than the 20 connections, so the queue grows without end.
The pool's busy share is L divided by the pool size. The queue stays short at 50% and grows fast near 100%. In the standard queueing model with random arrivals and 20 connections, 55% of queries wait when the pool is 90% busy; at 50% almost none do. The simulator below runs that model. It is the showcase of this lesson: three knobs that every API team turns.
The bar is the pool, one cell per connection. The curve is the spread of request times. Push the rate past the pool's limit and watch p99.
A real simulation run in your browser: 20,000 queries with random (exponential) gaps and query times, first come first served, a 1,000 ms timeout. Seeded, so the same knobs give the same result.
Read the run at the defaults: 10 connections in use on average, and the median and p99 are close to the bare query time. Now set the query time to 10 ms. Little's law says L = 20, the whole pool. The median creeps up while p99 jumps, and timeouts start. A percentile is the time under which that share of requests finish: p99 is the time that 99 in 100 beat.
The failure. Symptom: p50 is normal, p99 climbs, and 500 errors appear only at peak hours. Measure: plot "requests waiting for a connection" and the pool's checkout time. Fix: first make W smaller (an index, a shorter transaction). Then size the pool from Little's law with headroom, and keep the total under what the database can run.
Chapter 8
See why a rare slow call becomes a common slow request when one request calls many servers
A search request asks 100 index servers at once and waits for all of them. Each server is fast 99 times in 100. Yet most search requests are slow. The reason is the tail: the slow end of the latency spread, measured by p99 and higher.
A parallel request is as slow as its slowest call. Call the chance that one call is slow p and the number of calls in parallel n. The chance that the whole request is slow, P, is one minus the chance that every call is fast:
P equals one minus, one minus p, to the n.
Take the chance that one call is fast, 1 minus p. Multiply it by itself n times to get the chance that all n are fast. Subtract that from 1. What is left is P, the chance at least one call is slow.
With p = 0.01 and n = 100: 0.99 to the 100 is 0.366, so P = 0.634. About 63% of requests wait for a slow call. With n = 10, P = 0.096.
This is the example in Dean and Barroso's paper "The Tail at Scale" (2013). Each server is slow 1 time in 100, a request calls 100 of them, and 63% of requests are slow.
Each dot is one server call. Red ones are slow on this request. Drag the fan-out and press Resample to draw new requests.
The curve is the formula above; the grid draws random requests with a seeded generator. Real slow calls are not fully independent, so treat the curve as a guide.
So the per-call budget must be tighter than the request budget. A request of 100 calls whose p99 must be 50 ms needs each call's p99.99 near 50 ms, since 0.9999 to the 100 is 0.99. Two fixes help. Call fewer servers on each request. Or send a hedged request: if a call is slower than its usual p95, send a copy to another server and take the first answer.
The failure. Symptom: every service's dashboard shows a good p99, yet users complain. Measure: look at p99 of the user request, not of each call. Fix: set budgets from the top down, and hedge or cut fan-out on the calls with the worst tails.
Chapter 9
Set a target for good requests, count the failures you may spend, and page when you spend them too fast
"Never fail" is not a target you can meet, and trying stops every change. Teams pick a number instead. A service level indicator (SLI) is a measured share, such as requests that succeed in under 200 ms. A service level objective (SLO) is the target for it, such as 99.9% over 30 days. The error budget is what is left: 0.1% of requests may fail.
In time, a 99.9% SLO over 30 days allows 0.001 × 30 × 24 × 60 = 43.2 minutes of full outage. In requests, 10 million requests a month allow 10,000 failures. When the budget is spent, the team stops risky launches and works on reliability.
How fast is the budget going? Call the measured share of failed requests e and the SLO target S. The burn rate B compares the failure rate with what the budget allows:
B equals e divided by one minus S.
Divide the share of requests failing now, e, by the share the SLO allows, 1 minus S. A burn rate B of 1 spends the budget in exactly the window. A burn rate of B spends it in the window divided by B.
With S = 0.999 and a bad deploy that fails e = 1.44% of requests: B = 0.0144 / 0.001 = 14.4. The 30-day budget is gone in 30 / 14.4 = 2.08 days, about 50 hours. One hour at this rate spends 14.4 / 720 = 2% of the budget.
The line is the budget left over 30 days. Pick an SLO and drag the error ratio. Find the ratio that pages someone.
The 14.4 paging threshold (2% of a 30-day budget in one hour) and the 30-day window follow the Google SRE Workbook chapter "Alerting on SLOs". The error ratios are illustrative and held constant.
The Google SRE Workbook pages a person when the burn rate over the last hour passes 14.4, and opens a ticket for slower burns over longer windows. A threshold on burn rate catches a fast outage in minutes and ignores a single stray error.
The failure. Symptom: an alert on "any 500 error" fires 50 times a day, and the on-call stops reading it. Measure: count pages that led to no action. Fix: alert on burn rate over two windows, a short one to catch fast burns and a long one for slow leaks.
Chapter 10
Keep the terms, the numbers, the checklist and the core code in one place
A backend engineer owns the time between a request and its response. The contract says what each call means and what a retry does. The data path (indexes, pagination, caches) keeps each call cheap as tables grow. The limits (rate limits, pools, timeouts) keep one caller or one slow query from hurting the rest. Budgets, percentiles and SLOs say when the system is good enough.
| Term | One line | Worked number on this page |
|---|---|---|
| Safe / idempotent | reads only / same effect once or many times (RFC 9110) | PUT twice: qty stays 3; POST twice: 2 orders |
| Idempotency key | one key per intent; the server replays the stored response | 3 lost responses, 1 charge |
| Backoff ceiling | min(cap, base × 2n), then full jitter | 100, 200, 400, 800, 1,600 ms |
| Offset cost | rows read = offset + limit | page 51 reads 1,020 rows |
| B-tree height | ceiling of log base f of N | f = 200, 10M rows: 4 pages |
| Cache read time | h × t-hit + (1 − h) × t-miss | h = 0.9: 2.9 ms, 500 DB reads/s |
| Token bucket | refill r per second up to b; one token per request | r = 10, b = 20: 620 per minute at most |
| Little's law | in progress = arrival rate × time inside | 2,000/s × 5 ms = 10 connections |
| Fan-out tail | 1 − (1 − p)n | p = 1%, n = 100: 63% |
| Burn rate | error ratio / (1 − SLO) | 1.44% at 99.9%: 14.4, budget gone in 50 h |
EXPLAIN ANALYZE on every query against production-sized data.pythonimport time, json, random class TokenBucket: # Chapter 6 def __init__(self, rate, capacity): self.r, self.b = rate, capacity self.k, self.t = capacity, time.monotonic() # start full def allow(self): now = time.monotonic() self.k = min(self.b, self.k + self.r * (now - self.t)) # k' = min(b, k + r*dt) self.t = now if self.k >= 1: self.k -= 1; return True return False # caller sends 429 + Retry-After def backoff(n, base=0.1, cap=10.0): # Chapter 2, full jitter return random.uniform(0, min(cap, base * 2 ** n)) def create_payment(db, key, body): # Chapter 2 with db.transaction(): row = db.one("SELECT body, status, response FROM idem WHERE key=%s FOR UPDATE", key) if row: if row.body != body: return 409, {"error": {"code": "key_reused"}} return row.status, json.loads(row.response) # replay, never run twice db.run("INSERT INTO idem(key, body) VALUES (%s, %s)", key, body) # key is UNIQUE pay = db.one("INSERT INTO payments(amount) VALUES (%s) RETURNING id", body["amount"]) resp = {"id": pay.id} db.run("UPDATE idem SET status=201, response=%s WHERE key=%s", json.dumps(resp), key) return 201, resp # Chapter 3 and 4: one cursor page, served by INDEX (customer_id, created_at, id) PAGE = """SELECT id, created_at, total FROM orders WHERE customer_id = %s AND (created_at, id) < (%s, %s) ORDER BY created_at DESC, id DESC LIMIT 20"""
HTTP semantics: RFC 9110 (safe and idempotent methods, 422, Retry-After), RFC 6585 (429) and RFC 5789 (PATCH). Idempotency keys: Stripe API docs. Indexes: PostgreSQL, multicolumn indexes. Backoff: Marc Brooker, Exponential Backoff and Jitter. Tails: Dean and Barroso, "The Tail at Scale", Communications of the ACM, 2013. Burn rates: the Google SRE Workbook, Alerting on SLOs.
Now press Present or Teach and explain each chapter from memory. Start with why POST needs a key and end with how fast a 14.4 burn spends a month. Then go back to the hero and say which chapter each switch belongs to.