Home/Guides/Reliability Engineering

HTTP 429 Rate Limits, Exponential Backoff & Edge Caching Math for Public APIs

Turn a 60 req/min free public API into a 50,000-DAU production dashboard using Cache-Control, ETag 304 revalidation, jittered retries, and response coalescing.

11 min read·Updated: 2026-12-02·7 verified primary sources

Quick Takeaways

  • Under shared edge caching with TTL T seconds across K active normalized keys, steady-state upstream traffic is bounded by K / T requests per second—completely decoupled from total user traffic R.
  • Deterministic exponential backoff (1s, 2s, 4s, 8s) fails under load because stalled clients wake up in synchronized spikes; Full Random Backoff (sleep = random(0, min(cap, base * 2^attempt))) combined with honoring Retry-After spreads retry waves cleanly and slashes peak origin collisions by over 80%.
  • Conditional revalidation with ETag and If-None-Match shrinks a 20 KB JSON response to a ~300-byte HTTP 304 Not Modified reply (98.5% wire-byte reduction), and major APIs such as GitHub REST explicitly deduct zero rate-limit quota on 304 hits.
  • Cache key cardinality kills hit ratios faster than short TTLs: rounding raw GPS coordinates to two decimal places (~1.1 km) and sorting query parameters shrinks urban weather keys by up to 250x without noticeable UX loss.
  • In a worked 50,000-DAU dashboard model (225,000 requests/day; 781.25 req/min peak against a 60 req/min free cap), exact Poisson occupancy math proves a flat 10-minute TTL still breaches the limit at 80.2 req/min, whereas tiered TTLs (10m/30m/60m) + cache shielding + coalescing cap peak origin traffic at 38.4 req/min (95.08% peak hit ratio) for $5/month.

1. Anatomy of HTTP 429, Retry-After & Rate-Limit Algorithms

RFC 6585 defines HTTP 429 Too Many Requests as the standard signal that a client has exceeded an upstream provider's rate quota within a given window. Unlike generic 500 Internal Server Error responses, a well-behaved 429 reply carries actionable metadata: a Retry-After header (specified either as integer delta-seconds such as Retry-After: 42 or as an HTTP-date timestamp) plus quota status headers such as the legacy X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset (Unix epoch seconds) or the newer IETF draft RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset (delta seconds).

Why do applications frequently receive 429 errors even when their average daily request rate sits well below the documented limit? The root cause is almost always algorithm mismatch against micro-bursts. Four enforcement algorithms dominate public REST APIs: Fixed Window counters reset abruptly on the clock boundary (allowing 2x bursts across a boundary, then hard-blocking the entire remaining minute); Sliding Window counters smooth boundary spikes over rolling 60-second or 3,600-second windows; Token Buckets allow controlled short bursts up to bucket capacity while refilling steadily; and Leaky Buckets enforce strict constant spacing—meaning a burst of 10 simultaneous calls to a 1 req/sec endpoint like OpenStreetMap Nominatim or MusicBrainz fails immediately on requests 2 through 10.

Inspecting both the numeric ceiling and the underlying window type prevents subtle production surprises. For example, GitHub REST publishes an explicit X-RateLimit-Reset timestamp on primary hourly limits plus a separate secondary concurrent-request limiter that returns Retry-After even when X-RateLimit-Remaining is still positive. CoinGecko Public v3 dynamically tightens its 10–30 req/min ceiling under global load. Reading these headers proactively in your edge proxy lets you slow background refresh jobs when remaining quota drops below 15%—long before interactive user traffic sees an error.

Table 1 — Rate-Limit Algorithms, Quota Headers & Burst Behavior Across Major Public APIs
Enforcement ModelPublic API ExamplesTypical Quota HeadersShort Burst TolerancePrimary Production Failure Trap
Fixed Window (Hourly)GitHub REST, NASA, USDAX-RateLimit-Limit / Remaining / ResetHigh until limit exhaustedExhausting full hour in 2 min leaves 58 min dry
Sliding Window (Minute)CoinGecko Public, openFDA, OpenAQRetry-After, X-RateLimit-RemainingLow to moderateCron jobs firing at :00 second spike past 1-min cap
Token Bucket (Multi-tier)TVmaze (20/10s), Deezer (50/5s), ScryfallRetry-After (seconds)Medium up to bucket sizeUnthrottled Promise.all() drains bucket instantly
Strict Spacing / Leaky BucketNominatim (1/s), MusicBrainz (1/s), Open Trivia (1/5s)Retry-After or 429/503Near zero (1 concurrent)Parallel page-load requests fail immediately
Dual Primary + SecondaryGitHub REST, SEC EDGAR (10/s)X-RateLimit-Reset + Retry-AfterLow on rapid concurrencyHitting secondary limit while hourly quota looks full

2. Exponential Backoff, Random Spread & Retry Budgets

When an upstream public API returns HTTP 429, 502, 503, or 504, naive retry loops make outages dramatically worse. Retrying immediately inside a while loop multiplies traffic by 5x–10x on an already overloaded endpoint, often escalating a temporary 429 throttle into a multi-hour IP ban. Deterministic exponential backoff—waiting base * 2^attempt (for example, 500 ms, 1,000 ms, 2,000 ms, 4,000 ms)—reduces overall retry frequency, yet still exhibits a dangerous synchronization flaw: if 500 requests fail at t = 0.0 s during a brief upstream hiccup, all 500 clients wake up simultaneously at t = 0.5 s, collide again, and retry together at t = 1.5 s and t = 3.5 s.

The classic AWS Architecture analysis of backoff strategies proves why randomizing the sleep window outperforms deterministic schedules. Full Random Backoff (often termed 'Full Jitter' in English literature) computes sleepMs = Math.random() * Math.min(capMs, baseMs * 2 ** attempt). Instead of clustering all 500 waiting requests onto a single millisecond boundary, Full Random Backoff smears retries uniformly across the entire interval—reducing peak simultaneous arrival density by more than 80% while actually finishing sooner on average because early slots succeed instead of waiting idle. Equal Random Backoff—sleepMs = (window / 2) + Math.random() * (window / 2)—guarantees a minimum cooling period when upstream servers strictly enforce minimum inter-request gaps.

Four engineering rules complete a safe retry policy. First, always inspect Retry-After before running your backoff math: if the server tells you Retry-After: 8, respect that value (plus a small 100–500 ms random offset), but cap maximum interactive wait at your endpoint SLA (for example, never block a web user for Retry-After: 3600—return stale cached JSON or a fast fallback instead). Second, retry ONLY transient status codes (429, 408, 502, 503, 504) and network timeouts—never retry 400 Bad Request, 401 Unauthorized, 403 Forbidden, or 404 Not Found. Third, retry only safe read methods (GET, HEAD) or write operations designed to produce the same outcome if repeated. Fourth, enforce a hard retry budget: max 3 attempts, max 6–8 seconds total elapsed wall time per interactive request, and a client-side concurrency queue so retries never pile up faster than completions.

Table 2 — Backoff Delay Schedules & Peak Collision Density (base = 500 ms, cap = 16,000 ms, 500 Stalled Clients)
Retry StrategyAttempt 1 DelayAttempt 2 DelayAttempt 3 DelayAttempt 4 DelayPeak 100 ms Arrival Spike (500 Clients)
Fixed 1,000 ms Interval1,000 ms1,000 ms1,000 ms1,000 ms~500 req / 100 ms (severe sync wave)
Deterministic Exponential500 ms1,000 ms2,000 ms4,000 ms~500 req / 100 ms (synchronized spikes)
Equal Random Backoff250–500 ms500–1,000 ms1,000–2,000 ms2,000–4,000 ms~25–100 req / 100 ms (75%–90% lower)
Full Random Backoff (Recommended)0–500 ms0–1,000 ms0–2,000 ms0–4,000 ms~12–50 req / 100 ms (80%–95% lower)
Retry-After + 0–500 ms Random OffsetHeader + 0–500 msHeader + 0–500 msAbort if > SLA capServe stale cacheRespects upstream window; ~100 req / 100 ms

3. HTTP Caching Math: s-maxage, stale-while-revalidate & ETag 304 Savings

Retries only rescue you after a limit has already been hit; shared HTTP caching (RFC 9111) prevents you from hitting the limit in the first place. The governing equation of shared edge caching is remarkably clean: if your application queries K distinct normalized cache keys and stores each entry in a shared cache with fresh TTL T seconds, the maximum steady-state origin request rate is K / T requests per second—no matter whether 100 users or 1,000,000 users visit your page. For instance, 120 currency/weather keys cached for T = 600 seconds produce at most 120 / 600 = 0.20 origin requests per second (12 req/min), easily fitting inside a strict 60 req/min free API cap.

Four Cache-Control directives work together to separate user-perceived speed from upstream quota protection. max-age controls private browser caching (e.g., max-age=60 so clicking Back/Forward costs zero network requests). s-maxage overrides max-age exclusively for shared CDN and edge proxies (e.g., s-maxage=300 pools all visitors behind one origin fetch every five minutes). stale-while-revalidate (RFC 5861, e.g., stale-while-revalidate=600) instructs the cache to serve the slightly expired JSON immediately in ~25 ms while refreshing from the origin asynchronously in the background—eliminating tail-latency spikes when cache entries expire. stale-if-error (e.g., stale-if-error=3600) serves the last known valid response for up to an hour whenever the public upstream throws HTTP 429, 500, 502, or 503.

When an entry finally revalidates, conditional HTTP requests via ETag + If-None-Match (or Last-Modified + If-Modified-Since) multiply savings even further. Instead of transferring a fresh 20 KB JSON body every refresh cycle, the edge cache sends the stored ETag token. If upstream data has not changed, the origin replies with HTTP 304 Not Modified carrying ~300 bytes of headers and zero body—a 98.5% wire-byte reduction. Better still, several high-value public APIs (notably GitHub REST) explicitly exclude 304 responses from counting against your hourly quota. Table 3 models 100,000 daily user lookups across 250 active keys for a 20 KB JSON payload across five caching configurations.

Table 3 — Daily Origin Requests, Transfer Bandwidth & P95 Latency (100,000 Req/Day, 250 Active Keys, 20 KB JSON)
Cache Layer ConfigurationDaily Origin RequestsCache Hit RatioDaily Origin TransferTransfer SavingsP95 End-User Latency
1. No Caching (direct fetch)100,000 full 2000.0%2,000.0 MB (2.00 GB)0.0%260 ms
2. Browser max-age=60s only (20% repeat)80,000 full 20020.0%1,600.0 MB (1.60 GB)20.0%235 ms
3. Shared Edge s-maxage=300s (32 active windows)8,000 full 20092.0%160.0 MB92.0%240 ms (expiry spikes)
4. Edge s-maxage=300s + SWR=600s8,000 full 20092.0%160.0 MB92.0%29 ms (async refresh)
5. Edge + SWR + ETag 304 (75% unchanged)2,000 full 200 + 6,000 30492.0% hit / 98.0% full cut41.8 MB97.9%26 ms

4. Cache Key Normalization, Request Coalescing & Negative Caching

Even a perfectly tuned Cache-Control header delivers dismal hit ratios if your cache key cardinality K grows unbounded. Look at how easily real frontend traffic fragments a shared cache: HTML5 navigator.geolocation returns 7-decimal latitude and longitude values (such as 35.6762194, 139.6503112), giving every person walking down the same Tokyo street a distinct cache key; user-filtered URLs pass ?to=USD&from=EUR in one tab and ?from=EUR&to=USD in another; and marketing links append ?utm_source=x or cache-busting timestamps. Because origin rate scales directly as K / T, letting K grow 100x silently multiplies your origin bill and 429 rate by 100x.

Four normalization steps keep K compact before checking the cache. First, quantize continuous spatial coordinates: rounding latitude and longitude to 2 decimal places maps every location onto a ~1.1 km grid—more than accurate enough for local weather or air quality while compressing 100,000 metro GPS readings down to roughly 400 shared keys (a 250x reduction). Second, sort all allowed query parameter names alphabetically, normalize currency/country codes to uppercase, and drop every unrecognized parameter before constructing the cache key. Third, fetch a compact shared base payload (for example, EUR base rates against all 30 currencies in one cached Frankfurter call) and compute cross-pairs like GBP→JPY in memory on the edge instead of caching 30 × 29 = 870 separate currency-pair URLs.

Two complementary protections close the remaining concurrency gaps. First, enable in-flight request coalescing (also called request collapsing or single-flight deduplication): if a popular cache key expires while 180 users request it within the same 150-millisecond window, the edge proxy holds 179 listeners on the single active upstream Promise and fans out one shared response instead of firing 180 redundant origin calls. Second, apply short negative caching (30–60 seconds) to deterministic 404 Not Found responses—for example, misspelled ticker symbols or non-existent postal codes—so a broken external link or bot crawl cannot bypass cache and burn through your free API quota.

Table 4 — Cache Key Normalization & Cardinality Reduction Impact Across Common Public API Inputs
Input DimensionRaw Unnormalized Key SpaceNormalized Canonical KeyCardinality ReductionOrigin Traffic Impact
GPS Coordinates (Weather)100,000 raw 7-decimal floats / metro2-decimal grid (~1.1 km): ~400 keys250x smallerCuts peak weather misses by >99%
FX Currency Pairs (30 ISO)870 directed pairs (from/to)1 base=EUR table + edge cross-math870x smaller1 origin call/window serves all 870 pairs
Query Param Ordering & UTM12–50 permutations per URLSorted allowlist params, strip utm_*12x–50x smallerEliminates duplicate cache fragments
Case & Whitespace (Search)'Tokyo', 'tokyo ', 'TOKYO'Lowercase, trimmed, single-space3x–8x smallerUnifies mobile & desktop search keys
Invalid IDs / 404 LookupsUnbounded broken links / botsNegative cache 404 for 60sCaps repeats to 1/minPrevents 404 bursts burning free quota

5. Worked Numeric Case Study: Scaling a 60 req/min Free API to 50,000 DAU

Can a free public REST API capped at 60 requests per minute (1.0 req/sec steady, 86,400 req/day maximum) reliably power a 50,000-DAU production dashboard? Let us solve the exact numbers end to bottom without hand-waving. Suppose each of 50,000 daily active users triggers an average of 4.5 dashboard refreshes per day, generating 225,000 total API calls/day (6,750,000 calls/month). Daily average demand is 225,000 / 1,440 = 156.25 req/min (2.60 req/sec)—already 2.6x above the 60 req/min cap. During the evening peak hour (5x daily average), incoming demand spikes to 781.25 req/min (13.02 req/sec), exceeding the free rate limit by 13.0x.

Traffic follows a realistic Zipf curve across 1,500 normalized daily keys (after coordinate/parameter canonicalization): Tier A (Hot) has the top 100 keys receiving 80% of traffic (180,000 req/day; peak 625.0 req/min); Tier B (Warm) has the next 400 keys receiving 15% of traffic (33,750 req/day; peak 117.2 req/min); Tier C (Long Tail) has the remaining 1,000 keys receiving 5% of traffic (11,250 req/day; peak 39.1 req/min). We deploy a single upper-tier regional cache shield (such as Cloudflare Tiered Cache) with in-flight request coalescing so every unique key refreshes at most once per TTL window T minutes. Under Poisson arrivals at per-key rate λ_k, the exact peak origin miss rate is K × (1 - e^(-λ_k × T)) / T.

Step 1 — Why a Naive Flat 10-Minute TTL Still Fails: Plugging a uniform T = 10 minutes (s-maxage=600) into the exact formula reveals a hidden trap that rough averages miss. During peak hour: Tier A produces 100 × (1 - e^(-62.5)) / 10 = 10.0 req/min; Tier B produces 400 × (1 - e^(-2.93)) / 10 = 37.9 req/min; Tier C produces 1,000 × (1 - e^(-0.391)) / 10 = 32.3 req/min. Combined peak origin rate = 10.0 + 37.9 + 32.3 = 80.2 req/min—which STILL breaches the 60 req/min free cap by 33.7% and triggers evening 429 outages!

Step 2 — Tiered TTLs + SWR + ETag 304 Solves Peak Load Cleanly: Keep hot Tier A fresh at T = 10 minutes (s-maxage=600, stale-while-revalidate=600), extend warm Tier B to T = 30 minutes (s-maxage=1800, SWR=900), and extend long-tail Tier C to T = 60 minutes (s-maxage=3600, SWR=1800), with stale-if-error=3600 across all tiers. Recomputing exact peak miss rates: Tier A stays at 10.0 req/min; Tier B drops from 37.9 to 400 × (1 - e^(-8.79)) / 30 = 13.3 req/min; Tier C drops from 32.3 to 1,000 × (1 - e^(-2.34)) / 60 = 15.1 req/min. Combined peak origin load drops to exactly 38.4 req/min—36.0% safely below the 60 req/min cap (95.08% peak cache hit ratio)!

Step 3 — Daily Quota, Bandwidth & Cost Verification: Across a full 24-hour day, combined origin calls equal 14,400 (Tier A) + 15,890 (Tier B) + 8,981 (Tier C) = 39,271 origin calls/day (82.55% daily hit ratio across 225,000 user calls). For a 20 KB JSON payload, raw uncached daily egress would be 4.50 GB/day (135.0 GB/month). Caching cuts that to 785.42 MB/day, and when 70% of revalidations return 300-byte ETag 304 responses (11,781 full 200s + 27,490 304s), daily origin transfer plunges to 243.87 MB/day (7.32 GB/month)—a 94.58% bandwidth reduction (and on 304-exempt APIs like GitHub, only 11,781 quota-counted calls/day). Total edge infrastructure cost on Cloudflare Workers Paid is $5/month (covering 10,000,000 monthly requests vs our 6,750,000 requests/month), compared with $149–$299/month for a commercial 1,000 req/min API upgrade—saving $144–$294/month ($1,728–$3,528/year).

6. Production Quota-Protection & Monitoring Checklist

Turning cache math into year-round uptime requires six concrete operational habits. First, always enable a regional cache shield (tiered cache) in front of your upstream public API: without a shield, 200 global CDN PoPs independently expire the same key and multiply your origin traffic by up to 200x, instantly destroying carefully calculated TTL budgets. Second, isolate interactive user traffic from background batch scripts by reserving at least 40% of your upstream quota exclusively for live user misses and pacing scheduled sync workers with an explicit token bucket.

Third, wire every upstream response through header telemetry—logging HTTP status distribution (200 vs 304 vs 429 vs 5xx), cache hit ratio, and minimum observed X-RateLimit-Remaining—and fire an alert whenever edge cache hit ratio dips below 88% (which almost always signals an accidental query parameter leak expanding K). Fourth, set hard timeouts (AbortSignal.timeout(4000)) plus stale-if-error fallback so a slow public server never hangs page renders. Fifth, persist a daily snapshot of critical static/daily reference JSON in object storage (R2/S3) as a cold backup if a free provider suffers multi-hour maintenance. Sixth, re-audit upstream rate-limit documentation every quarter, because public providers adjust free ceilings as traffic grows.

Frequently Asked Questions

Should I retry immediately when an API returns HTTP 429 Too Many Requests?

Never retry immediately in a tight loop. Check the Retry-After response header first; if present, wait at least that duration plus a small 100–500 ms random delay (up to your UX timeout cap). If no Retry-After header is returned, use Full Random Backoff (0 to min(cap, base * 2^attempt)) with a maximum of 3 attempts.

Why does adding random delay beat plain exponential backoff (1s, 2s, 4s)?

When hundreds of requests fail together during a rate-limit window boundary, plain exponential backoff makes every waiting client retry at the exact same second—re-triggering HTTP 429 in synchronized waves. Randomizing across the interval (Full Random Backoff) spreads retries smoothly, cutting peak collision density by 80%–95% and lowering total recovery time.

Do HTTP 304 Not Modified responses count against public API rate limits?

It depends on the provider, so always verify in official docs. GitHub REST explicitly guarantees that 304 Not Modified conditional responses deduct zero quota from your 60/hr or 5,000/hr bucket. Even on providers that do count 304 calls toward request totals, ETag revalidation still saves 95%–99% of response payload transfer bytes and speeds up origin handling.

What is the difference between max-age, s-maxage, stale-while-revalidate, and stale-if-error?

max-age sets freshness for both browsers and proxies; s-maxage overrides it for shared CDN/edge caches only; stale-while-revalidate allows the cache to serve an expired response immediately while fetching an update asynchronously in the background; and stale-if-error lets the cache continue serving the last valid payload when the origin fails with 429 or 5xx.

Why did my CDN cache hit ratio stay low even though I set s-maxage=600?

Three causes explain 95% of low hit ratios: (1) unnormalized cache keys (raw high-precision GPS floats, unsorted query strings, or utm_* parameters inflating K), (2) lack of a regional cache shield (allowing 100+ edge PoPs to miss independently), and (3) forwarded browser Cookie or Authorization headers causing the CDN to mark responses uncacheable.

How does in-flight request coalescing prevent rate-limit spikes when a popular cache entry expires?

Without coalescing, 200 simultaneous visitors requesting a just-expired hot key all trigger separate upstream HTTP calls during the 150 ms fetch window. Coalescing tracks active upstream Promises by canonical cache key in memory so only the first miss calls the origin while the remaining 199 await and share that exact same response.

Should I cache HTTP 404 or 429 error responses at the edge?

Cache deterministic 404 Not Found responses briefly (30–60 seconds) so broken links or bots cannot hammer your upstream quota, but NEVER cache HTTP 429 or 5xx error responses as fresh objects—instead serve stale-if-error last-known-good data when available, or return a non-cached transient error JSON with Retry-After.

Official Sources & References