Skip to content

Design a URL Shortener

A system design interview walkthrough for a URL shortener like TinyURL or Bitly, from key generation to caching, redirects, analytics and abuse.

Intermediate23 minUpdated 2 December 2026

Before this: Back-of-the-envelope Estimations, Caching

"Design a URL shortener" is the most common opening question in system design interviews, and it is often the first one a candidate gets wrong by making it too easy.

The product fits on a napkin: turn a long URL into a short one, and send anyone who opens the short one to the long one. What the interviewer is testing is everything behind that napkin. How do you hand out billions of unique keys without a bottleneck? What does a 100:1 read ratio do to your design? And what happens when someone shortens a phishing link?

We will work it the way you should in the room: clarify, estimate, define the API and data, draw the design, then go deep where the real decisions are.

Clarify the requirements

Functional requirements:

  1. Given a long URL, return a short URL.
  2. Opening the short URL redirects to the long URL.
  3. Optionally, a user picks a custom alias (sho.rt/launch-day).
  4. Links can expire.
  5. The owner can see how many times a link was opened.

Out of scope, said aloud so you protect your time: editing a link's target, link previews, QR codes, team workspaces.

Non-functional requirements: these decide the architecture.

  • Redirects must be fast: under 50 ms at the server, because a redirect is pure overhead between the user and the page they wanted.
  • Redirects must be highly available. A broken short link breaks every place it was ever pasted: emails, printed posters, other sites.
  • Short keys must be unique, forever. Two long URLs must never share a key, and a key must never be reused, even after its link expires, or an old poster starts sending people somewhere new.
  • Keys should not be guessable in order. If abc124 follows abc123, anyone can walk the whole table and read every link people shortened, including the private ones.

Estimate the scale

Assume 100 million new links a month and a read-to-write ratio of 100:1, which is typical: a link is created once and clicked many times.

Writes: 100M ÷ (30 × 86,400 s) ≈ 40 new links per second, perhaps 150 per second at peak.

Reads: 100 × 40 = 4,000 redirects per second on average, and 15,000 to 20,000 per second at peak.

Storage: keep links for five years: 100M × 12 × 5 = 6 billion links. At about 500 bytes each (long URL, key, owner, timestamps), that is roughly 3 TB.

Key length: with the 62 characters [a-zA-Z0-9], six characters give 62⁶ ≈ 57 billion keys and seven give 62⁷ ≈ 3.5 trillion. Six would hold our 6 billion links, but seven leaves room for growth and for burning keys we never hand out.

Cache: about 345 million redirects a day. If the hottest 20% of links take most of the traffic, caching them takes 345M × 0.2 × 500 bytes ≈ 35 GB, which fits in one cache cluster's memory.

Now say what the numbers mean, which is the part that earns credit:

"40 writes per second is tiny, so the write path is not where this gets hard. 4,000 to 20,000 reads per second, against data that almost never changes, makes this a caching problem. 3 TB is big but not huge. The hard part is generating unique, non-sequential keys without making every write wait on one counter."

You can change these assumptions and watch the numbers move in the capacity estimator.

API and data model

POST /v1/links          { longUrl, alias?, expiresAt? }  -> { key, shortUrl }
GET  /{key}                                              -> 302 Location: longUrl
GET  /v1/links/{key}/stats                               -> { clicks, byDay[] }
DELETE /v1/links/{key}

The redirect is a plain GET on the key. Every other route sits under /v1/ so it can never collide with a key.

The data is one table, looked up by its key and nothing else:

links  (key PK, long_url, owner_id, created_at, expires_at)

Clicks are not a column on this row. Incrementing a counter on every redirect would turn the read path into a write path. Clicks go somewhere else, as we will see.

High-level design

The redirect path is the one worth running: a load balancer, a stateless API fleet, a cache in front of the link store, and read replicas behind it.

Redirects pass a load balancer to a stateless API fleet that reads the link cache first and falls back to the link store and its read replicas.clientslbredirect apilink cachelink store
Redirects pass a load balancer to a stateless API fleet that reads the link cache first and falls back to the link store and its read replicas.
  • Clients reach the redirect API through a load balancer.
  • The API reads the link cache, and on a miss reads the link store's replicas.
Describe this diagram

Components

  • clients (Client)
  • lb (Load balancer)
  • redirect api (Service)
  • link cache (Redis)
  • link store (PostgreSQL)

Connections

  • clients sends to lb
  • lb sends to redirect api
  • redirect api sends to link cache
  • redirect api sends to link store

Run it, then try turning the cache off or doubling the load. The link store is the part that suffers first.

The write path: the API takes a long URL, gets a fresh key (next section), writes one row and returns the short URL. At 40 writes per second, a single primary handles this comfortably.

The read path: the API looks the key up in the cache, falls back to a read replica on a miss, fills the cache, and answers with a redirect. Links are almost never edited, so a cached entry can live for hours.

The interesting problem: generating keys

Everything above is standard. Key generation is where interviewers spend their time, and there are three classic answers.

Approach A: hash the long URL

Take MD5 or SHA-256 of the long URL, base62-encode it and keep the first seven characters.

Good: no coordination. Any server can compute a key alone.

Bad: truncating a hash creates collisions, so every write has to check whether the key is taken and retry with a salt if it is. The birthday bound makes this real: among 3.5 trillion possible keys, you expect your first collision after only about 2 million links. Hashing also gives the same key for the same URL, which is wrong when two users want separate links with separate stats.

Approach B: a counter, base62-encoded

Keep a global counter. Each new link takes the next number, and its key is that number in base62: 125 becomes 21, and even the 3.5 trillionth link needs only seven characters.

Good: no collisions, ever, and the keys are as short as they can be.

Bad: a single counter is a single point of failure and a single point of contention. The keys are also sequential, so anyone can enumerate every link in the system.

Approach C: hand out ranges, then scramble

Fix both problems of B:

  • Ranges remove the contention. A small coordination service (one database row, or ZooKeeper) hands each API server a block of 10,000 numbers at a time. The server spends its block from memory and only asks again when it runs out. One coordination call per 10,000 links is nothing. If a server crashes mid-block, the unused numbers are simply lost, and with 3.5 trillion keys we can afford that.
  • A scramble removes the enumeration. Before encoding, pass the number through a reversible permutation of the key space, such as a small Feistel network or multiplication by a large odd number modulo 62⁷. Consecutive counters now produce keys that look random, and because the permutation is a bijection, they still never collide.
Conceptual diagramblock of 10,000Range serviceAPI serverNext number in blockReversible scrambleBase62 encode7-character key
Diagram, as text
  • Range service leads to API server (block of 10,000)
  • API server leads to Next number in block
  • Next number in block leads to Reversible scramble
  • Reversible scramble leads to Base62 encode
  • Base62 encode leads to 7-character key

This is the answer to aim for. The reasoning matters more than the mechanism: you removed coordination from the hot path and kept the uniqueness guarantee.

The second decision: which redirect

The redirect status code looks like a detail. It is a product decision.

  • 301 Moved Permanently: browsers and proxies may cache it, so a returning visitor skips your servers entirely. Cheaper, but you never see those clicks, and you can't change or expire the link for anyone who has cached it.
  • 302 Found: nothing caches it by default, so every click reaches you. More load, but accurate analytics and working expiry.

A shortener that sells analytics uses 302. Say that you chose it because of the analytics requirement, and that a 301 would cut load if analytics were dropped.

Counting clicks without slowing redirects

Don't write a counter row on every redirect. Instead, the API publishes a small click event (key, time, country, referrer) to a queue and redirects at once. A stream consumer aggregates the events into per-link, per-day counts in a separate store. The redirect stays a read, and analytics can lag a few seconds without anyone noticing.

Bottlenecks and failures

Hot links. A link shared by a celebrity can take a large share of all traffic. The cache absorbs it, but a single cache node holding that key can saturate. Replicate hot keys across nodes, or keep a short-lived in-process cache on each API server for the top few thousand keys.

Cache misses on new links. A link is usually clicked right after it is created, before any cache has it. Write it into the cache when you create it.

The link store. 3 TB on one primary is workable, but replicas carry the read load and give you failover. If the data outgrows one machine, partition by key: lookups are always by key, so any key-based partitioning spreads the load evenly.

Expired links. Don't scan the table for expired rows on the read path. Check expires_at when you serve a redirect, return 410 Gone if it has passed, and delete expired rows in a background job.

Abuse. Shorteners are a favorite tool for hiding phishing and malware links. Check every new long URL against a reputation service such as Google Safe Browsing, rate-limit creation per user and per IP, and keep a way to disable a key instantly, which is one more reason to prefer 302.

What if the range service is down? Servers keep spending the blocks they already hold. With 10,000 numbers per block, an outage of minutes goes unnoticed.

Trade-offs to name aloud

  • 302 over 301: more load in exchange for analytics and control.
  • Range allocation over hashing: a small coordination service in exchange for no collision checks and the shortest possible keys.
  • Lost numbers are fine: a crashed server wastes part of a block, which is cheaper than making allocation durable.
  • Eventually consistent analytics: click counts lag by seconds so that redirects never wait on a write.

What interviewers listen for

  • A working answer: a table keyed by short code, a hash or counter for keys, a cache in front.
  • A strong answer: reasons from the 100:1 ratio to a cache-first design, explains why truncated hashes collide, and removes the counter from the hot path with ranges.
  • A standout answer: also raises enumeration and fixes it with a reversible scramble, treats 301 versus 302 as a product choice, keeps analytics off the redirect path and brings up abuse without being asked.

Check your understanding

Common mistakes

Starting with the database schema. The schema is one table. Spending ten minutes on it signals that you don't know where the problem is hard.

Making the redirect write. Updating a click counter row on every redirect turns a cache-friendly read into a contended write. Clicks are events, aggregated elsewhere.

One global counter with no plan for it. "Use an auto-increment ID" is fine as a first step only if you immediately explain how you remove it as a bottleneck and a single point of failure.

Forgetting key reuse. Recycling the keys of expired links seems efficient and is a real bug: old emails and posters start pointing at someone else's page.

Ignoring abuse. Every public shortener is used for phishing within days of launch. A design without a scan, a rate limit and a kill switch is not production-ready.

Practice

A marketing customer will shorten 50 million links in a single day for a campaign, ten times your normal daily volume. Walk through what breaks in your design and what you change.

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Look at each part of the write path separately: key generation, the database write and the cache fill.

Show a strong answer

Key generation holds. 50 million links over a day is under 600 per second. With blocks of 10,000, the range service sees about one request every 17 seconds. Nothing changes, though you might give this customer's servers larger blocks.

The primary database is the real question. 600 inserts per second is still well within one Postgres or DynamoDB table, so no sharding is needed for one day. If the campaign runs as a burst of minutes rather than a day, put a queue in front of the inserts and accept the links asynchronously.

The cache fill is the trap. Writing 50 million new links into the cache evicts the links everyone else is clicking. Either skip the write-through for bulk-created links or give the campaign its own cache space, and let its links fill the cache on first click.

The pattern worth keeping: a 10x spike in writes rarely breaks a read-heavy system where you expect. Check what the writes do to the shared cache.

The interviewer asks you to run the shortener in three regions so redirects are fast everywhere. What changes?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Separate the read path from the write path, and think about where a key's uniqueness is decided.

Show a strong answer

Reads replicate easily. Each region gets its own API fleet, cache and read replica of the link store. Links almost never change, so asynchronous replication with a few seconds of lag is fine. The one exception is a link clicked seconds after creation in another region: fall back to the home region on a miss.

Writes need one source of truth for uniqueness. Give each region its own slice of the number space, for example one region holds counters starting 0, one starting 1 trillion, one starting 2 trillion. Each region can then allocate ranges with no cross-region coordination, and keys still never collide.

Custom aliases are the hard part. Two users in different regions can ask for launch-day at the same moment. Send alias creation to one home region (a strongly consistent write), and accept the extra latency on that rare path.

The pattern worth keeping: split the number space so each region owns its own, and only send the rare operation that needs global agreement across regions.

Key takeaways

  • The 100:1 read ratio makes this a caching problem. Estimate first, or you won't know that.
  • Key generation is the core. Hashing collides, a single counter bottlenecks, and range allocation with a reversible scramble solves both.
  • Never reuse a key, even after its link expires.
  • 302 over 301 when you need analytics or the ability to disable a link.
  • Keep the redirect a pure read: clicks are events, aggregated off the hot path.
  • Plan for abuse from the first version: scanning, rate limits and a kill switch.

Further reading

  • Flickr engineering blog, "Ticket Servers: Distributed Unique Primary Keys on the Cheap" (2010): unique IDs from two database servers with interleaved auto-increments.
  • Ryan King (Twitter engineering), "Announcing Snowflake" (2010): time-ordered unique IDs without coordination on every ID.
  • R. Fielding, M. Nottingham and J. Reschke, RFC 9110 "HTTP Semantics" (2022), sections 15.4.2 and 15.4.3: the exact caching rules for 301 and 302.
  • Google, Safe Browsing API documentation: checking submitted URLs against known phishing and malware lists.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track