Every redirect hit the database. Under load, slow requests piled up and popular links made it worse.
Put Redis in front of PostgreSQL, cache misses as well as hits, and count clicks in memory instead of on every request.
p95 redirect latency, measured with Locust.
How a redirect works
On a cache hit, a redirect is two Redis calls and never touches PostgreSQL.
Measured results
Same laptop, same traffic: 50 simulated users for 2 minutes, 90% of requests to 200 popular links.
| Metric | Cache off | Cache on |
|---|---|---|
| Requests | 67,639 | 147,694 |
| p50 latency | 14 ms | 6 ms |
| p95 latency | 300 ms | 13 ms |
| Throughput | 568 req/s | 1,236 req/s |
| Cache hit rate | n/a | 93.3% |
Design decisions
302, not 301
Browsers cache a 301 forever, which would skip click counting and make links impossible to expire.
Random base62 codes
Seven characters give 3.5 trillion codes. Random rather than sequential, so links can't be guessed by counting.
Negative caching
Unknown codes are cached as "not found" for 60 seconds, so scans for random codes can't hammer the database.
A bug it caused
A code visited before it existed kept returning 404 for a minute after creation. Creating a link now clears its cache entry.
Batched clicks
Clicks go into a Redis hash and reach PostgreSQL in one UPDATE every 10 seconds. Trade-off: up to 10 s of clicks lost if Redis crashes.
Rate limiting
10 link creations per IP per minute with a fixed window. Redirects are never limited.
Quality
Run against real PostgreSQL and Redis, clean state for every test.
GitHub Actions runs ruff and the full test suite on every push and pull request.
Eight phases, each merged through its own pull request with a written description.