URL Shortener System Design
A TinyURL / Bitly-style link shortening service
By Ankur NayakReviewed
Turn long URLs into short, unique codes and redirect billions of clicks with single-digit-millisecond latency. A read-heavy system built around a key-value store, a cache and a collision-free ID generator.
Open in Studio· edit a copy- Users
- 100M monthly users
- Throughput
- ~40K redirects/s peak
- Storage
- ~6 TB over 5 years
- Read:write ratio
- 100:1
- New links / month
- 100M
- Code length
- 7 chars
Requirements
Functional
- Create a short link for any valid long URL
- Redirect a short link to its original URL
- Optional custom aliases and expiry dates
- Click analytics per link (count, referrer, country)
Non-functional
- Redirect latency under 10 ms at the server (p99 under 50 ms)
- 99.99% availability for redirects; creation can be slightly less available
- Codes must never collide and should be hard to enumerate
- Scale horizontally for a 100:1 read-heavy workload
In depth
Start from the numbers
A URL shortener is the classic warm-up problem because almost every decision follows from one number: reads outnumber writes by about 100 to 1. With 100 million new links a month, that is roughly 40 creations per second on average but thousands of redirects per second, peaking in the tens of thousands. Storage is small: even five years of links at about 500 bytes each fits in a few terabytes.
So the design optimises one thing above all: turning a short code into a long URL as fast and as reliably as possible.
Generating codes without collisions
The interesting part is minting codes. Hashing the long URL and truncating it to seven characters is tempting, but truncated hashes collide, so every write needs a read-and-retry. A cleaner approach is a counter encoded in base62: the number 125 becomes cb, and seven characters cover about 3.5 trillion numbers.
A single global counter would be a bottleneck, so each API server asks a coordinator for a range of numbers, say a million at a time, and counts through it in memory. Servers never collide and only talk to the coordinator once per range. If the coordinator goes down, servers keep working until their ranges run out. See unique ID generation for alternatives like Snowflake IDs.
The read path
A redirect is a single key lookup: code → long URL. A small cache in front of a partitioned key-value store absorbs most requests, because link popularity follows a power law: a few links get most of the clicks. The redirect service then answers with a 302 so the browser comes back on every click and analytics stay accurate.
Analytics must never slow the redirect, so each click is published to a message queue and aggregated asynchronously.
What interviewers look for
- Back-of-the-envelope estimates that justify the choices
- A collision-free code strategy, and why
- Separating the read path from the write path
- Caching, and what happens when the cache is cold
- 301 vs. 302, expiry, custom aliases and abuse prevention
Components
Browser / App
Client. A user creating a link or clicking a short link.
Load Balancer
L7 / HTTPSLoad balancer. Terminates TLS and spreads requests across stateless API and redirect servers.
Building block: Load Balancer
Shorten API
Stateless serviceService. Validates the long URL, obtains a unique ID, encodes it in base62 and stores the mapping.
Why: Stateless, so it scales horizontally behind the load balancer; the only coordination is fetching an ID range now and then.
Building block: Unique ID Generation
URL Validator
Service. Normalises the URL and rejects malformed or blocklisted targets.
Range Allocator
ZooKeeperCoordination. Hands each API server a block of numeric IDs (e.g. 1M at a time) so servers never collide.
Building block: Unique ID Generation
Local Counter
Service. Counts through the server's current range in memory.
Base62 Encoder
Service. Turns the integer into a 7-character code using [0-9a-zA-Z].
Redirect Service
Stateless serviceService. Looks up the short code and answers with an HTTP 301 or 302 to the original URL.
Why: Kept separate from writes so the hot read path stays tiny and scales independently.
URL Cache
RedisCache. Holds hot code → URL mappings so most redirects never touch the database.
Why: Link popularity follows a power law, so a small LRU cache absorbs most reads.
Building block: Cache, Consistent Hashing
URL Store
DynamoDB / CassandraNoSQL database. Durable key-value store of code → { long URL, owner, created, expiry }.
Why: Single-key lookups with no joins fit a partitioned key-value store; the short code is a natural partition key.
Building block: Database Sharding, Replication
Click Events
KafkaStream. Redirects emit click events asynchronously so analytics never slows a redirect.
Building block: Message Queue & Event Log
Analytics Workers
Stream processorWorker. Aggregate clicks per link, referrer and country into a reporting store.
Analytics Store
Columnar DBData warehouse. Pre-aggregated click counts served to the link owner's dashboard.
Request flows
User clicks a short link
- The browser requests the short URL over HTTPS.
- The load balancer routes GET /{code} to any redirect server.
- The redirect server looks the code up in Redis; most lookups hit.
- On a miss it reads the URL store and fills the cache for next time.
- A click event is published asynchronously for analytics.
- The client receives a 302 with the original URL and follows it.
User creates a short link
- The user submits a long URL with POST /urls.
- The load balancer forwards the write to any Shorten API server.
- The server takes the next ID from its pre-allocated range, encodes it in base62 and stores code → URL.
- It returns the new short code.
- The user receives the short link, ready to share.
Failure scenarios
What if: cache cluster goes down?
Every redirect falls through to the URL store, multiplying its read load until the cache is warm again.
User impact: Higher redirect latency; possible throttling if the store is not provisioned for the full read rate.
- Replicate the cache across availability zones
- Coalesce concurrent misses for the same code
- Provision the store for a cold-cache read rate
Trade-offs
Hash vs. counter-based codes
Pre-allocated numeric ranges encoded in base62.
- Pros
- No collisions and no read-before-write
- Short, fixed-length codes
- Cons
- Sequential codes are guessable unless the ID is shuffled first
- Needs a coordinator for ranges
Alternatives: Truncated MD5/SHA-256 of the URL with a collision check; Random 7-character codes with a conditional insert
301 vs. 302 redirects
302 (temporary) by default so every click is counted.
- Pros
- Accurate analytics
- Links can be edited or expired
- Cons
- Every click reaches the service
Alternatives: 301 for links where analytics don't matter, to save load
Key-value store vs. relational database
A partitioned key-value store keyed by short code.
- Pros
- Predictable single-digit-ms lookups at any size
- Easy horizontal scaling
- Cons
- Queries like 'all links by user' need a secondary index
Frequently asked questions
How long should a short code be?
Seven base62 characters give about 3.5 trillion combinations. At 100 million new links a month that lasts for thousands of years, so seven is a comfortable default; six (about 57 billion) also works for smaller services.
How do you avoid two servers generating the same code?
Give each server its own block of numbers from a coordinator, such as ZooKeeper or a database counter, and let it count through the block locally. Blocks never overlap, so codes never collide, and the coordinator is contacted only once per block.
Should a URL shortener use a 301 or 302 redirect?
Use 302 if you need click analytics or might change the destination, because browsers re-request the short link every time. Use 301 if you only care about load, because browsers cache permanent redirects.
How do you stop people from guessing other short links?
Don't expose raw sequential numbers: shuffle the ID with a reversible bijection or block cipher before base62-encoding, or use random codes with a uniqueness check. Rate limiting lookups also makes enumeration impractical.
Building blocks used
Sources
- System Design Primer: Design Pastebin.com (or Bit.ly) · GitHub
- Snowflake (2010 release) · Twitter (GitHub)
- Dynamo: Amazon's Highly Available Key-value Store · SOSP