Design a URL Shortener

How to design a URL shortener in an interview, covering short-code generation, caching, click counting, and what to say about failures.

Case study30 minLesson 1 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A URL shortener takes a long link and returns a short one, such as sho.rt/008sudj. When anyone opens the short link, the service redirects them to the long one. The design has several parts that interviewers like to probe: a workload where reads far outnumber writes, a way to create unique codes on many servers without collisions, a cache that serves most of the traffic, and a database that must not lose a link once it has been created.

This case study follows the steps in A Framework for Any Design. Try each "Your turn" box before you read the section after it.

Clarify the problem

The prompt is one sentence long, so the interviewer first checks whether you ask about scope before drawing anything. Ask about features, then scale, then what must keep working when something fails.

The first five minutes
Interviewer

Design a URL shortener.

You

Users submit a long URL, get a short one back, and opening the short one redirects to the long one. Can users choose a custom alias? Do links expire? Do we need to count clicks?

Interviewer

Custom aliases are required. Links live forever unless the user sets an expiry. A click count per link is enough, and there is no need for dashboards.

You

How many links are created, and how often is each one opened?

Interviewer

About 100 million new links a month, and reads are about 100 times the writes.

You

Then the system is read-heavy and the redirect is the path to protect. I will aim for a redirect that adds under 20 ms on our side and keeps working even when link creation is down. A link that was created must never be lost. I will leave out user accounts, spam scanning and dashboards unless you want them included.

Write the agreed requirements down.

  • Functional requirements: create a short link for a long URL with an optional custom alias and expiry date, redirect a short code to its long URL, and count the clicks on each link.
  • Non-functional requirements: redirects add under 20 ms and are highly available, created links are never lost, and codes are short.
  • Out of scope: user accounts, abuse scanning and analytics dashboards.

Estimate the scale

Convert the interviewer's monthly numbers into rates per second and into bytes. A month has about 30 × 86,400 ≈ 2.6 million seconds.

  • Writes: 100 million ÷ 2.6 million ≈ 40 new links a second on average. Assuming peaks of 5 times the average, that is 200 a second.
  • Reads: 100 times the writes is 4,000 redirects a second on average and 20,000 at peak.
  • Code length: with 62 characters (0-9, a-z and A-Z), 6 characters give 626 ≈ 57 billion codes and 7 characters give 627 ≈ 3.5 trillion. Five years of writes is 6 billion links, so 7 characters leave plenty of room.
Estimate: Storage for five years

How much storage do the link records need after five years?

You know
  • 100 million new links a month
  • About 500 bytes per record (code, long URL, timestamps)
  • Nothing is deleted

Show the working
  1. 100 million × 12 months × 5 years = 6 billion links
  2. 6 × 109 × 500 B = 3 × 1012 B = 3 TB
  3. With 3 copies for durability, that is about 9 TB of disk

Estimate 3 TB (anything from 1 TB to 10 TB is a good answer)

This is too much for one machine but small for a cluster, so the data needs partitioning eventually but not on the first day.

Your turn: Define the API

Write the two endpoints with their method, path, request body and response, including the error cases.

Compare with a model answer

One endpoint creates a link (POST /api/links with the long URL and an optional alias and expiry, returning the code). The other is the redirect (GET /{code}, returning a redirect status with a Location header). The decision worth discussing is which redirect status to use.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /api/links
  body: { "long_url": "https://...", "alias": "spring-sale"?, "expires_at": "2027-01-01"? }
  201 Created   { "code": "008sudj", "short_url": "https://sho.rt/008sudj" }
  400 Bad Request   the URL is not valid
  409 Conflict      the alias is taken
 
GET /{code}
  302 Found   Location: https://the-long-url...
  404 Not Found     no such code, or it has expired

The redirect can use status 301 (moved permanently) or 302 (found). Browsers cache a 301, so repeat clicks from the same browser never reach your servers. That reduces load, but you cannot count those clicks and you cannot change the target later. A 302 is not cached, so every click comes through. The requirements include click counts, and the estimate shows that the extra traffic is small, so use 302.

Your turn: Model the data

What does one record hold, how is it looked up, and which kind of database fits?

Compare with a model answer

There is one record per code. Every read is a lookup of the row for one code, every write is an insert, and nothing needs a join. That is a key-value access pattern.

Model the data

links
code        VARCHAR(32)  PRIMARY KEY   -- "008sudj" or a custom alias such as "spring-sale"
long_url    TEXT                       -- up to 2 KB
created_at  TIMESTAMP
expires_at  TIMESTAMP NULL
clicks      BIGINT                     -- updated in batches, not on every click

The hot path looks up one row by primary key. It has no joins and no range scans, and a row never changes except for its click count. A key-value or wide-column store, such as DynamoDB or Cassandra, fits this pattern, and it partitions by key without extra work, which is what we need at 3 TB and beyond. A relational database with read replicas also works at this size, and it is a reasonable choice if the team already runs one.

Custom aliases are stored in the same table as generated codes. Because code is the primary key, an "insert if absent" operation makes alias claims safe. If two users try to claim spring-sale at the same moment, only one insert succeeds and the other receives the 409 response.

Expired links are not served, because the redirect service checks expires_at, but the rows still take up space. A background job deletes rows whose expiry time has passed, or the store's built-in time-to-live feature does it if it has one. A custom alias can also equal a code that the generator would produce later, such as an alias typed as 008sudj. The generator therefore uses the same insert-if-absent operation and takes the next number when the insert fails.

Your turn: High-level design

Sketch both paths. What sits between a browser and the database on a redirect, and where does a new code come from?

Compare with a model answer

Separate the read path from the write path so that each can scale on its own. A stateless redirect service reads through a cache in front of the store, and a create service produces the codes.

High-level design

Redirects outnumber creates by 100 to 1, so they get their own service and their own cache. Every new link needs a code that no other server will produce, so a small ID allocator gives each create server a block of numbers to use.

Reads and writes take separate paths. The redirect service reads through a cache, and the create service takes numbers from a block it reserved from the ID allocator.Browser or app to Load balancer (HTTPS); Load balancer to Redirect service (GET /{code}); Load balancer to Create service (POST /links); Redirect service to Link cache (get code); Redirect service to Links store (on miss); Create service to Links store (insert); Create service to ID allocator (next ID block).Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeID allocatorHTTPSGET /{code}POST /linksget codeon missinsertnext ID block
Reads and writes take separate paths. The redirect service reads through a cache, and the create service takes numbers from a block it reserved from the ID allocator.
Write path, then read pathUse the arrows or ← → keys
  1. Write path, then read path, step 1Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeID allocator

    1A user submits a long URL. The load balancer sends POST /api/links to any create server.

  2. Write path, then read path, step 2Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceid 125,000,017Link cacheLinks storeID allocator

    2This server reserved the numbers 125,000,000 to 125,000,999 earlier, so it takes the next unused one without asking anyone. That number is 125,000,017.

  3. Write path, then read path, step 3Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate service008sudjLink cacheLinks storeID allocator
    code
    008sudj

    3The server writes the number in base 62 and pads it to 7 characters, which gives the code 008sudj.

  4. Write path, then read path, step 4Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeinsert 008sudjID allocator
    code
    008sudj

    4The server inserts the row. The store replicates the row to other nodes before it confirms the write, so the link survives the loss of a disk.

  5. Write path, then read path, step 5Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeID allocator
    code
    008sudj

    5The short URL goes back to the user. The whole write needed one store insert and no other coordination.

  6. Write path, then read path, step 6Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeID allocator
    code
    008sudj

    6Someone opens sho.rt/008sudj. The load balancer sends the GET request to a redirect server.

  7. Write path, then read path, step 7Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cachemissLinks storeID allocator
    code
    008sudj

    7The redirect server asks the cache for the code. The link is new, so the cache does not have it.

  8. Write path, then read path, step 8Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheset 008sudjLinks storeID allocator
    code
    008sudj

    8The server reads the row by primary key and stores a copy in the cache. A link's target never changes, so the copy cannot go stale.

  9. Write path, then read path, step 9Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cacheLinks storeID allocator
    code
    008sudj
    status
    302

    9The browser receives 302 Found with the long URL in the Location header and follows it.

  10. Write path, then read path, step 10Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceLink cachehitLinks storeID allocator
    code
    008sudj
    status
    302

    10The next click on the same link is a cache hit. Most redirects end this way, which is why the store can stay small.

  11. Write path, then read path, step 11Browser or app to Load balancer; Load balancer to Redirect service; Load balancer to Create service; Redirect service to Link cache; Redirect service to Links store; Create service to Links store; Create service to ID allocator.Browser or appLoad balancerRedirect serviceCreate serviceIDs left: 982Link cacheLinks storeID allocatordown

    11If the allocator goes down, each create server keeps using the numbers left in its block. With 40 writes a second spread over 10 servers, a block of 1,000 lasts about 4 minutes, which is time to fail over.

1 / 11

Deep dives

Interviewers usually push on three parts of this design: how the codes are generated, how redirects stay fast, and how clicks are counted without slowing the redirects down.

Generating short codes

Many create servers run at once, and each must produce a code that no other server will produce, without a slow check against the database on every request. There are three common approaches.

Hashing the long URL. The server computes a hash of the URL and encodes the first 7 characters. The same URL always produces the same code, so duplicates are easy to detect. The problem is that a truncated hash collides, so every insert needs a check and a retry. If two users submit the same URL they also share one code, which means one user's deletion or expiry affects the other. This approach makes sense only when deduplication is a requirement.

Random codes with a retry. The server picks 7 random characters and inserts the row with "insert if absent". If the code already exists, it picks another. No servers need to coordinate, and the codes cannot be guessed. With 6 billion links stored out of 3.5 trillion possible codes, a new code collides with probability 6 × 109 ÷ 3.5 × 1012 ≈ 0.2%, which is about one retry in every 600 creates. Choose it when codes must not be guessable.

Counter blocks encoded in base 62. A small allocator service hands each create server a block of 1,000 consecutive numbers. The server uses the numbers one at a time, converts each to base 62 and pads it to 7 characters. Codes never collide, and each server contacts the allocator only once for every 1,000 links. The costs are that the allocator must be highly available and that the codes are sequential, so anyone can step through them. If guessability worries the interviewer, scramble each number with a reversible function before encoding it.

Ways to make a short code
OptionGood atBad atPick it when
Hash the long URLThe same URL always gets the same code, so duplicates are cheap to detect.A truncated hash collides, so every insert needs a check and a retry, and two users share one code.Use it when deduplication matters more than anything else, which is rare.
Random code, retry on collisionIt needs no coordination between servers, and the codes cannot be guessed.Every create needs an insert-if-absent, and collisions become more frequent as the table fills.Use it when codes must not be guessable.
Counter blocks in base 62 Usual defaultCodes never collide, and each server calls the allocator only once per 1,000 links.Codes are sequential unless you scramble them, and the allocator must be highly available.Use it for public links where guessable codes are acceptable.

Keeping redirects fast

A small share of links receives most of the clicks, so a cache with least-recently-used (LRU) eviction in front of the store serves most redirects in about a millisecond. Because a link's target never changes, writes do not need to invalidate anything. There are two exceptions. When a link is deleted, delete its cache key as well. And because a cached entry could outlive the link's expiry time, the redirect service checks expires_at on every redirect, so an expired link is never served from the cache. When a link suddenly goes viral, many requests can miss the cache at the same moment and reach the store together, which is the cache stampede problem described in Caching.

Counting clicks without slowing redirects

Updating a counter on every click puts a database write on the hot path. A viral link would also make one row the busiest in the database. Instead, the redirect service publishes a click event to a queue and returns the redirect immediately. A worker adds up the events for each code and writes one update per link every few seconds.

Clicks leave the redirect path as events. A worker batches them, so a link clicked 5,000 times in a minute costs only a handful of writes.Redirect service to Click events (click 008sudj), asynchronous; Click events to Counter worker, asynchronous; Counter worker to Links store (clicks += 312).Redirect serviceClick eventsCounter workerLinks storeclick 008sudjclicks += 312

request and replyasynchronous message

Clicks leave the redirect path as events. A worker batches them, so a link clicked 5,000 times in a minute costs only a handful of writes.

The trade-off to state in the interview is that the counts lag by a few seconds, and events lost from the queue make them slightly too low. That is acceptable for a click count. If clicks were billed, you would make the events durable and make the processing idempotent so that a retried event is not counted twice.

Bottlenecks and failures

At 10 times the load, the system must handle 200,000 redirects a second at peak and 30 TB of data after five years. Each part scales in a different way.

  • Redirect servers hold no state, so you add more of them.
  • The cache becomes a cluster that splits keys with consistent hashing, so adding a node moves only a small share of the keys.
  • The store is partitioned by a hash of code, so that sequential codes from the same allocator block do not all land on one partition.
  • The allocator is barely affected. Blocks of 1,000 at 2,000 writes a second mean only 2 requests a second.

The table lists what happens when each component fails and what you do about it.

Component that failsWhat happensWhat you do
A redirect or create serverRequests sent to it fail.Health checks remove it from the load balancer within seconds, and the other servers absorb its share.
A cache nodeThe keys it held are read from the store instead.Size the store for the extra reads, or run replicas of each cache node.
A store nodeOne partition loses one of its three copies.The other replicas keep serving, and the failed node is rebuilt from them.
The ID allocatorCreate servers cannot get new blocks.Servers keep working from their current blocks. Run the allocator on three nodes that agree through a consensus store so that it rarely goes down.
The click queueClick counts stop updating.Nothing changes for redirects, which is the reason counting is asynchronous.

What a strong answer sounds like

The levels differ in how much the numbers drive the design and in how well the trade-offs are argued.

LevelWhat the answer does
JuniorProposes a service and a database, builds the code from a hash of the URL, and reaches a working design after the interviewer asks about collisions.
Mid-levelEstimates traffic and storage, separates reads from writes, adds a cache and explains why, and compares two ways of making codes.
SeniorStarts from the read-to-write ratio, chooses 302 because of click counts, moves counting off the hot path, and says what fails first at 10 times the load and what the design leaves out.
Defending the choiceStrong answer
Interviewer

Why not just hash the URL?

You

A 7-character piece of a hash collides, so I would still need a check and a retry on every insert, and two users who submit the same URL would share one code. Counter blocks never collide and cost one allocator call for every thousand links. The cost is that the codes are guessable. If that matters, I would scramble each number before encoding it.

Interviewer

What happens to creates if the allocator goes down?

You

Each create server keeps using the numbers left in its block. At 40 writes a second over 10 servers, a block of 1,000 lasts about 4 minutes, which is enough time to fail over. Redirects are not affected at all.

Follow-up questions

How would you run this in several regions?

Serve redirects in every region from a local cache and a local replica of the store. Replication lag delays a brand-new link by a second or two at most. Give each region its own range of numbers so that creates never coordinate across regions.

What if the same long URL is submitted twice?

By default each submission gets its own code. Returning the same code would need an index on the long URL, and it would let one user's expiry or deletion affect another user's link. If the interviewer wants deduplication, offer it per user, so that each user gets one code for each URL.

How do you stop abuse?

Apply a rate limit to creates per API key and per IP address, and check each new URL against a blocklist of known bad domains. Scan new URLs asynchronously as well, so that a link found to be malicious later can be disabled.

Mark the row as deleted in the store and delete its key from the cache. Because the redirect is a 302, browsers have not cached it, so the next click sees the change and gets a 404.

That is about 17,000 requests a second for a single key, and all of them land on the one cache node that holds it. Each redirect server can keep a copy of that link in its own memory for a few seconds, so most requests are answered locally and the cache node is not overloaded.

Self-review: URL shortener0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure