Turn long links into short ones (like bit.ly) and redirect fast. The classic first design question.
“Design a URL shortener, like bit.ly.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Asking before drawing | The prompt has no numbers and no features. A strong candidate makes it specific first (custom links? expiry? analytics? how many?). |
| Estimation that drives the design | Read-heavy, small data. The numbers should tell you that caching matters a lot and that one database is not the problem, availability is. |
| Unique code generation | This is the heart of the question. Hash, counter, random and key-service each have a real cost, and the interviewer wants you to compare them. |
| Read-path performance | A redirect must feel instant. Caching, hot links, and what happens when the cache or database is down. |
| Judgement and trade-offs | 301 or 302, consistency of analytics, reuse of expired codes, abuse. There is no single right answer, only reasoned ones. |
A create service makes a short code and saves code → long URL. A redirect service looks the code up and answers with an HTTP redirect. The system is read-heavy (about 100 reads per write), so almost every redirect is served from a cache.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Scope: custom alias, expiry, analytics, scale. Say what is out of scope. |
| 2. Estimate | 3 | Writes per second, reads per second, storage, cache size, code length. |
| 3. API and data | 5 | Two endpoints, the record, and why a key-value store fits. |
| 4. High-level design | 8 | Boxes, one write path, one read path. |
| 5. Deep dives | 15 | Code generation, then the read path. Custom aliases, expiry and analytics if time allows. |
| 6. Scale and failures | 7 | Hot links, cache down, database down, abuse, monitoring. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would do next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| Who creates links: anyone, or only signed-in users? Is there an API for other apps? | Decides authentication, abuse limits, and whether links have owners. | Signed-in users and an API with keys. Anonymous creation is allowed but rate-limited. | Links need an owner field and per-user limits. Rate limiting is part of the design. |
| Can users pick their own short name (a custom alias)? | Custom names need a uniqueness check against generated codes. | Yes, optional. | Creates a race on the alias. Needs an atomic conditional write and a rule that keeps custom names apart from generated codes. |
| Do links expire? Can they be edited, disabled or deleted? | Expiry means cleanup jobs and affects whether a redirect can be cached forever. | Optional expiry. Owners can disable or delete. | Rules out permanent redirects (301) by default, and needs an expiry field plus cache purge on delete. |
| Do we need click analytics? | Counting every click changes the write load on the hot path. | Basic counts per link per day, with a delay of a few minutes being fine. | Analytics goes through a queue, off the redirect path. |
| How many new links per month, and what is the read to write ratio? | The numbers decide whether you need sharding, and how big the cache is. | 100 million new links a month, about 100 reads for each write. | Read-heavy. A cache is the main tool. Storage is small. |
| How long should a short link be, and which characters may it use? | Sets the code length and the alphabet. | As short as possible, letters and digits only, case sensitive. | Base62 (0-9, a-z, A-Z). 7 characters is enough, shown in the estimate. |
| What availability and latency do we need for a redirect? | A redirect is on the critical path of every click. | 99.99% available, under 100 ms at the server. | Multiple zones, no single point of failure, cache-first reads. |
| Is it a problem if two people shorten the same long URL and get different codes? | Decides whether you de-duplicate. | No. Each link has its own owner, expiry and stats. | A new code for every create request. No lookup by long URL needed. |
| How long do we keep links, and can an old code be reused? | Decides storage growth and whether an expired code can be handed out again. | Keep for 5 years by default. Do not reuse codes soon. | Storage is sized for 5 years. No quick reuse, so an old link can never point to someone else. |
| Is the long URL checked for safety (phishing, malware)? | A shortener hides where a link goes, so it is a favourite tool of spammers. | Yes, check at creation and block known bad links. | Adds a safety-check step to the write path, and a way to disable links fast. |
| Assumption | Value |
|---|---|
| New links per month | 100 million |
| Read to write ratio | 100 : 1 |
| Peak traffic vs average | 3 times the average |
| Size of one saved link (code, long URL, owner, dates) | about 500 bytes |
| Retention | 5 years |
| Cache hit rate we aim for | 90% or better |
| Click event size | about 100 bytes |
| One app server can handle | about 2,000 redirects per second |
| What | Maths | Result |
|---|---|---|
| New links per second (average) | 100,000,000 ÷ (30 × 86,400 s) = 100M ÷ 2.6M | about 40 per second |
| New links per second (peak) | 40 × 3 | about 120 per second |
| Redirects per second (average) | 40 × 100 | 4,000 per second |
| Redirects per second (peak) | 4,000 × 3 | 12,000 per second |
| Links stored after 5 years | 100M × 12 months × 5 years | 6 billion links |
| Possible 7-character codes | 62^7 | 3.5 trillion |
| How much of that space we use | 6 billion ÷ 3.5 trillion | 0.17% |
| Storage for 5 years | 6 billion × 500 bytes | 3 TB (about 9 TB with 3 copies) |
| Redirects per day | 4,000 × 86,400 | about 346 million |
| Cache size (80/20: keep the hottest 20%) | 0.2 × 346M × 200 bytes | about 14 GB |
| Database reads after the cache (90% hits) | 4,000 × 10% | 400 per second (1,200 at peak) |
| Redirect bandwidth at peak | 12,000 × 0.5 KB | 6 MB per second, about 48 Mbit/s |
| Click events per day | 4,000 × 100 bytes × 86,400 | about 35 GB per day |
| App servers for peak load | 12,000 ÷ 2,000, then 3 zones so one can fail | 6 needed, so 9 (3 per zone) |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/links | { longUrl, customAlias?, expiresAt? } | 201 { code, shortUrl, expiresAt } | Needs an API key or login. 409 if the alias is taken. 400 for a bad URL. 429 when over the limit. Send an Idempotency-Key header so a retry does not create a second link. |
| GET | /{code} | none | 302 Location: longUrl | The hot path. 404 if unknown, 410 if expired or removed. No login. Add Cache-Control: private, max-age=60 if you accept a short browser cache. |
| GET | /v1/links/{code}/stats | none | 200 { total, byDay: [...] } | Owner only. Counts can be a few minutes behind. |
| DELETE | /v1/links/{code} | none | 204 | Owner only. Marks the link deleted and removes it from the cache. |
| Field (links table) | Type | Notes |
|---|---|---|
| code (key) | string, up to 20 | Short code or custom alias. Partition key. Unique. |
| long_url | string, up to 2,048 | The target. Validated and normalised. |
| owner_id | id | Who created it. Used for limits and the delete check. |
| created_at | timestamp | For listing and for support. |
| expires_at | timestamp, optional | Null means never. Indexed for the cleanup job. |
| status | active | disabled | deleted | blocked | Lets us stop a link without deleting data (and re-enable it). |
| Other stores | Holds | Key |
|---|---|---|
| owner_links (secondary index) | A user's links, newest first | owner_id, then created_at |
| click events (queue, then analytics store) | One event per redirect | code, time, country, referrer |
| click_daily (aggregate table) | Clicks per link per day | code, day |
| code ranges (small counter store) | The next unused range of the counter | one row |
code : "k3Fz9aQ" long_url : "https://example.com/blog/how-to-design-systems?ref=mail" owner_id : 48213 created_at : 2026-03-02T09:14:00Z expires_at : null status : "active"
| Component | What it does |
|---|---|
| CDN / edge (optional) | Can cache popular redirects for a few seconds close to the user. Skipped if we want exact click counts at the origin. |
| Load balancer | Spreads traffic over app servers in three zones, and removes sick servers using health checks. |
| Create service | Validates the URL, checks it is safe, takes the next code from its local range, saves it with a conditional write. |
| Redirect service | Looks the code up (cache first), checks status and expiry, returns 302, and sends a click event without waiting for it. |
| Redis cache | Holds the hot links in memory. Cache-aside with a TTL that never outlives the link's expiry. |
| Key-value store | The source of truth. Partitioned by hash of the code, three copies in different zones. |
| Range service | A tiny, strongly consistent store (a database row, or ZooKeeper or etcd) that gives each app server a block of unused counter values. |
| Queue and aggregator | Receive click events, count them, and write daily totals. If they fall behind, redirects are not affected. |
The problem: We need billions of codes that are short, never repeat, work across many servers with no bottleneck, and are not easy to guess. Two servers must never hand out the same code, even at the same instant.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Hash the long URL, keep 7 characters | MD5 or SHA-256 of the URL, encode in base62, take the first 7 characters. | No shared state. The same URL gives the same code, which is a free de-duplication. | Two different URLs can share the first 7 characters (a collision). With 6 billion links, about 5 million pairs would clash, so every insert needs a check and a retry with a salt. The same URL for two owners shares one code. |
| Counter, written in base62 | One global number that goes up by 1. Link number 125 becomes ‘21’. Pad to 7 characters. | Never collides. Shortest possible codes. No check needed. | One counter is a bottleneck and a single point of failure. Codes come out in order, so anyone can guess the next one and count how many links you have. |
| Random code, then check | Make 7 random base62 characters, insert only if free, and try again if it exists. | Simple. Not guessable in order. No shared counter. | Collisions rise as the table fills (0.17% of inserts at 6 billion, so rare). Every create does a conditional write that may need a retry. |
| Key generation service (pre-made codes) | A separate service makes unique random codes ahead of time and stores them as ‘unused’. App servers take a batch of 1,000 and mark them ‘used’. | No collision at request time. Fast creates. Codes look random. | One more service to run and make highly available. If a server dies, the unused part of its batch is lost (fine, the space is huge). |
Each app server asks a small range service for a block of 1 million numbers (for example 3,000,000 to 3,999,999). It uses them from memory, one by one, and asks again only when the block runs out. At 4 creates per second per server, a block lasts about 3 days. So the range service is touched rarely, and a short outage of it does not stop creates for a long time.
Two servers always own different blocks, so codes never collide. A server that crashes just wastes the rest of its block, which is nothing out of 3.5 trillion. Before writing the code in base62, we run the number through a bijective scramble (a one-to-one shuffle of all numbers below 62^7), so consecutive links do not look consecutive.
| App server | Takes range | Next number | Code (before scramble) |
|---|---|---|---|
| A | 0 to 999,999 | 125 | 0000021 |
| B | 1,000,000 to 1,999,999 | 1,000,000 | 0004c92 |
| C | 2,000,000 to 2,999,999 | 2,000,001 | 0008oi5 |
if (range.next > range.end)
range = rangeService.reserve(1_000_000); // rare, strongly consistent
n = range.next++;
code = base62( scramble(n), 7 ); // scramble: a one-to-one shuffle below 62^7
ok = db.putIfAbsent(code, { longUrl, ownerId, expiresAt });
if (!ok) retry with the next number; // only if a custom alias already uses this codeThe problem: 4,000 redirects a second on average and 12,000 at peak, under 100 ms, with 99.99% availability. A few links will be far more popular than the rest, and caches and databases do fail.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Database only | Every redirect reads the key-value store. | Simplest. Always correct. | Every click costs a disk-backed read. The database becomes the availability bottleneck. |
| In-process cache on each app server | A small LRU map in memory, with a 1 to 5 second TTL. | Fastest possible. Absorbs a viral link without any network call. | Each server has its own copy, so the hit rate is lower. Changes (disable, delete) show up only after the TTL. |
| Shared Redis cache (cache-aside) | Look in Redis first. On a miss, read the database and fill Redis. | A high hit rate across all servers. About 14 GB holds the hot set. Takes about 90% of reads off the database. | One more system to run. It can fail or be cold. Needs protection from a stampede on a miss. |
| CDN edge caching | Let the CDN cache the 302 answer for a short time. | The answer comes from near the user. Takes load off the origin. | Clicks served at the edge are not counted unless the CDN logs them. Disable and delete are delayed by the TTL. |
Each layer removes load from the next. The tiny in-process cache handles a viral link. Redis, sized at about 14 GB, handles the hot set. The database sees about 400 reads a second on average, which is easy. I would skip the CDN for redirects at first, because it complicates click counting and takedowns, and add it later if the origin needs relief.
Failure behaviour matters as much as speed. If the database is down, redirects for cached links keep working. If Redis is down, servers fall back to the database, with request coalescing (one lookup per code) and limits so that a cold cache does not flatten the database.
| Problem | What to do |
|---|---|
| Viral link (one hot key) | In-process cache on every server for 1 to 5 seconds. Optionally keep several copies of the hot key under names like code#1, code#2 so many Redis nodes share it. |
| Cache stampede (a hot key expires and 1,000 requests miss at once) | Coalesce: only one request per code goes to the database, the rest wait for it. Add a little random time to every TTL so keys do not all expire together. |
| Scans for random codes (always a miss) | Cache ‘not found’ for 30 to 60 seconds, and rate limit by IP. A Bloom filter of existing codes can answer ‘definitely not here’ without touching the database. |
| Stale cache after disable or delete | On disable or delete, remove the key from Redis. In-process copies expire in seconds. Say this delay is accepted. |
| Cache entry outliving the link | Set the TTL to the smaller of the normal TTL and the time left before expires_at. |
The problem: People pick their own names, and two people may want the same one at the same moment. Links expire, and we must remove them without scanning 6 billion rows, and without ever pointing an old link at a new owner.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Check, then insert | Read to see if the alias is free, then write it. | Easy to understand. | A race: two users both see ‘free’ and both write. One silently overwrites the other. |
| Conditional insert (put-if-absent) | One atomic write: insert only if the key does not exist. A duplicate fails and returns 409. | No race. One round trip. Works with a unique constraint or a conditional put. | Needs a store with conditional writes (most have them). |
| Lazy delete on read | When a redirect finds an expired link, answer 410 and delete it then. | Free. Expired links stop working at once. | Links nobody opens never get cleaned up. |
| Background sweeper (or store TTL) | A job deletes expired rows in small batches, using an index on expires_at. Some stores can expire rows by themselves. | Reclaims space. Works for links nobody opens. | Must be paced, so it does not hurt normal traffic. |
The conditional insert makes the alias check and the write one atomic step. For expiry, we check expires_at on every read, so a link stops working on time even before cleanup. The sweeper handles the long tail in small, paced batches.
Do not reuse a code soon after it expires. Old links live on in emails, documents and browser history. If a code is handed to a new owner, those old links now send people to a stranger's page. With 3.5 trillion codes there is no need to reuse. If you must, wait many months.
| Alias rule | Why |
|---|---|
| Allowed characters and a length range (for example 4 to 30) | Keeps URLs clean and predictable. |
| Reserved words blocked (api, admin, login, static, help) | A user must not be able to take a name we use for our own routes. |
| Blocked or offensive words | Brand safety and abuse. |
| Decide on case: treat ‘Sale’ and ‘sale’ as different (base62 is case sensitive), or fold to lower case | Pick one rule and say it. Mixing causes support problems. |
| Soft delete first (status = deleted), hard delete after a retention period | Allows undo and lets us purge caches and queues in order. |
The problem: Every redirect should be counted, but a write to a counter on every click would put a database write on the hot path, at 4,000 to 12,000 writes a second, and one hot link would hammer one row.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Increment a counter in the link row | UPDATE clicks = clicks + 1 on every redirect. | Simple. Instant totals. | A write on every redirect. A hot link becomes a hot row. The redirect now fails if this write fails. |
| Log events, count them later (queue) | Drop an event on a queue (Kafka), without waiting. A job aggregates counts per link per time bucket. | Off the hot path. Handles bursts. Can answer more questions later (by country, by referrer). | Counts are a few minutes late. Needs care about duplicates. One more system. |
| Count in memory, flush in batches | Each server counts per code and writes the totals every few seconds. | Far fewer writes. Cheap. | A server crash loses a few seconds of counts. No raw events for later questions. |
The redirect only needs the long URL. So it sends one small event (code, time, country, referrer) to Kafka and moves on. If the queue is slow or down, the server buffers a little in memory and then drops events before it drops redirects. A redirect never fails because analytics is unhealthy.
An aggregator reads the events and writes counts per link per day (and per hour if wanted). Delivery is at least once, so a duplicate is possible. Use an event id to de-duplicate, or accept a small error for plain counts, and say so. Unique visitors can use a HyperLogLog sketch, which counts distinct items in a few kilobytes.
A counter is just a number. Base 62 uses the digits 0–9, then a–z, then A–Z, so a big number becomes a short code. Type a number to see its code at the length chosen above.
The “tries” figure is 1 ÷ (1 − fraction used). The “clashing pairs” figure is the birthday estimate N² ÷ (2 × possible codes). Both assume codes are spread evenly. A real system always checks the database, so a clash costs a retry, never a wrong link.
| Bottleneck | Fix |
|---|---|
| Redirect reads at 12,000 per second (and growing) | Add app servers (they are stateless), enlarge Redis, add read replicas. The cache already takes about 90% of reads. |
| Database size and write growth (3 TB, 9 TB with copies) | Shard by a hash of the code with consistent hashing and virtual nodes, so adding a node moves only a small part of the data. |
| One viral link (hot key) | In-process cache with a short TTL on every server, plus optional copies of the hot key across Redis nodes. Optionally let the CDN serve it for a few seconds. |
| The range service | It is hit about once per million links per server, so it is not a bottleneck. Keep it replicated (three nodes, majority agreement) and give each server a big block so it can ride out an outage. |
| Click event stream (35 GB a day) | Partition the queue by code. Scale the aggregator workers. Keep raw events short-lived and keep daily totals for good. |
| Listing ‘my links’ across shards | A separate index keyed by owner, so it does not scan every shard. |
| Global users far from the servers | Serve reads from regional replicas and caches. See the multi-region question below. |
| Failure | How the design copes |
|---|---|
| A cache node fails | Consistent hashing sends its keys elsewhere. Misses go to the database, with request coalescing. Refill gradually (cache warming for the hottest keys). |
| All of Redis is down | Fall back to in-process cache and the database, with a limit on database concurrency. Redirects get slower, but still work. |
| One database replica or one zone fails | Three copies in three zones. Reads and conditional writes continue on the others. The load balancer drops dead app servers. |
| The database is unreachable | Cached links keep redirecting. Creates return 503 with Retry-After. Reads are the priority. |
| The range service is down | Servers keep using the block they hold (days of codes). Alert early, restore, no user impact. |
| An app server crashes with part of a range | The rest of its range is simply never used. Nothing to repair. |
| The analytics pipeline is down or behind | Redirects are unaffected. Events are buffered or dropped. Counts catch up when it recovers. |
A stateless create and redirect service in front of a key-value store partitioned by code. Codes come from per-server ranges of a counter, are scrambled, and written in base62 at 7 characters. A layered cache serves almost every redirect, with 302 so we keep control and can count clicks. Click events go through a queue, so analytics never slows or breaks a redirect.
| Decision | What we gain | What it costs |
|---|---|---|
| 302 (temporary) instead of 301 (permanent) | Every click reaches us, so we can count it, change it, expire it or block it. | More traffic to our servers. Browsers cannot cache it for long. |
| Counter ranges with scramble instead of hashing | No collisions and no check on the hot path. No shared state per request. | A small range service to run. The scramble is not strong security. |
| Cache first, with short TTLs | Very fast redirects and a database that stays calm. | A disabled link may still redirect for a few seconds from some caches. |
| Analytics through a queue | Redirects never wait for counting. | Counts are a few minutes late and may be slightly off. |
| A key-value store | Simple, horizontal scale, conditional writes. | Fewer ad hoc queries than SQL. Listing needs a secondary index. |
| A new code for every create request | Each link has its own owner, expiry and stats. | Several codes may point to the same URL, which uses more storage. |
The part interviewers push hardest. Know the numbers.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Links must never be guessable (private links) | Use long random codes (10 or more characters) from a secure random source, and require sign-in for sensitive targets. A scramble is not enough. |
| Strict click counts, with no loss | Write events to a durable log before redirecting, with acknowledgement. Accept higher latency on redirects, or use 301 with care. De-duplicate by event id. |
| Same URL must always give the same short code | Hash the normalised URL (plus a salt on collision) and use a unique index on its hash. Lose per-user stats and expiry, or key the hash by (owner, URL). |
| Links can be edited after creation | Never use 301. Update the row and purge caches. Keep a version history for audit. |
| 10 times more traffic, global audience | Edge caching for the hot set, regional replicas, regional code ranges, and a bigger analytics pipeline. |
| Custom domains per customer (brand.link/abc) | The key becomes (domain, code). Add domain verification, per-domain certificates and per-domain limits. |
| Shorter codes needed (5 characters) | Only 916 million codes. Codes must be reused and links expire, so you need a reuse policy and a fast, reliable cleanup. |
| Add QR codes and link previews | A separate service reads the same data. Previews fetch pages, so they need a safe sandbox, caching and abuse limits. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing. Never asks about alias, expiry, scale or analytics. | Asks the main questions and writes functional and non-functional lists. | Asks the questions that change the design (301 vs 302, reuse, abuse), says what is out of scope, and confirms it. |
| Estimation | No numbers, or numbers with wrong units. | Writes per second, reads per second, storage and code length, with correct maths. | Uses the numbers to decide things: cache size, code length, whether to shard, and says which numbers are assumptions. |
| Design | A single box called ‘database’. No read path or write path. | Clear components, a write path and a read path, cache in front. | Keeps analytics off the hot path, shows failure behaviour, and every box earns its place. |
| Code generation depth | Says ‘hash it’ or ‘use a random string’ with no discussion. | Compares hash, counter and random, and names the collision and counter problems. | Gives numbers (birthday collisions, 62^7), handles the distributed counter with ranges, and covers guessing. |
| Trade-offs and failures | Cannot say what happens when the cache or database fails. | Explains cache down, hot key, and database down. | States what each choice costs, picks with a reason, and offers what would change the choice. |
| Communication | Silent for long periods, or jumps around. | Follows the 7 steps and explains as they go. | Summarises at each step, checks in with the interviewer, handles hints and curveballs calmly. |
| Mistake | Do this instead |
|---|---|
| Jumping to the database before asking questions | Spend 4 minutes on scope. Say what is out of scope. It shows maturity and saves you from the wrong design. |
| Saying ‘hash the URL’ and stopping | State the collision problem, give the birthday numbers, and compare with a counter and random codes. |
| A single auto-increment counter with no discussion of failure | Show ranges per server, so the counter is off the hot path, and say what happens if it is down. |
| Choosing 301 without thinking about analytics and expiry | Explain 301 vs 302 and pick 302 by default, with a reason. |
| Writing a counter on every redirect | Send an event to a queue. Never put analytics on the redirect path. |
| No numbers, or numbers that never change the design | Say how each number changes a decision: cache size, shard or not, code length. |
| Ignoring abuse (phishing, spam, scanning) | Add a safety check, rate limits and a kill switch. Mention that a shortener is an open redirect. |
| Reusing expired codes immediately | Do not reuse, or quarantine for months. Explain the risk to old links. |
Cache-aside and TTLs, used on the redirect path.
What to do when one link gets most of the traffic.
Why a cache miss on a hot key can flatten the database.
More ways to make unique IDs without a central counter.
Picking the code as shard key, and adding shards safely.
How adding a node moves only a small part of the data.
Limiting creation per user, key and IP.
The store that fits access by one key.