Building Scalable REST APIs (Part 3): Caching, Rate Limits and Resilience
Keep REST APIs responsive under load with HTTP caching, ETags, conditional requests, rate limits, deadlines, safe retries, circuit breakers and overload protection.

A scalable API is not one that survives a benchmark when every dependency is healthy. It is one that degrades predictably when traffic spikes, a database slows down, a partner API starts timing out or thousands of clients retry at once.
Part 2 reduced the work done by each request. Now we need to control how much work reaches the system in the first place — and what happens when parts of that system cannot keep up.
The recurring principle is simple: do not allow one slow component to turn into unlimited waiting and unlimited retries everywhere else.
HTTP caching is part of API design
Caching is often treated as an infrastructure afterthought: “put Cloudflare in front of it” or “add Redis”.
HTTP already has a caching model. Using it correctly can eliminate requests before they reach your application at all.
Consider a public catalogue resource:
GET /products/sku-123
If the representation can be reused for five minutes:
HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: application/json
Browsers, gateways and shared caches can use that policy according to HTTP caching rules.
Private data needs different treatment
Do not mark personalised responses public because you want a better cache-hit ratio.
For a user-specific resource you may use:
Cache-Control: private, max-age=60
or, where storage is inappropriate:
Cache-Control: no-store
no-cache does not mean “never store this response”. It means a stored response must be validated before reuse. That distinction matters.
ETags can save bandwidth and work
A resource that rarely changes can return a validator:
ETag: "product-sku-123-v19"
The client later asks conditionally:
GET /products/sku-123
If-None-Match: "product-sku-123-v19"
If the selected representation is unchanged:
HTTP/1.1 304 Not Modified
No representation body needs to be transferred.
Validators are especially useful when a response is large or clients poll for changes.
Validators can also protect writes
The same ETag can support optimistic concurrency:
PATCH /products/sku-123
If-Match: "product-sku-123-v19"
If another writer has already changed the resource, the server can reject the stale update rather than silently losing data.
Caching and concurrency are different concerns, but HTTP validators elegantly support both.
Cache keys are correctness boundaries
A shared cache must distinguish every request characteristic that changes the representation.
If /prices/ABC returns different currencies based on a header, a cache that keys only by URL can return GBP data to a USD caller.
HTTP’s Vary header can tell caches that selected request headers affect representation selection:
Vary: Accept-Encoding, Accept-Language
But be cautious: varying on high-cardinality values can destroy cache efficiency, and caching responses that depend on authorization requires careful design.
Do not “fix” a bad cache key after it has leaked tenant data.
Distributed caches are not databases with fewer guarantees
An application cache such as Redis can remove repeated work from an origin database. It also introduces another distributed system.
For each cached value define:
- source of truth;
- key structure;
- TTL;
- invalidation mechanism;
- acceptable staleness;
- behaviour when the cache is unavailable;
- protection against stampedes.
Cache-aside is common:
request
-> cache lookup
-> hit: return
-> miss: query source -> cache -> return
The dangerous part is the miss path. If 10,000 callers miss the same hot key together, your origin sees 10,000 requests.
Use request coalescing, jittered TTLs, stale serving or proactive refresh where appropriate.
Rate limiting is not just requests per minute
A flat limit such as “100 requests/minute” is useful for some APIs, but it is a crude measure of resource consumption.
Compare:
GET /health
with:
POST /reports/full-history-export
One may cost microseconds; the other may trigger minutes of work.
Useful limits can be applied by:
- IP for unauthenticated abuse controls;
- user/account;
- API client;
- tenant;
- endpoint or operation class;
- concurrency;
- consumed units/credits;
- expensive business workflow.
The goal is to protect finite capacity fairly, not merely produce 429 responses.
Tell clients how to back off
When a limit is exceeded:
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json
Clients should not have to guess whether retrying immediately will help.
For planned or temporary unavailability, Retry-After can also be useful with appropriate service-unavailable responses.
Rate limiting cannot replace authorization
If user A can request:
GET /accounts/user-b-secret-id
and receive user B’s data, limiting A to ten such requests per minute does not solve the vulnerability.
OWASP’s API guidance continues to put object-level authorization at the top of the API risk list. Every access to a user-controlled object identifier needs the appropriate authorization decision.
Rate limits reduce abuse and resource exhaustion. They do not turn an insecure operation into a secure one.
Timeouts are capacity controls
Without deadlines, requests can accumulate behind a slow dependency until all available workers, connections or sockets are occupied.
Every remote operation should have a time budget derived from the end-to-end request budget.
If your API promises a useful response within two seconds, giving a downstream service a 30-second timeout makes no sense.
Conceptually:
client deadline: 2.0 s
API processing budget: 1.8 s
DB query budget: 0.5 s
partner call budget: 0.8 s
remaining margin: retries/serialization/network
Exact values depend on the operation, but deadlines should be deliberate.
Propagate deadlines downward
If the upstream caller has already abandoned the request, downstream work should not continue indefinitely.
Cancellation and deadlines need to flow through the call chain where protocols and libraries allow it.
Retries can multiply an outage
Imagine:
mobile client retries 3 times
API gateway retries 2 times
service A retries 3 times
service B retries database calls
One user action can become dozens of attempts against the failing component.
Retries are appropriate only when:
- the failure is plausibly transient;
- the operation is safe to repeat or protected by idempotency;
- there is enough remaining deadline;
- attempts are bounded;
- retry timing uses backoff and jitter;
- the retry layer is intentionally chosen.
Do not retry validation failures, authorization failures or every 500 by reflex.
Exponential backoff needs jitter
If 20,000 clients all retry at exactly 1, 2 and 4 seconds, they create synchronized traffic waves.
Jitter randomises retry timing so recovery load is spread out.
A simple conceptual strategy is:
base delay grows exponentially
actual delay = random value within an allowed range
Use a well-tested resilience library rather than inventing a statistically questionable retry algorithm in every service.
Circuit breakers protect failing dependencies
If a dependency is consistently failing, repeatedly calling it may waste resources and slow every request.
A circuit breaker can temporarily stop calls after a failure threshold, then allow controlled probes to determine whether the dependency has recovered.
States are commonly described as:
closed -> calls flow normally
open -> calls fail fast
half-open -> limited probes test recovery
A breaker is not a cure for every exception. Configure it around meaningful dependency failures and pair it with observability so operators know why traffic is being rejected.
Bulkheads stop one dependency consuming everything
A slow recommendation service should not consume all request concurrency needed for checkout.
Bulkhead-style isolation limits how much shared capacity one workload can occupy. This can mean separate:
- concurrency limits;
- connection pools;
- worker pools;
- queues;
- service instances;
- resource quotas.
The objective is blast-radius control.
Load shedding is better than total collapse
Once a system is saturated, accepting more work can make outcomes worse for everybody.
Rejecting some requests quickly may preserve the core service.
Strategies include:
- bounded queues;
- concurrency limits;
- admission control;
- prioritising critical operations;
- disabling optional expensive features;
- serving stale data;
- returning
429or503with useful retry guidance.
A queue with no maximum length is not resilience. It is delayed failure plus a memory problem.
Protect asynchronous queues too
Moving work to a queue does not make capacity infinite.
If requests arrive at 5,000 jobs/minute but workers process 1,000 jobs/minute, backlog grows by 4,000 jobs every minute.
Monitor:
queue depth
oldest message age
arrival rate
processing rate
failure/dead-letter rate
Oldest-message age is often more actionable than queue depth because it tells you what delay users are actually experiencing.
Apply backpressure before backlog becomes unrecoverable.
Idempotent consumers make queues survivable
Most practical messaging systems are designed around delivery semantics where a message may be delivered more than once.
A worker should be able to see the same logical command again without duplicating an irreversible side effect.
Typical techniques include:
- event/message IDs stored with processed state;
- unique database constraints;
- state-machine transitions that reject duplicates;
- idempotency records around external effects.
“The queue guarantees exactly once” is rarely a sufficient business-level design explanation.
The outbox pattern closes an ugly failure gap
Suppose a request updates the database and then publishes an event:
1. UPDATE Order SET Status = 'Paid'
2. publish OrderPaid
If the process crashes after step 1 but before step 2, the database says paid while downstream systems never hear about it.
An outbox stores the state change and event-to-publish in the same local transaction:
transaction:
update Order
insert OutboxMessage
commit
publisher:
read unsent outbox rows
publish
mark sent
Consumers still need duplicate handling because publication acknowledgement can fail after a broker accepted the message.
This is much more honest than pretending a database transaction spans arbitrary external systems.
Graceful degradation needs product decisions
Resilience is not only middleware configuration.
If recommendations are unavailable, should product pages fail entirely or render without recommendations?
If the fraud-scoring service is unavailable, should a payment fail closed, queue for review or proceed below a risk threshold?
Those are business decisions with security and financial consequences.
Write them down before the incident.
Health endpoints should mean something
A process being alive is different from being ready to receive traffic.
Useful platforms commonly distinguish:
- liveness — should the process be restarted?
- readiness — should this instance receive new traffic?
Do not make liveness depend on every remote dependency. If a shared database goes down and every application instance deliberately kills itself, you may turn a recoverable dependency outage into a restart storm.
Readiness checks should also avoid hammering dependencies at high frequency.
Resilience review checklist
For each important API operation ask:
- Can the response be cached safely?
- Is the cache policy explicit?
- Could ETag validation avoid retransferring unchanged data?
- Are personalised responses prevented from leaking through shared caches?
- Is the cache miss path safe?
- Are hot-key stampedes controlled?
- What rate/concurrency limit protects the operation?
- Is
Retry-Afteruseful to callers? - What is the end-to-end deadline?
- Are dependency timeouts shorter than that deadline?
- Which layer owns retries?
- Are retries bounded, jittered and idempotent?
- Can a failed dependency consume all capacity?
- Is queue depth bounded?
- Are queued consumers idempotent?
- Is cross-system publication durable?
- What functionality can degrade gracefully?
- Are liveness and readiness checks correctly separated?
The goal is not to eliminate failure. Distributed systems fail. The goal is to make failure contained, observable and recoverable.
What comes next
Resilience controls protect capacity, but a fast resilient API can still expose the wrong data very efficiently. Part 4 focuses on production API security: authentication, object- and property-level authorization, tenant isolation, resource consumption, SSRF, inventory, unsafe downstream APIs and the mistakes highlighted by the OWASP API Security Top 10.
