URL Shortener (Bitly)
Design a service that turns a long URL into a short link and redirects anyone who opens it.
Save, progress and topic tools
Problem statement
Save a destination once and resolve its short code on every visit. Redirects must stay fast even when click reporting falls behind.
Functional requirements
- Shorten a URL with an optional alias and expiry.
- Redirect active links to their destination.
- Let owners disable links and see approximate daily clicks.
Where to stop
Leave account management and custom domains for a follow-up. Neither changes how a code is claimed or a redirect is served.
Non-functional requirements
- Keep codes unique and generated codes hard to guess.
- Target redirects under 50 ms in-service and 100 ms from a same-region client.
- Target 99.99% redirect availability. Allow bounded staleness on reads and enforce unique alias claims on writes.
- Support 1B stored links and 100M daily active users. Redirects dominate traffic.
Scale assumptions
- 10M new links per day. Size writes for peak traffic and storage for retained links.
- 1B redirects per day. At roughly 100 opens per create, cache popular links.
Entities
| Record | Key fields |
|---|---|
| Link | Code, destination, owner, expiry, status, version |
| Create request | Owner + request ID → code and payload fingerprint |
| Click | Event ID, code, timestamp |
| Daily click total | One count per code and day, updated by click workers. |
API design
| Endpoint | Result |
|---|---|
POST/links | 201 · short URL / 409 · alias taken |
GET/{code} | 302 · Location header / 404 · missing or inactive |
DELETE/links/{code} | 204 · disabled / 412 · version changed |
GET/links/{code}/stats | 200 · daily counts for the owner |
High-level design
How to draw the four boundaries
How to draw this design
- CreateCreate service · code allocation
- StorePostgreSQL · link ownership
- RedirectRedirect service · Redis
- ReportKafka · click workers
Link creation commits to PostgreSQL. Redirects use Redis. Click reporting runs asynchronously.
- State ownership
- PostgreSQL owns the short-code mapping.
- Scale
- Cache popular links close to readers. Partition mappings when measured load or retained size warrants it.
- Correctness
- A unique constraint prevents two destinations from owning one code.
- Failure and recovery
- hot-key misses and cap fallback reads when Redis fails.
URL Shortener · create, redirect and report
Start with creation across the top. Follow the visitor through the middle. Reporting runs below the request path and writes daily totals separately from link mappings.
What changes if one link goes viral?
A single code accounts for half the clicks. Adding database partitions still sends those reads to the same partition. Cache the popular mapping near readers and combine simultaneous misses into one lookup.
Before caching closer to readers, agree on how quickly a disabled link must stop working. That deadline limits the cache lifetime.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Popular redirects miss together and can overload the mapping store.
One server can share a lookup among its waiting readers. Ten servers can still start ten reads. Cap total database reads and give excess callers a temporary error.
Read the journeys step by step
Create a link
Open a link
Count a click
High-level design component walkthrough
Link owner
Sends the destination and optional alias or expiry. If the response is lost, resends the same request ID and payload to recover the original link.
Why, tradeoff and connected operations
Retain the request ID when retrying creation.
Tradeoff: A timeout can hide a successful create.
Connected operations: POST /links; 201 · link ready
Link creation API
Checks the owner and destination, then proposes a random code or uses the requested alias. PostgreSQL decides which writer owns that code.
Why, tradeoff and connected operations
Commit the mapping and retry result together. Rate-limit creates and reject unsupported schemes.
Tradeoff: An automatic collision needs a fresh code.
Connected operations: POST /links; Insert unique code; 201 · link ready
Redirect API
Handles GET /{code}. Checks status and expiry before returning the destination, whether the mapping came from Redis or PostgreSQL.
Why, tradeoff and connected operations
A separate read path can scale with click traffic.
Tradeoff: Cache misses consume database capacity.
Connected operations: GET /{code}; Look up by code; Miss · read row; Cache until expiry; 302 · Location; Emit click event
PostgreSQL
Stores the destination, owner, status, version and expiry. A unique index settles competing claims. Separate tables hold create-request results and daily click totals.
Why, tradeoff and connected operations
One transaction enforces uniqueness and records the result for retries.
Tradeoff: Growing indexes and retained links consume disk.
Connected operations: Insert unique code; Miss · read row; Commit count + ID
Redis mapping cache
Holds a versioned copy of a link for fast reads. A cache miss says nothing about whether the link exists. The redirect service asks PostgreSQL.
Why, tradeoff and connected operations
Memory lookups absorb most repeated reads.
Tradeoff: Missed invalidations can leave a stale entry.
Connected operations: Look up by code; Cache until expiry
Kafka click log
Retains accepted click events so workers can catch up after a pause. Each event carries a stable ID for recognizing retries.
Why, tradeoff and connected operations
Consumers can replay retained events after an outage.
Tradeoff: A full publisher buffer can drop clicks.
Connected operations: Emit click event; Read retained clicks
Click aggregation workers
Groups clicks by code and day. Records the event ID and increments the count together before acknowledging progress.
Why, tradeoff and connected operations
Reporting can catch up independently of redirects.
Tradeoff: Recent totals may lag.
Connected operations: Read retained clicks; Commit count + ID
Visitor’s browser
Requests the short code, receives a destination in the Location header, then makes a separate request to that site. A redirect alone cannot confirm that the page loaded.
Why, tradeoff and connected operations
The browser makes the next request directly to the destination.
Tradeoff: A redirect only proves that the shortener issued a response.
Connected operations: GET /{code}; 302 · Location
Simulation and engineering control room
Deep dives — decisions, failures and recovery
How should we generate short codes?
| Approach | How it works | What you give up |
|---|---|---|
| Random Base62 (our choice) | Pick letters and digits. Insert the code into a unique index. | Retry if the generated code is taken. Longer codes reduce collisions. |
| Counter in blocks | Give each server a separate range of numbers to encode. | Generated IDs stay unique, but sequential codes are easy to guess. |
| Hash the destination | Use part of a URL fingerprint as the code. | Different URLs can collide. Reusing a code also couples owners who need separate expiry or stats. |
90-second interview summary
I would split link creation from redirects. The create service validates the destination, generates a short code and saves it in PostgreSQL. A unique constraint settles collisions. Saving the request ID in the same transaction lets the client retry safely if the response is lost.
Most traffic is redirects, so I would check Redis first. If a popular code disappears from cache, each server shares its lookup among waiting requests. I would limit total fallback reads to protect PostgreSQL. The redirect includes the destination in the Location header.
Click reporting runs through Kafka. A reporting delay is acceptable for basic counts, as is losing some clicks during a prolonged outage. For disabled links, version checks and expiry bound how long cached data can be used. If a region fails, I would keep a single writer and return a temporary error wherever the surviving replica cannot give a trustworthy answer.
Test your design decisions
Redraw the system from memory
Draw the create and redirect paths. Mark where a code becomes unique and where a click can be lost.
A create request times out. Can the client retry?
Reveal answer
Yes. Reuse the same request ID and payload to recover the committed result.
How do a missing link and an unavailable database differ?
Reveal answer
Return 404 for an authoritative miss and 503 when the lookup cannot be completed.
Can a reporting outage break a valid link?
Reveal answer
The redirect remains available. A full event buffer can leave click counts incomplete.
Rehearsal checklist
- Trace a cache hit and a miss.
- Defend the alias claim and retry rule.
- State the limit on stale redirects.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope link creation and redirection. Estimate redirect traffic, the read-to-write ratio, and the number of codes needed. |
| 15–30 min | High-level design | Draw the create service, redirect service, PostgreSQL and Redis. Add the Kafka branch for click counts. |
| 30–45 min | Deep dives | Explain collision handling and how a popular link can be served without a database lookup on every redirect. |
| 45–55 min | Failure and recovery | Walk through a hot link losing its cached copy. misses, bound database reads, and explain when to shed load. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |