Backend & API Engineer

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.

Fit one request in its budget

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

What a Backend Engineer Builds

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.

PartWhat you buildWhat goes wrong without it
The contractendpoints, methods, status codes, error bodiesclients guess, and retries create duplicates
The data pathtables, indexes, pagination, cachesfast at 1,000 rows, unusable at 10 million
The limitsrate limits, connection pools, timeoutsone caller's loop takes down every caller
The numberslatency budgets, percentiles, capacity plansthe average looks fine while 1 in 100 users waits seconds
The promiseSLOs, error budgets, alertseither 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.

Trace one request

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.

The road

  1. The API contract: methods, status codes and error bodies (the hero's request line).
  2. Retries and idempotency keys: send a request twice, charge once.
  3. Pagination: offset against cursor on a list that moves.
  4. Database indexes: the hero's Index switch, 300 ms to 2 ms.
  5. Caching: the hero's Cache switch, hit rate and stampedes.
  6. Rate limiting: the token bucket and its burst.
  7. Capacity: connection pools, Little's law and the queue that explodes.
  8. Latency budgets and tails: why p99 matters when you call many servers.
  9. SLOs and error budgets: how much failure you may spend.
  10. The field guide: numbers, checklist, code and links.
A read endpoint has a 50 ms budget. A trace shows load balancer 2, gateway 3, handler 10, cache 1, database 20 and serialize 2 ms. Which stage should you work on first if the budget drops to 30 ms?

Chapter 1

The API Contract

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.

Resources and methods

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.

Send it twice

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.

Status codes and errors

CodeMeaningUse it when
201 Createda new resource existsa POST created it; send its id
202 Acceptedwork started, not donea long job; send a job id to poll
400 / 422bad syntax / valid syntax, wrong contenta field is missing / a value is out of range
401 / 403who are you? / you may notno valid key / the key lacks the scope
409 Conflictclashes with current statea version mismatch or a reused key with a new body
429Too Many Requests (RFC 6585)a rate limit; add Retry-After
503Service Unavailableoverloaded; 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.

A client's connection drops before it reads the response. Which request can it resend with no extra protection?

Chapter 2

Retries and Idempotency Keys

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.

  1. The client makes a random key (a UUID) and sends it with the POST.
  2. The server takes a lock on the key. If the key has a stored response, it returns that response.
  3. Otherwise it runs the work, stores the status and body under the key, then replies.
  4. If the same key arrives with a different body, the server returns an error.

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.

Spacing the retries

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:

Say it aloud

w-n equals the minimum of cap and base times two to the n.

wn
w-n the longest wait before retry n, in milliseconds.
min
the minimum of take the smaller of the two values, so the wait never passes the cap.
cap
cap the longest wait you ever allow, here 10,000 ms.
base
base the first wait, here 100 ms.
2n
two to the n 2 multiplied by itself n times, so the wait doubles on each retry.
In plain words

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 numbers

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.

Retry a lost payment

Each tick on the timeline is one attempt. The first responses are lost. Turn the key on or off and press Send.

3

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.

With base 100 ms and cap 10,000 ms, what is the longest wait before retry 3 (counting from 0)?

Chapter 3

Pagination That Holds Still

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.

Insert rows between two pages

The list is newest first, 8 rows per page. Page 1 is already shown. Add new orders, then fetch page 2 each way.

3

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:

Say it aloud

R equals o plus l.

R
R the rows the database reads to answer one offset page.
o
o the offset: rows skipped, equal to the page size times the pages already read.
l
l the limit: rows returned on the page, here 20.
In plain words

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 numbers

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.

A page size is 20. How many rows does the database read to serve page 51 with offset pagination?

Chapter 4

Database Indexes

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:

Say it aloud

h equals the ceiling of log base f of N.

h
h the height: tree pages read to find one key.
⌈ ⌉
the ceiling of round up to the next whole number, since you cannot read part of a page.
logf
log base f how many times you multiply f by itself to reach N.
N
N the number of rows in the table.
In plain words

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 numbers

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.

Grow the table, count the pages

The index is on (customer_id, created_at). Pick a query and drag the table size. The bars use a log scale.

10M

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.

An index exists on (customer_id, created_at). Which query can it NOT narrow well?

Chapter 5

Caching

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:

Say it aloud

T equals h times t-hit, plus one minus h times t-miss.

T
T the average time of one read, in milliseconds.
h
h the hit rate: the share of reads the cache answers, from 0 to 1.
thit
t-hit the time of a cache hit, here 1 ms.
tmiss
t-miss the time of a miss, which goes to the database, here 20 ms.
In plain words

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 numbers

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.

The stampede

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.

Expire the hot key

Drag the hit rate and watch the database bar. Then press Expire and count the queries that reach the database.

90%

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.

At 5,000 reads per second, the hit rate rises from 90% to 99%. What happens to database reads per second?

Chapter 6

Rate Limiting

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:

Say it aloud

k-prime equals the minimum of b, and k plus r times delta-t.

k′
k-prime the tokens after the refill, before this request takes one.
min
the minimum of the smaller value wins, so the bucket never overflows.
b
b the capacity: the largest burst a caller may send at once.
k
k the tokens left after the last request.
r
r the refill rate: tokens added per second, the steady rate allowed.
Δt
delta-t the seconds since the last refill.
In plain words

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 numbers

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.

Drain the bucket

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.

5 /s
10

Illustrative rates. The bucket runs in this page in real time, the same code as the field guide's TokenBucket.

Other shapes, and where to count

ShapeHow it countsWeak spot
Fixed windowone counter per clock minute600 at 12:00:59 and 600 at 12:01:00 is 1,200 in 2 seconds
Sliding window counterthis minute's count plus the last minute's, weighted by overlapan estimate; 25% into the minute, 600 last minute and 100 now count as 600 × 0.75 + 100 = 550
Token buckettokens refilled by elapsed timea 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).

A token bucket has r = 10 per second and b = 20. It is full. How many requests can a caller send in the next 10 seconds?

Chapter 7

Capacity: Pools and Queues

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:

Say it aloud

L equals lambda times W.

L
L the average number of queries in progress, so the connections in use.
λ
lambda the arrival rate: queries per second.
W
W the time one query holds a connection, in seconds.
In plain words

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 numbers

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.

Fill the pool

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.

2,000
5 ms
20

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.

An API sends 4,000 queries per second to PostgreSQL, and each holds a connection for 5 ms. About how many connections are in use on average?

Chapter 8

Latency Budgets and Tails

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:

Say it aloud

P equals one minus, one minus p, to the n.

P
capital P the chance that the whole request is slow.
(1 − p)
one minus p the chance that one call is fast; p is the chance it is slow.
n
to the n multiply by itself once per call, n calls in parallel, assumed independent.
In plain words

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 numbers

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.

Fan out one request

Each dot is one server call. Red ones are slow on this request. Drag the fan-out and press Resample to draw new requests.

100

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.

One call is slow 1 time in 100. A request makes 10 calls in parallel. About how often is the request slow?

Chapter 9

SLOs and Error Budgets

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:

Say it aloud

B equals e divided by one minus S.

B
B the burn rate: how many times faster than allowed the budget is being spent.
e
e the measured error ratio: failed requests over all requests, in a recent window.
(1 − S)
one minus S the error budget as a ratio; S is the SLO target, such as 0.999.
In plain words

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 numbers

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.

Burn 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.

1.44%

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.

The SLO is 99.9% over 30 days. For the last hour, 0.5% of requests failed. What is the burn rate, and when does the budget run out if it continues?

Chapter 10

The Field Guide

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.

Terms and numbers

TermOne lineWorked number on this page
Safe / idempotentreads only / same effect once or many times (RFC 9110)PUT twice: qty stays 3; POST twice: 2 orders
Idempotency keyone key per intent; the server replays the stored response3 lost responses, 1 charge
Backoff ceilingmin(cap, base × 2n), then full jitter100, 200, 400, 800, 1,600 ms
Offset costrows read = offset + limitpage 51 reads 1,020 rows
B-tree heightceiling of log base f of Nf = 200, 10M rows: 4 pages
Cache read timeh × t-hit + (1 − h) × t-missh = 0.9: 2.9 ms, 500 DB reads/s
Token bucketrefill r per second up to b; one token per requestr = 10, b = 20: 620 per minute at most
Little's lawin progress = arrival rate × time inside2,000/s × 5 ms = 10 connections
Fan-out tail1 − (1 − p)np = 1%, n = 100: 63%
Burn rateerror ratio / (1 − SLO)1.44% at 99.9%: 14.4, budget gone in 50 h

Checklist for a new endpoint

  1. Name the resource and pick the method by what a retry must do.
  2. Accept an idempotency key on every POST that creates or charges.
  3. Validate input and reject bad values with a 422 that names the field.
  4. Page lists with a cursor on a unique sort key.
  5. Run EXPLAIN ANALYZE on every query against production-sized data.
  6. Decide what the cache may hold, for how long, and which writes delete which keys.
  7. Set a rate limit, a statement timeout and a pool size from Little's law.
  8. Give the endpoint a latency budget and an SLO, and alert on burn rate.

The core as code

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"""

Keep going

Sources

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.

The takeaway. Make every write safe to retry, every list stable, every query an index walk, every hot read a cache hit, every caller bounded, and every pool sized by Little's law. Then measure the tail, not the average, and spend the error budget on purpose.
p50 is fine, p99 doubles at peak hours, and the pool's "waiting for a connection" count rises. Which fix should come first?

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.

Backend & API Engineer at Scale
RFC 9110 · PostgreSQL indexes · SRE Workbook · Back to Gleams