Home / Projects / Snip

Snip

A URL shortener built to stay fast under load, with the load test to prove it.

The problem

Every redirect hit the database. Under load, slow requests piled up and popular links made it worse.

The approach

Put Redis in front of PostgreSQL, cache misses as well as hits, and count clicks in memory instead of on every request.

The result300 to 13 ms

p95 redirect latency, measured with Locust.

How a redirect works

On a cache hit, a redirect is two Redis calls and never touches PostgreSQL.

Browser FastAPI4 workers in Docker Redis cache1 h TTL, misses for 60 s Click countersone HINCRBY per click PostgreSQLsource of truth only on a miss flush every 10 s

Measured results

Same laptop, same traffic: 50 simulated users for 2 minutes, 90% of requests to 200 popular links.

p95 redirect latency Throughput
MetricCache offCache on
Requests67,639147,694
p50 latency14 ms6 ms
p95 latency300 ms13 ms
Throughput568 req/s1,236 req/s
Cache hit raten/a93.3%
Locust and the API shared one laptop's CPU, so absolute numbers are higher than on a server. The comparison is what matters.

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

Integration tests24

Run against real PostgreSQL and Redis, clean state for every test.

Continuous integration

GitHub Actions runs ruff and the full test suite on every push and pull request.

Built in the open

Eight phases, each merged through its own pull request with a written description.

View the repository