A URL shortener turns a long link into a short one such as sho.rt/aZ3k9Qx, and sends anyone who opens the short link to the long one. It is the most common first design question. It looks trivial, yet it covers the main ideas of the course: estimation, key generation, storage choice, caching, and the trade-offs of a very read-heavy system. This lesson follows the steps of the interview framework lesson.
1. Requirements and Scope
Functional requirements:
- Given a long URL, create a short URL. A user can optionally choose a custom alias and an expiry date.
- Opening a short URL redirects to the long URL.
- Basic click analytics: how many clicks per link, by day and by country.
- Links expire after a set time (default: never).
Non-functional requirements:
- Redirects are fast: under 50 ms at the server, since the user is waiting.
- High availability: a dead short link is a broken link on someone's website, in an email or on a printed poster.
- Short codes are unique and not guessable in order, if links may be private.
- Durable: a link created today must still work in five years.
Out of scope: user accounts in detail, link editing, QR codes, and billing.
2. Estimation
- Writes: 20 million new links a day. 20,000,000 ÷ 86,400 ≈ 231 per second.
- Reads: redirects outnumber creations about 100 to 1. That is 2 billion redirects a day, and 231 × 100 ≈ 23,100 per second on average. Peak is about 4 times that: roughly 92,400 per second.
- Servers: one m5.xlarge handles about 2,000 simple requests per second, so peak needs 92,400 ÷ 2,000 ≈ 46 servers. To survive the loss of one of three zones we need 1.5 times that, about 70 servers.
- Storage: keep links for 5 years. 20 million × 365 × 5 = 36.5 billion links. At about 500 bytes per record (code, long URL, owner, dates), that is about 18 TB.
- Code length: using the characters 0-9, a-z and A-Z (62 symbols), 6 characters give 626 ≈ 56.8 billion codes, of which 36.5 billion (about 64%) would be used after 5 years. That is too tight, so we use 7 characters: 627 ≈ 3.5 trillion. With random or hashed codes, a collision is possible on any day, even the first (the chance for a new code is the number of existing links ÷ 3.5 trillion, tiny at first and about 1% after 5 years), so every insert must check for it.
- Cache: a cache holds only a small, active part of the data, frequently 5% to 20% of the total, depending on the workload. Here the total is 36.5 billion links × about 200 bytes (code and long URL) ≈ 7.3 TB, so 5% to 20% would be 365 GB to 1.5 TB, which is 15 to 60 Redis nodes of about 24 GB usable. But clicks on short links are very skewed: most go to recently created links. If we cache the links of the last 5 days, that is 20 million × 5 = 100 million links, under 1% of the total, and 100 million × 200 bytes = 20 GB. One node can hold that, but a single node handles about 100,000 operations per second, so we run 3 shards with replicas for load and availability. With a 90% hit rate (to be confirmed with real traffic), the database sees only 10% of 92,400, about 9,200 reads per second.
The takeaway: this is a read-heavy system with a tiny write rate. The design effort goes into caching and reliable code generation, not write throughput.
3. API
POST /v1/linkswith{ "longUrl": "...", "alias": "optional", "expiresAt": "optional" }returns201with the short URL. A taken alias returns409.GET /{code}returns302with aLocationheader,404if unknown and410if expired.GET /v1/links/{code}/stats?from=&to=returns click counts.DELETE /v1/links/{code}disables a link.
Creation takes an idempotency key, so a retry does not create two links.
4. Data Model and Storage
One main table: links (code PRIMARY KEY, long_url, owner_id, created_at, expires_at, status). The access pattern is only "get by code" and "insert if the code does not exist". No joins, no range queries, and a very large number of rows.
That points to a key-value or wide-column store such as DynamoDB or Cassandra: it scales to billions of rows, shards by the code, replicates across zones, and supports a conditional write ("insert only if absent"), which we need for uniqueness. A relational database sharded by code would also work, and many teams choose it for familiarity. State the reason either way. Click events go to a separate analytics store, not this table.
5. High-Level Design
flowchart LR
U["Browser"] --> LB["Load balancer"]
LB --> R["Redirect service"]
LB --> C["Create service"]
R --> CA[("Redis cache, sharded")]
CA --> DB[("Links store, sharded by code")]
R -.-> K[["Kafka: click events"]]
K --> A["Analytics pipeline"]
C --> ID["ID allocator (counter blocks)"]
C --> DB
Create flow: validate the URL, get a unique ID from the allocator, encode it as a 7-character code, store the record, and return the short URL.
Redirect flow: look up the code in Redis, and on a miss read it from the store and fill the cache. Send a click event to Kafka without waiting, and answer with a redirect.
The redirect service and the create service are separate, because their load is very different (92,400 per second against 231 per second) and they scale independently.
6. Deep Dive: Generating Short Codes
Background note: encoding and hashing are different things
- Encoding is a reversible way of writing a number using a chosen set of symbols. Base 62 means writing the number with 62 symbols (0-9, a-z, A-Z) instead of the 10 digits we normally use. The same value gets shorter: 3.5 trillion needs 13 decimal digits but only 7 base-62 characters.
- Why 62 and not another base? Letters and digits are safe in any URL. Base 64 adds
+and/, which have special meaning in URLs. Base 36 (digits and lowercase) is safe too but needs longer codes for the same range.- Hashing (MD5, SHA-256) is a different tool. It is a one-way function that turns any input into a fixed-size fingerprint, such as 128 bits for MD5. You cannot go back from the fingerprint to the URL. It is not short either: MD5 gives 32 hex characters.
A hash returns a fixed-size block of bits, usually shown as a hex string, not a number. You turn it into a number yourself. MD5 of a URL gives 128 bits, shown as 32 hex characters such as
5d41402abc4b2a76b9719d911017c592. Those bits can be read as one very large number. So a hash-based design takes three steps:
- Hash the URL: 128 bits (MD5) or 256 bits (SHA-256).
- Keep the first 42 bits and read them as a number below 242, about 4.4 trillion.
- Encode that number in base 62 to get 7 characters.
Cutting the hash down to 42 bits is the problem: with so few bits, collisions are likely after only about 2 million links, and we will have 36.5 billion.
6.1 The Options
| Approach | How it works | Good | Problem |
|---|---|---|---|
| Hash the long URL | Hash it, keep 42 bits, encode them as 7 base-62 characters | No central counter. The same URL gives the same code | Frequent collisions, so every insert must check and retry with a salt. Two users cannot get separate codes for one URL |
| Random code | Pick 7 random characters, insert only if absent, retry on conflict | Simple, not guessable | An extra check on every write. Collisions grow as the space fills (36.5 billion of 3.5 trillion is about 1%, so retries are rare) |
| Counter + base 62 | A unique number, written in base 62 | No collisions at all, short codes | The counter is a shared dependency. Codes are sequential, so guessable |
| Pre-generated keys | A separate service creates random unique codes in advance. Servers take batches | No collision checks at request time | Another service to run. Used and unused keys must be tracked |
6.2 Counter + Base 62, Handed Out in Blocks
A good answer is a counter with base 62. The question is how to share one counter between several create servers. Asking a central counter for every single link would make it a bottleneck, so each server takes a block:
- The central counter holds the next free number, for example 5,000,000.
- A create server asks for a block of 100,000. The counter does one atomic step,
next = next + 100,000, and returns the range 5,000,000 to 5,099,999. No other server can get these numbers. - The server hands out the numbers from memory, one per new link, and encodes each one in base 62. No network call is needed per link.
- When the block is used up, it asks for the next one. If the server crashes, the unused part of its block is lost. That is fine: gaps in the numbering do not matter in a space of 3.5 trillion.
public class CodeGenerator {
private static final String ALPHABET =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static final int BLOCK = 100_000;
private final CounterStore counters; // a replicated database row, or etcd
private long next;
private long end;
public CodeGenerator(CounterStore counters) {
this.counters = counters;
}
public synchronized String nextCode() {
if (next == end) { // block used up: take a new one
long start = counters.incrementBy("link_counter", BLOCK) - BLOCK;
next = start;
end = start + BLOCK;
}
return toBase62(next++);
}
static String toBase62(long id) { // 125 becomes "21" (2 x 62 + 1)
StringBuilder sb = new StringBuilder();
do {
sb.append(ALPHABET.charAt((int) (id % 62)));
id /= 62;
} while (id > 0);
return sb.reverse().toString();
}
}
Is the central counter a single point of failure? It is a dependency, but a weak one, and we can make it safe:
- It is called rarely. With 231 links per second over 3 create servers, each server uses about 77 numbers per second, so a 100,000 block lasts about 22 minutes. The whole system calls the counter about once every 7 minutes.
- Servers keep working during an outage. They continue with the block they hold, and they can fetch the next block early, when the current one is 20% left. A counter outage shorter than the remaining time causes no failed creates.
- The counter itself is replicated. Use a database primary with a synchronous replica and automatic failover, or a small consensus store such as etcd or ZooKeeper (see the consensus lesson). The increment must be durable before a block is handed out, otherwise a failover could give the same block to two servers.
- A safety net. The links table has the code as its primary key and inserts only if the code is absent. Even if a block were handed out twice by mistake, the second insert would fail and the server would take a new number, so no link is overwritten.
- No counter at all is also possible. A Snowflake-style ID (a timestamp, a machine number and a sequence number, packed into 64 bits) is created locally with no coordination. The price is a longer code: 11 base-62 characters instead of 7 (see the ID generation lesson).
Sequential codes can be walked one by one by a scraper. If links are private, or enumeration is a problem, scramble the number before encoding it with a reversible mix (multiply by a large odd number modulo 627, which keeps codes unique but not in order), or use the random approach. Start the counter high enough that codes have 7 characters.
Same long URL twice? Usually each request gets a new code, so each owner has their own link, statistics and expiry. If you want one code per URL, you need a lookup by long URL, which means a second index over 36.5 billion rows. It is rarely worth it.
7. Deep Dive: The Redirect
7.1 301 or 302
- 301 (permanent): browsers and CDNs cache it, so repeat visits skip our servers. That saves load, but we never see those clicks, and we cannot change or expire the link for people who cached it.
- 302 (temporary): every click reaches us, so analytics are accurate, and links can be edited, disabled or expired immediately. It costs more load.
Choose 302 when analytics or expiry matter, which is the usual case. Choose 301 when only speed and low load matter.
7.2 Cache-Aside
The redirect path follows the cache-aside pattern from the caching lesson. Two additions matter here. First, cache "not found" for a short time (for example 60 seconds), so someone scanning random codes cannot send every request to the database (cache penetration). Second, cap the cache time of a link at its expiry time, so an expired link does not keep redirecting from the cache.
@RestController
public class RedirectController {
private final LinkResolver resolver; // cache first, then the links store
private final ClickPublisher clicks;
public RedirectController(LinkResolver resolver, ClickPublisher clicks) {
this.resolver = resolver;
this.clicks = clicks;
}
@GetMapping("/{code}")
public ResponseEntity<Void> redirect(@PathVariable String code) {
Link link = resolver.find(code);
if (link == null) {
return ResponseEntity.notFound().build(); // 404
}
if (link.isExpired()) {
return ResponseEntity.status(HttpStatus.GONE).build(); // 410
}
clicks.publish(new ClickEvent(code, Instant.now())); // asynchronous, never blocks the redirect
return ResponseEntity.status(HttpStatus.FOUND) // 302
.location(URI.create(link.longUrl())).build();
}
}
8. Deep Dive: Analytics, Expiry, Aliases and Abuse
- Analytics without slowing redirects. The redirect service puts a small click event (code, time, country from the IP, user agent) on Kafka and does not wait for it. If Kafka is slow, drop or buffer the event, but never delay the user. A stream job counts clicks per link per minute and hour and stores them for the stats API (see the real-time analytics lesson). Counts may lag by seconds. That is fine for statistics.
- Expiry. Each record has
expires_at. A read checks it, and a store with a TTL feature (DynamoDB, Cassandra) can delete expired rows by itself. Do not reuse an expired code for a long time, because old copies may still exist in caches and in browsers that cached a 301. - Custom aliases. Use a conditional write ("insert only if the code does not exist"), which is atomic, so two users asking for the same alias cannot both win. Keep a list of reserved words (
admin,api,login) and keep the custom alias space apart from generated codes, for example by a minimum length, so a generated code can never clash with an alias. - Abuse. Shorteners are used to hide phishing and malware links. Accept only
httpandhttpsURLs, check new links against a block list or a safe-browsing service, rate-limit creation per user and per IP (see the rate limiter lesson), allow reports and takedowns, and refuse to shorten your own short domain (redirect loops).
9. Scaling and Availability
- Links store: shard by a hash of the code, with three replicas across zones. Reads and writes go to one shard, so no cross-shard queries are needed (see the sharding lesson).
- Cache: Redis shards with replicas. If the whole cache is lost, all 92,400 reads per second would hit the store. Protect the store with request coalescing, gradual cache warm-up, and load shedding (see the caching and resilience lessons).
- Edge: put a CDN or edge cache in front for very popular links with a short cache time. This only works for 301, or for a 302 with a short
Cache-Controland an accepted loss of exact click counts. - Multi-region: deploy redirect services and cache replicas near users, since the extra 100 ms or more between continents is added to every click. The links store is replicated to each region. Creation can go to one home region, because writes are rare.
- Allocator: if the central counter fails, servers continue with their current blocks for a while. Run the counter store with replication and keep a spare range per server.
- Monitoring: redirect latency (p99), cache hit rate, 404 rate (a spike can mean a scan), store errors and Kafka lag.
10. Common Pitfalls
- A single database sequence as the only code source, with no block allocation or replication.
- Hashing the URL and ignoring collisions.
- Too short a code, or no capacity calculation.
- Blocking the redirect on analytics.
- No negative caching, so scans reach the database.
- Using 301 and then needing analytics or expiry.
- A check-then-insert for aliases instead of one atomic conditional write.
- Accepting any URL, including
javascript:links and known phishing sites. - Making the store relational with joins for a pure key-value access pattern, then struggling at 36.5 billion rows.
11. Interview Questions This Lesson Prepares You For
- How do you generate unique short codes? A counter in base 62 with blocks handed to each server (no collisions, one central call per 100,000 links), or random codes with a conditional insert. Explain the trade-offs of hashing and pre-generated keys.
- How long should the code be? Compute the code space: 627 ≈ 3.5 trillion, against 36.5 billion links over 5 years, which leaves plenty of room.
- 301 or 302? 301 is cached by browsers, so it reduces load but loses analytics and control. 302 sends every click to us, so choose it when analytics or expiry matter.
- How do you handle 92,000 redirects per second? Redis in front of a sharded store with a high hit rate, stateless redirect servers behind a load balancer, and a CDN for hot links.
- How do you add click analytics without slowing the redirect? Publish an event asynchronously to Kafka and aggregate in a stream job. Counts are eventually consistent.
- How do you prevent two users from getting the same custom alias? An atomic conditional write on the code, so the second request fails with
409. - How would you protect the service from abuse? URL validation, a block list or safe-browsing check, rate limits, takedown tools and monitoring of unusual 404 rates.