API Rate Limiting, ETags & HTTP Caching Headers: Complete Scaling Guide

Two of the fastest ways to crash a growing API or rack up surprise cloud bills are missing HTTP caching (recomputing identical JSON responses on every page load) and missing rate limiting (letting a single runaway client loop or scraper saturate database connections). Fortunately, HTTP already includes standardized headers for caching, conditional validation, and polite throttling—and implementing both cleanly takes surprisingly little code.

In this practical backend guide, we break down Cache-Control directives, conditional ETag / 304 Not Modified validation, Vary header traps, and production rate-limiting algorithms (Fixed Window vs. Sliding Window vs. Token Bucket) alongside proper 429 Too Many Requests and Retry-After handling.

1. Mastering Cache-Control Directives (Browser vs. CDN)

Every cacheable HTTP response should declare an explicit Cache-Control header so browsers and CDNs know whether they may store a copy, for how long, and whether private user data may touch shared proxies:

DirectiveMeaningTypical Use Case
public, max-age=31536000, immutableCache for 1 year everywhere; never revalidate until URL changes.Versioned CSS/JS bundles (e.g. styles.css?v=20261203).
public, max-age=60, stale-while-revalidate=300Serve fresh for 60s, then serve stale while refreshing async.Public catalogs, changelogs, and documentation feeds.
no-cacheAllow local storage, but always revalidate via ETag before serving.Dynamic public JSON configs that must stay up to date.
private, no-storeNever write response to shared CDNs or browser disk caches.Authenticated profiles, tokens, banking, and checkout APIs.

Crucial distinction: Cache-Control: no-cache does not mean "do not store anything." It actually means "store locally, yet validate freshness with the server before serving"! To forbid caching completely on sensitive endpoints, send Cache-Control: no-store.

2. Conditional Requests: ETag & 304 Not Modified

Suppose your API serves a 150 KB JSON configuration document that updates only twice per day, while mobile apps poll it every 5 minutes. Without conditional requests, you waste 150 KB of bandwidth on every poll. With an ETag (Entity Tag—typically a fast hash of the JSON body):

  1. On the first request, the server responds 200 OK with ETag: "w/8a91f0c2" and Cache-Control: no-cache.
  2. On the next poll, the browser or client sends If-None-Match: "w/8a91f0c2".
  3. If the data has not changed, the server skips sending the 150 KB JSON body and returns an empty 304 Not Modified response (~200 bytes total)!

Express and Fastify even compute weak ETags automatically for JSON responses when enabled—saving huge mobile egress bandwidth with zero client complexity.

3. Cache Poisoning & Why Vary Headers Matter

If an endpoint returns different responses depending on request headers, CDNs need the Vary header to keep cache buckets separate:

  • Vary: Accept-Encoding: Keeps Gzip, Brotli, and uncompressed responses separated so a CDN never sends Brotli binary bytes to an old client that doesn't support Brotli.
  • Vary: Origin: Essential whenever your API echoes dynamic Access-Control-Allow-Origin headers for multiple allowed frontend domains (covered in our CORS Guide).
  • Never cache responses keyed on Authorization without private: Authenticated endpoints should always set Cache-Control: private, no-store (or include Vary: Authorization only on specialized private caches) so User A's profile is never accidentally cached and served to User B!

4. Rate Limiting Algorithms Compared

Rate limiting protects login forms from credential stuffing, shields expensive endpoints (PDF generation, search, AI inference), and enforces SaaS plan tiers:

AlgorithmHow It WorksPros & Cons
Fixed Window CounterCounts requests per fixed minute bucket (e.g. 12:00–12:01).Simplest to build; suffers boundary bursts (2x limit at 12:00:59 + 12:01:01).
Sliding Window Log / CounterTracks rolling 60-second window continuously.Eliminates boundary spikes accurately; slight extra Redis logic.
Token BucketBucket refills at steady rate R up to burst capacity B.Ideal for APIs—permits short legitimate user bursts while capping sustained rate.

5. Standard RateLimit & Retry-After Headers

When a caller stays within quota—or hits 429 Too Many Requests—never fail silently without telling them when to try again. Return clean headers alongside an RFC 9457 JSON error body:

HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json
Retry-After: 18
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 18

{
  "type": "https://techcar.online/errors/rate-limited",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "You exceeded 100 requests per minute. Retry after 18 seconds."
}

6. Distributed Sliding-Window Limiter in Node.js + Redis

In-memory JavaScript Map counters break the moment you scale beyond one Node.js worker process. Using Redis Sorted Sets (ZSET) gives accurate distributed sliding-window rate limiting across all API replicas:

export async function checkSlidingWindow(redis, clientKey, limit = 100, windowMs = 60000) {
  const now = Date.now();
  const windowStart = now - windowMs;
  const key = `rl:${clientKey}`;

  const tx = redis.multi();
  tx.zremrangebyscore(key, 0, windowStart);
  tx.zadd(key, now, `${now}-${Math.random()}`);
  tx.zcard(key);
  tx.pexpire(key, windowMs);

  const results = await tx.exec();
  const count = results[2][1];
  return {
    allowed: count <= limit,
    remaining: Math.max(0, limit - count)
  };
}

Key Design Tip: Identify authenticated users by their immutable user ID or API key hash rather than IP address alone—otherwise dozens of legitimate employees behind one shared corporate NAT or mobile carrier IP will accidentally block each other!

7. Writing Polite Client Retries With Jitter

On the frontend or SDK side, retrying a 429 or 503 immediately inside a tight while loop creates a thundering herd that keeps the server down. Always honor Retry-After first; if absent, apply exponential backoff + random jitter (wait base * 2^attempt + random(0..500ms)) and cap total attempts at 3–4 retries.

async function fetchWithBackoff(url, options = {}, maxRetries = 3) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const res = await fetch(url, options);
    if (res.status !== 429 && res.status !== 503) return res;
    if (attempt === maxRetries) return res;

    const retryHeader = Number(res.headers.get("retry-after"));
    const waitMs = Number.isFinite(retryHeader) && retryHeader > 0
      ? retryHeader * 1000
      : Math.min(1000 * 2 ** attempt, 16000) + Math.floor(Math.random() * 400);

    await new Promise((r) => setTimeout(r, waitMs));
  }
}

8. Modern Speed Trick: stale-while-revalidate

One of the most effective HTTP caching directives for fast perceived API and CDN performance is stale-while-revalidate. Setting Cache-Control: public, max-age=60, stale-while-revalidate=300 tells browsers and CDNs: serve the cached JSON immediately for 60 seconds; between 60 and 360 seconds, still serve the cached response in 5 milliseconds so the user never waits, while fetching a fresh copy asynchronously in the background for the next visitor!

9. Cache Invalidation Strategies Without Breaking Users

In computer science, cache invalidation has a famous reputation for difficulty because serving stale pricing or outdated feature flags breaks customer trust, while flushing an entire CDN cache triggers a sudden database spike. Production engineering teams combine three reliable invalidation techniques depending on how fast updates must propagate:

  • Short TTLs + ETag Validation: When data changes unpredictably—such as product inventory or live pricing—set a short max-age=30 alongside an ETag hash. Even when the 30-second window expires, unchanged resources cost almost zero bandwidth because the server answers with 304 Not Modified instead of re-transmitting the entire JSON payload.
  • Surrogate Keys (Cache Tags): Modern CDNs like Cloudflare and Fastly let origin servers attach a Cache-Tag: product-412,category-tools header on JSON responses. The moment a merchant edits Product 412 in the database, a webhook issues one targeted purge for tag product-412, evicting only affected URLs while keeping 99.9% of unrelated cached endpoints warm.
  • Immutable Content-Hashed Assets: For CSS, JavaScript bundles, icons, and WebP images, never rely on short TTLs or manual cache purges. Include a version query parameter or content hash in the filename so browsers can cache static files aggressively for an entire year while instantly picking up updates the second HTML references a new version string.

10. Designing Tiered Rate Limits & Abuse Protection

Applying one flat request cap across an entire application rarely works in practice: a search endpoint running expensive database aggregations needs much tighter throttling than a lightweight health check or static configuration endpoint. Group your API routes into explicit risk tiers:

  1. Authentication & Credential Routes (Strictest): Endpoints like login, password reset, and OTP verification should enforce aggressive per-IP and per-account limits (for example, 5 to 10 attempts per 15 minutes) to defeat brute-force credential stuffing without locking out normal users behind shared mobile carrier IPs.
  2. Expensive Compute & Export Endpoints (Medium): Endpoints generating reports, running full-text searches, or exporting bulk CSV datasets should limit both request frequency and concurrent in-flight jobs per user ID, returning 429 Too Many Requests with a clear Retry-After wait interval whenever concurrency caps saturate.
  3. Standard Authenticated Reads (Generous): Normal dashboard reads and paginated JSON queries can allow higher burst capacity via Token Bucket rules (such as 120 requests per minute with bursts up to 30 requests) so normal page navigation never triggers accidental throttling.

Finally, never forget to document your exact rate-limit headers, window reset behavior, and recommended backoff strategy inside your developer portal—and consider pairing rate limiting with query cost analysis if you expose flexible query endpoints, or validating incoming payload bounds early using JSON Schema before expensive business logic ever executes.

8. Production Caching & Throttling Checklist

  1. Set Cache-Control: private, no-store on all authenticated personal JSON endpoints and login responses.
  2. Version static CSS/JS/WebP assets with query strings or content hashes so 1-year browser caching never serves stale UI updates.
  3. Enable ETag conditional responses on large public JSON config/catalog endpoints.
  4. Apply stricter rate limits to unauthenticated high-cost routes (/login, /forgot-password, /search, /otp).
  5. Always attach Retry-After and clean JSON error bodies on 429 responses so SDKs back off gracefully.

Frequently Asked Questions

What is the difference between max-age and s-maxage?

max-age applies to both private browser caches and shared CDN caches. Adding s-maxage overrides the TTL specifically for shared CDN proxies—letting Cloudflare cache an API response for 10 minutes while browsers refresh every 30 seconds.

Should rate limits return 429 or 503?

Always return 429 Too Many Requests when a specific client exceeded their quota. Reserve 503 Service Unavailable for global server overload or planned maintenance affecting everyone.

Can CDN caching leak another user's private JWT or profile?

Yes—if an API mistakenly sends Cache-Control: public on an authenticated endpoint without Vary or cookie bypass rules! Always mark user-specific responses private, no-store.

How can I inspect response headers and JSON error payloads quickly?

Run curl -i https://your-api.example/endpoint to print raw headers, then paste any minified JSON error payload into our JSON Formatter & Validator for clean readability.