Caching, Rate Limiting & Observability: How Systems Scale
From flash-sale crashes to resilient backends: caching, rate limits, and seeing inside distributed systems

What happens when your application suddenly gets 1 million users?
Not over three quiet years of steady growth — at 12:00 PM on a Friday during a flash sale, a concert ticket drop, or a viral product launch. The app that felt instant for 500 daily users slows to a crawl, checkout requests time out, the database CPU pins at 100%, and your team has no idea which service broke first.
Scaling a web application is rarely about one magic tool. It is a progression: fix repeated work with caching, protect your backend from overload with rate limiting, and gain visibility into what is actually happening with logging, monitoring, and observability.
Why applications need to scale
Scalability is a system's ability to handle growing load — more users, more requests per second, or more data — without degrading response times or falling over.
When traffic grows, you have two ways to add capacity:
- Vertical scaling (scale up): move the app or database onto a bigger machine with more CPU cores, RAM, and faster disks. It is fast to do and requires zero code changes, until you hit a hardware ceiling or a single machine becomes a single point of failure.
- Horizontal scaling (scale out): run multiple instances of your service behind a load balancer. You can add or remove servers as traffic rises and falls, but your app must now be stateless — no in-memory sessions or local-only files that tie a user to one machine.
Even with ten app servers, traffic spikes expose predictable bottlenecks:
- Database connection limits and lock contention: thousands of concurrent queries reading the same product page or updating the same inventory row saturate the database long before your web servers run out of CPU.
- Repeated expensive computation: recomputing recommendations, aggregations, or serialized JSON payloads on every identical request wastes CPU cycles.
- Slow downstream dependencies: one sluggish payment gateway or external API holds open worker threads or request queues until everything behind it backs up (if you work in Node.js, blocking vs non-blocking I/O shows how one slow path drags down fast ones).
Throwing bigger hardware at an uncached, unprotected architecture buys time, not resilience. Architecture decides whether a 100x traffic spike becomes a revenue milestone or an outage.
Understanding caching
During a flash sale, 100,000 shoppers might open the exact same sneaker page within ten seconds. Querying the database 100,000 times for a product description that changed once this morning is pure waste.
Caching stores the result of an expensive read or computation in a faster, closer location so future requests skip the slow path:
- Cache hit: the requested key is already in the cache. The app returns it directly in milliseconds (or sub-milliseconds in memory) without touching the database.
- Cache miss: the key is absent or expired. The app fetches the data from the database, stores a copy in the cache for subsequent callers, and returns the response.
In production, caching is not a single box. It sits at four distinct layers, from closest to the user to closest to your data:
- Browser cache: stores static assets (JS bundles, CSS, images) and cacheable API responses directly on the user's device using HTTP headers like
Cache-ControlandETag— avoiding network round-trips while fresh, or skipping full re-downloads with304 Not Modified. - CDN (Content Delivery Network) cache: edge servers geographically close to users serve static files, images, and public pages (like a product launch landing page) so that traffic never reaches your origin servers.
- Application cache (Redis or Memcached): an in-memory key-value store shared across your app servers. Ideal for hot product catalogs, user profiles, session state, and expensive computed aggregates.
- Database cache: built-in buffer pools and page caches inside PostgreSQL or MySQL that keep frequently accessed table pages and indexes in RAM instead of reading from disk.
Used together, caching slashes database load, cuts p99 latency, and lets you serve orders of magnitude more reads on the same database hardware.
Cache invalidation and advanced protection
Caching makes reads fast, but it introduces a second copy of your data. Keeping that copy accurate — cache invalidation — is where most caching bugs live.
If a store updates a concert ticket price from 50 to 75, or marks the last seat sold out, a stale cache entry can show users the wrong price or let them click "Buy" on an unavailable seat. You are always trading freshness against speed:
- Aggressive caching (long expiry) maximizes speed and database protection, but risks serving stale data.
- Tight consistency (invalidating or updating the cache on every write) keeps data fresh, but adds write complexity and race conditions when concurrent updates interleave.
Worse still is a cache stampede (thundering herd): a single hot key — say, the homepage feed or flash-sale inventory summary — expires at the exact moment 5,000 requests arrive. All 5,000 see a cache miss and slam the database simultaneously.
Production teams use six protection techniques to keep caches safe under load:
| Technique | How It Works | Problem It Solves | Main Tradeoff |
|---|---|---|---|
| TTL (Time To Live) | Attach an expiration window (e.g., 60 seconds) to every key | Bounds how long stale data can survive | Fixed expiries can trigger synchronized stampedes |
| Jitter on TTL | Add a small random offset (e.g., 60s +/- 10s) to each key's TTL | Prevents thousands of keys cached together from expiring at the exact same second | Slightly less predictable freshness window |
| Probabilistic Early Expiration | As a key nears expiry, a small fraction of requests recompute and refresh it early before TTL runs out | Hot keys get refreshed before they actually expire, avoiding stampedes | Extra logic tuned to query cost and traffic rate |
| Mutex Locking (Singleflight) | On a miss, only the first request acquires a lock to query the DB; concurrent requests wait for that result | Stops 5,000 simultaneous misses on one key from becoming 5,000 identical DB queries | Waiting requests add tail latency; lock timeouts need careful handling |
| Stale-While-Revalidate (SWR) | Serve the slightly expired cached value immediately while one background worker refreshes it | Users never block on a slow recomputation | Brief window where users still see stale data |
| Cache Warming | Pre-populate the cache with known hot keys before traffic arrives (e.g., before a flash sale opens) | Prevents a cold-start database meltdown at launch time | You must know which keys will be hot ahead of time |
No single technique fits every endpoint. Product descriptions work well with TTL + Jitter + SWR; seat inventory counts during a ticket drop need short TTLs, mutex protection, and a final authoritative check at the database during checkout.
Rate limiting and surviving traffic surges
Caching protects you from repeated reads, but it cannot stop a flood of writes, login attempts, checkout calls, or scrapers hitting uncached endpoints. That is where rate limiting comes in.
Rate limiting caps how many requests a client (identified by IP address, user ID, or API key) can make within a time window. When a caller exceeds the limit, the gateway rejects extra traffic immediately with HTTP 429 Too Many Requests and a Retry-After header before those requests ever reach your application logic or database.
Rate limiting is a protection mechanism against four real threats:
- Sudden traffic spikes: a viral launch or ticket drop where legitimate users hammer the refresh button.
- API abuse and credential stuffing: attackers brute-forcing login routes or spamming OTP endpoints.
- Bot traffic and scraping: automated scripts draining inventory or scraping catalog pages at machine speed.
- Cascading failures: when one overloaded service slows down, clients retry aggressively, multiplying traffic and knocking over every healthy service downstream. Shedding excess load early keeps the core system alive for everyone else.
Four strategies cover most real-world rate limiters:
| Strategy | How It Works | Strengths | Weaknesses |
|---|---|---|---|
| Fixed Window | Count requests per fixed time slice (e.g., 100 req/min from :00 to :59) |
Tiny memory footprint; easy to implement with a Redis counter | Boundary burst bug: 100 requests at :59 + 100 at :01 allows 200 in 2 seconds |
| Sliding Window | Tracks request timestamps or weights the previous and current windows | Eliminates boundary bursts; smooth enforcement | Higher memory or slightly more complex atomic logic |
| Token Bucket | A bucket refills at a steady rate up to a burst capacity; each request consumes one token | Allows short legitimate bursts while enforcing an average rate | Needs careful tuning of both burst size and refill rate |
| Leaky Bucket | Requests enter a fixed-size queue and drain out at a constant rate; overflow drops | Produces a smooth, predictable output rate to downstream services | Adds queueing delay; bursts do not pass through quickly |
At the architectural level, the decision is a tradeoff between burst tolerance (Token Bucket lets a normal user load a page that fires 5 parallel API calls) and strict smoothing (Leaky Bucket protects a fragile downstream database or third-party payment API that cannot tolerate bursts at all).
Here is a minimal Token Bucket in Node.js 24.22.1 with no packages: a burst capacity of 3, refilling 1 token per second, fed 5 checkout requests that arrive in the same instant:
// token-bucket.js (Node.js 24.22.1, no packages)
class TokenBucket {
constructor(capacity, refillPerSec) {
this.capacity = capacity; // burst size
this.tokens = capacity; // start full
this.refillPerSec = refillPerSec;
this.last = Date.now();
}
take() {
const now = Date.now();
// Refill for the time that passed, but never above capacity
this.tokens = Math.min(this.capacity, this.tokens + ((now - this.last) / 1000) * this.refillPerSec);
this.last = now;
if (this.tokens >= 1) {
this.tokens -= 1;
return { allowed: true, tokensLeft: Math.floor(this.tokens) };
}
return { allowed: false, retryAfterSec: Math.ceil((1 - this.tokens) / this.refillPerSec) };
}
}
const path = "/api/flash-sale/checkout";
const bucket = new TokenBucket(3, 1); // burst of 3, refills 1 token per second
// 5 checkout requests arrive in the same instant
for (let i = 1; i <= 5; i++) {
const traceId = `tr-9f4a-${i}`;
const result = bucket.take();
const log = result.allowed
? { level: "info", event: "request_allowed", traceId, path, status: 200, tokensLeft: result.tokensLeft }
: { level: "warn", event: "rate_limited", traceId, path, status: 429, retryAfterSec: result.retryAfterSec };
console.log(JSON.stringify(log));
}
Real output:
{"level":"info","event":"request_allowed","traceId":"tr-9f4a-1","path":"/api/flash-sale/checkout","status":200,"tokensLeft":2}
{"level":"info","event":"request_allowed","traceId":"tr-9f4a-2","path":"/api/flash-sale/checkout","status":200,"tokensLeft":1}
{"level":"info","event":"request_allowed","traceId":"tr-9f4a-3","path":"/api/flash-sale/checkout","status":200,"tokensLeft":0}
{"level":"warn","event":"rate_limited","traceId":"tr-9f4a-4","path":"/api/flash-sale/checkout","status":429,"retryAfterSec":1}
{"level":"warn","event":"rate_limited","traceId":"tr-9f4a-5","path":"/api/flash-sale/checkout","status":429,"retryAfterSec":1}
Notice two things in that output: requests 4 and 5 fail fast with 429 instead of piling onto the database, and every single decision emits a structured JSON record with a traceId — which brings us to visibility.
Logging, monitoring, and observability
Caching and rate limiting keep your system standing under load, but when latency suddenly doubles at 2:00 AM during a product launch, you need to know what broke and why. Teams usually build visibility in three stages: logging, monitoring, and observability.
Logging: recording discrete events
Logging writes timestamped records of events as your application runs — incoming requests, rate-limit rejections, cache misses, database errors, and authentication failures.
- Log levels separate signal from noise:
DEBUG(local diagnostics),INFO(normal lifecycle events),WARN(recoverable anomalies like a429or fallback), andERROR/FATAL(failures needing attention). - Structured logging emits machine-readable JSON (like the
request_allowedlines above) instead of free-form strings like"User 42 failed checkout". When you have 20 app servers writing millions of lines an hour, you need to filter bystatus=429ortraceId="tr-9f4a-4"in seconds. - Good logging hygiene: never log passwords, tokens, or credit card numbers; attach a request or trace ID to every log line; and keep
INFOlogs concise so log storage bills do not rival your database bill.
Monitoring: tracking known health signals
Logs tell you what happened to individual requests, but you cannot stare at raw logs to see whether the whole platform is healthy. Monitoring aggregates numerical metrics over time, displays them on dashboards, and triggers alerts when thresholds break.
For backend APIs, the Four Golden Signals from Google's SRE book (latency, traffic, errors, and saturation) catch most incidents early. They map closely onto the RED method (Rate, Errors, Duration) plus saturation:
- Rate (throughput): requests per second hitting your gateway and services.
- Errors: percentage of
5xxserver failures and429rate-limit rejections. - Duration (latency): tracked as percentiles (
p50,p95,p99), not averages — an average of 80ms can hide ap99of 4 seconds where 1 in 100 checkout users times out. - Saturation: how close CPU, memory, DB connections, or cache memory are to their ceiling.
Monitoring answers "Is the system healthy right now?" using conditions you knew to check in advance.
Observability: understanding unknown failures
Modern backends are distributed — a single checkout click might cross an API gateway, an auth service, a Redis cache, an inventory service, and a payment provider. Monitoring tells you "p99 latency on /checkout jumped from 120ms to 3.2s", and alerts page the on-call engineer. It does not always tell you why.
Observability is the property of a system that lets you ask arbitrary new questions about its internal state from the outside — without deploying new debug code.
- Logs capture what happened at a single point in code.
- Monitoring tracks whether the system is healthy against known thresholds.
- Observability connects logs, metrics, and distributed traces so you can explain why a novel failure is happening across multiple services.
Introduction to OpenTelemetry
Years ago, every observability tool (Datadog, New Relic, Honeycomb, Prometheus, Jaeger) required its own agent, client library, or export format. Switching backends meant re-instrumenting your entire codebase.
OpenTelemetry (OTel) is the open-source, vendor-neutral standard (a CNCF project) for collecting and exporting all three telemetry signals:
- Traces: follow a single user request end-to-end across services. Every request gets a shared
traceId, and each step (API gateway → Redis lookup → DB query → payment call) records a timed span. Looking at one trace immediately reveals whether a 3-second checkout spent 2.8 seconds waiting on a locked database row or an external webhook. - Metrics: counters, gauges, and latency histograms exported in a standard format.
- Logs: structured logs automatically correlated with the active
traceIdandspanId, so clicking a slow trace pulls up the exact logs emitted during that request.
In a modern stack, your application services instrument code once using the OTel SDK and send telemetry to an OpenTelemetry Collector — a standalone pipeline that batches, filters, and routes data to whatever backend you prefer (Prometheus + Grafana + Tempo/Jaeger, or a managed platform). You own your instrumentation without vendor lock-in.
Putting the scalable architecture together
Each layer we covered solves a distinct failure mode, and they reinforce one another when wired into one request lifecycle:
Trace a 1-million-user flash sale through that diagram:
- CDN and edge cache absorb static assets and public catalog pages before traffic ever touches your servers.
- API gateway and rate limiter shed bots and abusive bursts with
429responses so downstream services stay within safe capacity. - Load balancer + stateless app servers spread allowed requests horizontally across machines.
- Distributed cache (Redis) — protected with TTL jitter, mutex locking, and pre-sale cache warming — serves hot reads in milliseconds so the database handles writes and true misses without collapsing.
- OpenTelemetry + monitoring stream latency percentiles, error rates, cache hit ratios, and distributed traces continuously so your team spots a rising
p99or a sudden drop in cache hit rate minutes before users feel an outage.
Scalability is not a single feature you bolt on the night before launch — it is the combination of doing less repeated work (caching), bounding the work you accept (rate limiting), and seeing clearly when assumptions break (observability).
One honest tradeoff to keep in mind: every layer you add introduces operational complexity, extra network hops, and new failure modes (a misconfigured rate limiter can block real paying customers, and a dead Redis cluster can turn into a database outage if your app has no fallback). Start simple, measure real bottlenecks with observability first, and add each layer when your traffic actually earns it.
If your own app suddenly got 100x traffic tomorrow, which layer would break first — your database, your rate limits, or your visibility into what is failing?
Comments
Join the discussionNo comments yet. Be the first to comment.



