Design a URL Shortener
Understanding the Problem
🔗 What is a URL shortener? A URL shortener like bit.ly takes a long URL and gives back a short one, such as
short.ly/x7Kp2Qa. Anyone who opens the short link is redirected to the original. It's used wherever long links are awkward: social posts, SMS, printed material, QR codes. The service does two things: hand out short codes that are guaranteed unique, and turn each click into a redirect as fast as possible.
You may also be asked to design Pastebin. It's the same problem with a different payload: instead of storing a URL behind each short code, you store a block of text, and instead of redirecting, you show it. We'll design the URL shortener and cover what changes for Pastebin along the way.
Functional Requirements
Core Requirements
- Users should be able to submit a long URL and get back a short URL.
- Users should be able to choose a custom alias (
short.ly/summer-sale) and an optional expiration time. - Anyone opening a short URL should be redirected to the original URL.
- (Pastebin) Users should be able to upload a block of text and get a short link that displays it.
Below the line (out of scope)
- User accounts, link management dashboards and editing links after creation.
- Detailed click analytics. We'll note where they plug in.
- Spam and malware detection beyond a sentence.
Non-Functional Requirements
Ask your interviewer about the read/write ratio and how long links live. For our design: 10M new short URLs per day, 1B redirects per day, and links kept for up to 10 years unless they expire sooner.
Core Requirements
- Short codes must be unique: two long URLs must never get the same code.
- Redirects should be fast: under 100ms end to end, with the service itself adding only a few milliseconds.
- Redirects should be highly available. A dead redirect service breaks every link anyone has ever shared.
- Short codes should be as short as possible while giving us enough room for 10 years of links.
Below the line (out of scope)
- Strong consistency between creating a link and its first redirect across regions. A second of delay is fine.
The math is quick and settles a few choices:
- Writes: 10M per day is about 115 per second. That's tiny.
- Reads: 1B per day is about 11,600 per second on average. Traffic is bursty (a celebrity posts a link), so plan for a peak of around 5x, ~60,000 per second.
- Total links: 10M × 365 × 10 is about 36.5 billion over ten years.
- Code length: with base62 (
a-z,A-Z,0-9), 6 characters give 62^6 ≈ 56.8 billion codes, and 7 give 62^7 ≈ 3.5 trillion. Six would work but would be two-thirds used; we'll use 7 for headroom. - Storage: about 500 bytes per link (the long URL dominates, plus code, timestamps, owner) gives 36.5B × 500B ≈ 18TB over ten years. More than one database node, but nothing exotic.
So this is a read-heavy system with a 100:1 ratio, and the reads are skewed: a small fraction of links gets most of the clicks. That points straight at caching.
Writes are 115 per second. Don't spend your interview scaling the write path. Spend it on unique code generation (correctness) and the redirect path (latency and availability).
The Set Up
Planning the Approach
We'll build the create path and the redirect path, add custom aliases and expiry, then cover Pastebin. The deep dives handle code generation, fast redirects, storage at 36 billion rows, and expiry and abuse.
Defining the Core Entities
- Link: a short code, the long URL it points to, an optional expiry time, a creation time and an optional owner.
- Paste (Pastebin): a short code, a pointer to the stored text, a size, a content type and an optional expiry.
- User: optional; whoever created the link, for rate limiting and management.
API or System Interface
POST /links
{ longUrl, customAlias?, expiresAt? }
-> 201 { shortUrl: "https://short.ly/x7Kp2Qa" }
-> 409 alias already taken
GET /{code}
-> 302 Location: <longUrl>
-> 404 not found or expired
// Pastebin
POST /pastes { content, expiresAt?, syntax? } -> 201 { url }
GET /{code} -> 200 text
High-Level Design
1) Users should be able to submit a long URL and get a short URL
The create path is a Link Service behind a load balancer and a database. On POST /links, the service validates the URL (well-formed, http or https, not pointing at our own domain to avoid redirect loops), generates a short code, stores the mapping and returns the short URL.
The obvious first idea for the code is to hash the long URL (MD5 or SHA-256) and take the first 7 base62 characters. It's simple and the same URL always maps to the same code. But truncating a hash to 42 bits means collisions: with billions of links, two different URLs will share a 7-character prefix, and we'd need to detect that and retry with a salt. That works, but there's a cleaner approach, which we'll get to in deep dive 1. For now, assume a generateCode() that returns something unique.
The table is a simple key-value shape:
CREATE TABLE links (
code VARCHAR(16) PRIMARY KEY,
long_url TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP,
owner_id BIGINT
);
Should the same long URL always return the same code? It's tempting, but it needs a second index on long_url (large and costly at 36B rows) and it leaks information between users (anyone can find out whether a URL has been shortened). Most shorteners give each request a new code. Ask your interviewer, and default to not deduplicating.
2) Users should be able to choose a custom alias and an expiry
A custom alias is just a user-chosen code. The service checks it against a list of reserved words (api, admin, login) and inserts it with a conditional write so two users can't both claim it:
INSERT INTO links (code, long_url, created_at, expires_at)
VALUES ('summer-sale', :url, now(), :expires)
ON CONFLICT (code) DO NOTHING; -- 0 rows: alias taken, return 409
Custom aliases share the code space with generated codes, so a user could claim x7Kp2Qa before the generator reaches it. Avoid that by keeping the spaces apart: for example, generated codes are exactly 7 characters, and custom aliases must be at least 8, or contain a -. Then the generator never has to check.
For expiry, store expires_at. The redirect path treats a link as gone once expires_at is past. Physically deleting expired rows can happen later and lazily; deep dive 4 covers it.
3) Anyone opening a short URL should be redirected
GET /x7Kp2Qa arrives at a Redirect Service, which looks up the code and returns an HTTP redirect with the long URL in the Location header. We split this from the Link Service because it's 100x the traffic and has different scaling and availability needs.
Which redirect status to use matters, and interviewers like to ask:
- 301 Moved Permanently tells browsers and proxies the mapping never changes, so they can cache it. Repeat clicks from the same browser never reach us. Less load, but we can't count those clicks, and if a link expires or gets taken down for abuse, browsers that cached it keep redirecting.
- 302 Found (or 307) is a temporary redirect, so the browser asks us every time. More load, but every click is visible and we stay in control of the link.
Most shorteners use 302, because click counts are part of the product and takedowns need to work. We can still let shared caches (our CDN) hold the response for a short time with Cache-Control: max-age=60, which takes most of the load off without giving up control for long.
A plain database lookup works for this step. At 60,000 reads per second it needs a cache in front, which is deep dive 2.
4) (Pastebin) Users should be able to upload text and share a short link
Pastebin uses the same code generation and the same short URLs, with two differences.
First, the payload is bigger. A paste can be up to, say, 10MB, compared with a URL of a few hundred bytes. Storing pastes as rows in the links table would bloat the database and its cache with data that's mostly read once. Instead, put the content in object storage (S3) under the code as the key, and keep only metadata in the database: code, size, content type, expiry and the object key.
Second, instead of redirecting, we serve the content. Since pastes are immutable, they're ideal for a CDN: once a paste is fetched, the CDN can serve it from the edge until it expires.
For large uploads, the API can hand the client a pre-signed URL so it uploads straight to S3 without passing through our servers, then confirm the paste once the upload completes. For the typical paste of a few kilobytes, uploading through the API is simpler and fine.
Potential Deep Dives
1) How do we generate short codes that are unique and short?
Bad Solution: Truncated Hash of the URL
Approach
base62(sha256(longUrl))[0:7]. On collision, append a counter or salt and hash again.
Challenges
Every create needs a read to check for a collision, and as the table fills, collisions become more frequent. It also makes the same URL from two users map to the same code, which we decided we don't want. And it's not even as short as it could be: since a hash spreads codes randomly, we can't use the space densely.
Good Solution: Random Codes with a Uniqueness Check
Approach
Generate 7 random base62 characters and insert with a conditional write (ON CONFLICT DO NOTHING, or a DynamoDB attribute_not_exists(code) condition). On a conflict, generate another code and retry.
Challenges
It's simple and correct, and codes aren't guessable. The probability of a collision on each insert is the fraction of the space already used: after ten years, 36.5B / 3.5T ≈ 1%, so about one insert in a hundred needs a retry. That's fine. The cost is that every create depends on a conditional write against the full table, which constrains your choice of database (it must support atomic conditional inserts on the primary key, which most do).
Great Solution: A Counter Encoded in Base62
Approach
Give every link a unique integer and encode it in base62. With the alphabet 0-9a-zA-Z, the integer 1,000,000,000 becomes 15FTGg, and every integer below 62^7 fits in 7 characters. Unique integers guarantee unique codes, so there's never a collision to check.
A single counter is a bottleneck and a single point of failure, but at 115 writes per second, we can easily hand out ranges. Each Link Service instance grabs a block of 1,000 numbers at a time from a central counter (a Redis INCRBY counter 1000, or a database sequence row), then assigns codes from that block in memory:
def generate_code(self):
if self.next == self.end:
self.end = redis.incrby("link_counter", 1000) # atomic
self.next = self.end - 1000
n = self.next
self.next += 1
return base62(n).rjust(7, "0")
That's one Redis call per 1,000 links. If an instance crashes, its unused numbers are lost, which leaves gaps nobody notices. The counter needs to survive restarts, so persist it (Redis with AOF, or a database row). The same range-leasing technique comes up in /system-design/unique-id-generator.
Challenges
Sequential codes are guessable: if your link is 0000aB3, 0000aB4 is someone else's. Anyone can enumerate links, and sometimes those links point at things people didn't mean to make public (shared documents, unlisted videos). If that matters, scramble the integer before encoding with a reversible keyed permutation (for example a small Feistel network over the range 0 to 62^7, re-applied whenever an output falls outside that range). Each integer still maps to a unique code, but neighbors look unrelated. Or use the random-code approach if unguessability is a hard requirement.
Name the trade-off between random and counter-based codes explicitly: random codes are unguessable but need a uniqueness check, counters never collide but are sequential unless you scramble them. Either is a strong answer if you know what you're giving up.
2) How do we keep redirects fast at 60,000 per second?
Reads are 100x writes, and popular links get most of the traffic. Every layer that can answer before the database should.
Bad Solution: Read from the Primary Database Every Time
Approach
The Redirect Service queries the database for every click.
Challenges
60,000 queries per second on one primary is a lot, and it's mostly the same few thousand hot links read over and over. Read replicas help, but they're a costly way to serve data that never changes.
Good Solution: A Cache in Front of the Database
Approach
Put Redis (or Memcached) between the Redirect Service and the database. Look up code in the cache; on a miss, read the database and cache the result with a TTL of a day or so. Links never change after creation, so there's no invalidation problem, except for takedowns and expiry, which we handle by deleting the key.
How big? Click traffic is heavily skewed. If 20% of links created in the last month account for most clicks, that's about 60M links × 500 bytes = 30GB, which fits in a small Redis cluster. A hit ratio above 90% is realistic, leaving the database a few thousand reads per second. Cache "not found" too (a short-TTL negative entry), so bots probing random codes don't all fall through to the database.
Challenges
A cache cluster to run, and a failure mode to plan for: if the cache goes down, all 60,000 requests per second hit the database. Run the cache with replicas, and keep enough database read capacity (replicas) to survive a cold cache for a while.
Great Solution: Cache at the Edge Too
Approach
Serve redirects from a CDN or edge layer. The CDN caches each 302 response for a short TTL (say 60 seconds to a few minutes), keyed by path. A viral link clicked 10,000 times a second worldwide becomes one request per minute per edge location to our origin. Behind the CDN, the Redirect Service keeps a small in-process LRU cache of the hottest codes, then Redis, then the database.
Challenges
Edge caching makes takedowns slower (up to the CDN TTL, or you call the CDN's purge API) and hides clicks from our servers. If we need click counts, log them at the edge (most CDNs can stream request logs) or use edge compute to emit an event per click to Kafka, which an analytics pipeline aggregates. Counting clicks should never be on the redirect's critical path.
3) How do we store 36 billion links?
18TB and 36B rows is too much for one comfortable Postgres node, and the access pattern is pure key-value: get by code, insert by code. There are no joins and no range queries.
That makes a distributed key-value store a natural fit: DynamoDB or Cassandra, partitioned by code. Each lookup goes to exactly one partition, the data spreads evenly because codes are effectively random (or scrambled), and capacity grows by adding nodes. DynamoDB also has built-in TTL, which helps with expiry.
Sharded Postgres works too: hash the code to pick one of, say, 16 shards, each with replicas. It's more operational work, but it keeps a familiar database and its conditional inserts. If your interviewer prefers SQL, this is a fine answer.
One thing to avoid: sharding by creation time or by an increasing ID range. New links are the hottest, so all the traffic would land on the newest shard.
For Pastebin, the database only holds metadata, so the row count is the same but the rows are smaller. The content goes to S3, which handles storage at that scale without any sharding on our side.
4) How do we handle expiry and abuse?
Expiry. Every read checks expires_at and returns 404 (or 410 Gone) once it has passed, so expiry is enforced exactly at read time no matter when the row is deleted. Physical cleanup can be lazy: DynamoDB TTL or Cassandra TTL deletes rows in the background, or a daily job deletes expired rows in batches. When caching, cap each cache entry's TTL at the link's remaining lifetime, so the cache never serves a link past its expiry. For Pastebin, an S3 lifecycle rule or a cleanup job removes the object.
Should expired codes be reused? No. Someone may still have the old link in an email, and it's much better for it to show "expired" than to send them to a stranger's page. With 3.5 trillion codes, we never need to reuse one.
Abuse. Shorteners are a favorite tool for hiding phishing and malware links. A few defenses go a long way:
- Rate limit creation per user, API key and IP (see /system-design/rate-limiter). Anonymous creation gets the tightest limits.
- Check URLs on creation against a malicious-URL list (such as Google Safe Browsing), and re-check popular links periodically, since a page can turn bad after it's shortened.
- Support takedowns: a flag on the link that the redirect path checks, plus a cache delete and a CDN purge.
- For Pastebin, cap paste size and scan for leaked credentials and malware.
5) How do we keep redirects available?
Redirects are a promise that outlives any one deployment: links printed on posters will be scanned for years. Keep the redirect path simple and redundant:
- Stateless Redirect Service instances in multiple availability zones behind a load balancer.
- Database replicated across zones (DynamoDB does this by default; for Postgres or Cassandra, configure it).
- For a global product, replicate links to multiple regions and serve redirects from the nearest one. Writes are rare and can go to one home region; a newly created link appears in other regions within a second or so through replication. If a click lands in a region that hasn't seen the link yet, fall back to the home region before returning
404. - The CDN can keep serving cached redirects for hot links even if the origin is briefly down (many CDNs support serving stale content on origin errors).
Final Design
- A user creates a link through the Link Service, which validates the URL, checks it against abuse lists, and either reserves a custom alias with a conditional insert or assigns the next number from its leased counter range, encoded in 7-character base62.
- The mapping is stored in a key-value store partitioned by code, with optional expiry.
- A click on the short URL hits the CDN. On a miss, the Redirect Service checks its in-process cache, then Redis, then the database, and returns a
302with the long URL. - Expired or taken-down links return
404. Click events are emitted asynchronously to Kafka for analytics. - For Pastebin, content goes to S3 under the paste's code, metadata goes to the same store, and reads are served through the CDN.
What is Expected at Each Level?
Mid-level
You should get to a working design with a create path and a redirect path, calculate how many characters a code needs, and pick a code-generation method that's actually unique. You should know the difference between 301 and 302 and add a cache for redirects once you see the read/write ratio.
Senior
You should compare hashing, random codes and counters and choose one with its trade-offs (collisions versus guessability), including range leasing so the counter isn't a bottleneck. Expect to size the cache from the traffic skew, choose a key-value store partitioned by code, and handle custom aliases, expiry and negative caching cleanly. For Pastebin, you should move content out of the database into object storage.
Staff+
You should keep the write path deliberately simple and spend effort on the redirect path's latency and availability over years: CDN caching and its effect on takedowns and analytics, multi-region reads, and a database choice that matches the access pattern. Expect to bring up abuse unprompted (phishing, enumeration of sequential codes) and to explain how analytics stay off the critical path.