Book a 30-min callBook a call

System design: a URL shortener (keys, redirects, caching and abuse)

How to design a URL shortener: sizing, base62 and other key schemes, 301 vs 302 redirects, caching, sharding, click analytics, abuse checks and expiry.

A short code box with an arrow into a cache circle and a database cylinder, then a curved redirect arrow to a long URL box, with a dashed side arrow from the code box to a small analytics queue.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
20 min read

Questions people ask

Should a URL shortener use 301 or 302 redirects?

Use 302 (or 307) with Cache-Control: private, no-store if you need click analytics or the ability to edit, disable or expire links, because every visit then reaches your server. RFC 9110 makes 301 and 308 heuristically cacheable, so a cache may store them and skip your server on later visits. Use 301 with an explicit max-age only for links that will never change and need no counting.

How long should short codes be?

Base62 gives 56.8 billion keys at 6 characters and 3.52 trillion at 7. Six characters can be enough for a counter-based scheme, which never collides. For random keys, choose 7 or more so that most inserts never collide, and keep a unique index with a retry for the ones that do.

Can I hash the long URL to get the short code?

You can, but truncating a hash to a few characters makes collisions likely at scale, so you still need a unique index and a fallback such as rehashing with a salt. Hashing also maps one URL to one code, which conflicts with per-owner links, separate stats and different expiry times for the same destination.

How do I stop people from shortening malicious links?

Check destinations against threat lists such as Google Web Risk or Safe Browsing (for non-commercial use) when a link is created and again later, rate limit creation per account and IP, refuse non-HTTP schemes and links to other shorteners, show a warning page for suspicious links, and block quickly on reports in both the store and the cache.

Should the same long URL always get the same short code?

Usually not. Different owners want their own links, stats, expiry and the right to delete without affecting anyone else. Deduplicate per owner if you want to avoid duplicates in one account, by looking up the owner and URL before creating a new link.

Building something like this?