Ankit KanojiyaAdvanced
Evergreen guide by Ankit Kanojiya · Advanced · Backend
Building Resilient APIs: Rate Limiting, Retries, Idempotency, and Circuit Breakers
Four patterns that keep APIs stable under load and partial failure: rate limiting, safe retries, idempotency, and circuit breakers, with the trade-offs of each.
- Resilience
- Rate Limiting
- Retries
- Idempotency
- Circuit Breaker
- Reliability
Resilience is the ability to keep working, or to fail gracefully, when dependencies misbehave. A healthy-looking service can still take down a whole system if it retries blindly, lacks backpressure, or duplicates side effects. These four patterns, used together, turn fragile call chains into stable ones.
Rate Limiting and Backpressure
Rate limiting protects a service from being overwhelmed, whether by an abusive client, a buggy loop, or a legitimate traffic spike. It is a form of backpressure: the server tells callers to slow down rather than collapsing.
Two algorithms are common.
- The token bucket refills tokens at a steady rate and allows short bursts up to the bucket size. It is flexible and widely used.
- The sliding window counts requests over a moving interval and smooths out the boundary spikes that fixed windows suffer from.
Communicate limits clearly so clients can adapt.
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
Rate limit per principal, not just per IP, since many users can share an address and one user can span many addresses. Place limits at the edge for coarse protection and inside critical services for fine protection of scarce resources such as a database connection pool.
Retries Done Safely
Retries recover from transient faults such as a dropped packet or a brief restart. Done carelessly, they amplify outages: a struggling dependency receives a flood of retries exactly when it is least able to cope.
Safe retries follow a few rules.
- Retry only idempotent or clearly safe operations.
- Retry only transient errors: timeouts, connection resets,
503, and429. Never retry a400or422; the input will not improve. - Use exponential backoff with jitter so clients do not retry in lockstep.
- Cap the number of attempts and the total time budget.
async function withRetry(fn, max = 4) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= max || !isTransient(err)) throw err;
const base = 2 ** attempt * 100;
const jitter = Math.random() * base;
await sleep(base + jitter);
}
}
}
Jitter matters more than it looks. Without it, thousands of clients that failed at the same instant retry at the same instant, producing the synchronized thundering herd that backoff was meant to prevent.
Idempotency Makes Retries Safe
Retries are only safe if repeating an operation is harmless. Reads are naturally idempotent. Writes are not, which is why creation endpoints need explicit idempotency.
The standard approach is an idempotency key supplied by the client.
POST /payments
Idempotency-Key: 7c0b2a1d-4e5f-9f1c-2b7a-5e2a4a1e9f3d
On first receipt, the server processes the request and stores the response against the key. On a replay, it returns the stored response without repeating the side effect. The key must be stored atomically with the effect, often in the same transaction, so a crash cannot leave the effect done but the key unrecorded. Keys should expire after a reasonable window to bound storage.
Idempotency and retries are a pair: retries provide recovery, idempotency provides safety, and neither is complete alone.
Circuit Breakers
When a dependency is truly down, continuing to call it wastes resources and ties up threads waiting for timeouts. A circuit breaker detects sustained failure and stops calls for a while, failing fast instead.
The breaker has three states.
- Closed: calls flow normally while failures stay below a threshold.
- Open: the failure threshold is crossed, so calls are rejected immediately for a cooldown period.
- Half-open: after the cooldown, a few trial calls are allowed. Success closes the breaker; failure reopens it.
Failing fast has two benefits. It frees the caller's resources that would otherwise block on timeouts, and it gives the struggling dependency room to recover instead of being hammered. Pair a breaker with a fallback where possible: serve stale cached data, a default value, or a clear degraded response rather than a hard error.
Timeouts and Bulkheads
Two supporting patterns make the others work. Every outbound call needs an aggressive timeout; without one, a slow dependency exhausts the caller's thread or connection pool and the failure spreads. Bulkheads isolate resources so that one slow dependency cannot consume the capacity needed by others, much as compartments stop a ship from flooding entirely.
Putting It Together
These patterns compose into a layered defense.
- Timeouts bound how long any call can hang.
- Retries with backoff and jitter recover from transient faults.
- Idempotency keys make those retries safe.
- Circuit breakers stop calls to a dependency that is genuinely down.
- Rate limiting and bulkheads protect the service from overload and isolate failures.
Each pattern has a cost: rate limits can reject valid traffic, retries add latency and load, idempotency adds storage and complexity, and breakers can trip too eagerly if tuned poorly. Measure real failure behavior, set thresholds from data rather than guesses, and test the system under induced failure so the resilience is proven rather than assumed.