System design interview guide
Design a URL Shortener
A marketer mints a short code, including a word they chose, and expects each tap to open the long page in under 100 ms even at 50,000 clicks a minute. The painful failure is the tap waiting on the database while about 200 new codes are created each second, because the hot code was never cached.

Problem statement
URL shortener: create long→short mapping, redirect at massive read QPS, optional custom aliases and analytics.
Introduction
A marketer mints a short code—sometimes a word they chose—and expects every tap to open the long page in under 100 ms, even at tens of thousands of clicks a minute. The painful failure is not “link not found.” It is the tap waiting on the database while creates keep writing, because the hot code was never cached.
Interviewers want that story: a URL shortener is a read-heavy redirect machine with a smaller create path. If you put the database on every click, the design already failed.
This guide walks one link from create to redirect. You will mint unique short codes, keep the mapping in a cache on the hot path, reject taken custom aliases, and send click counts off the redirect path.
How to approach
Do not open with a multi-region Kafka diagram. Open with the two APIs.
- Scope the product. Create long→short (optional custom alias + expiry). Redirect short→long. Count clicks async. Analytics dashboards stay thin unless asked.
- Name the ratio out loud. Reads often outnumber writes ~100:1. Optimize redirect first.
- Pick an ID story. Counter→base62, hash+retry, or random+retry. Custom aliases need a uniqueness check.
- Deep-dive one fight. Usually cache-on-redirect or collision handling. Leave multi-region as a short replication note.
- Close with failure. Cache miss storm, expired link, phishing alias, analytics backlog.
In the room: “I will optimize for redirect latency and unique codes first. I will accept eventual consistency on click counts, and strong uniqueness on the short-code mapping.”
Capacity estimation
Use the numbers as a story about where the system hurts—not as memorization.
| Signal | Rough estimate | What it implies |
|---|---|---|
| Creates | ~200/s peak (~500M/month) | Write path must be correct, not the biggest QPS |
| Redirects | ~20K/s peak (~50B/month) | Redirect is the hot path; cache or CDN required |
| Read:write | ~100:1 | Separate scaling stories for create vs redirect |
| Mapping size | ~15 TB over years | Shard/partition the store; plan expiry/archive |
| Code length | 6–8 base62 chars | Show the keyspace math (62^7 ≫ needed IDs) |
Implications:
- Redirect must hit cache/CDN most of the time.
- Analytics must not sit on the redirect critical path.
- ID generation must not become a single global lock.
- Storage growth needs TTL/archive, not endless one-table growth as the only plan.
Design decisions
| Decision | Choice | Why | Cost |
|---|---|---|---|
| Short code | Base62 from range-allocated counter (or hash/random + retry) | Unique, compact, scalable minting | Predictability if counter is naive; ranges need coordination |
| Mapping store | KV or SQL keyed by code | Simple id→URL lookup | Hot partitions on popular codes |
| Redirect | Cache (+ optional CDN/edge) then DB on miss | Sub-100 ms without DB every tap | Invalidation / stampede on miss |
| Custom alias | Unique index + reserved-word list | Product feature with clear reject | Extra write check; abuse surface |
| Analytics | Async event after redirect responds | Protects latency | Counts can lag |
| 301 vs 302 | 302 if every click must be counted; 301 if destination is permanent | Matches product need | 301 hides later clicks from your servers |
High-level architecture
[ Creator / API client ] -- POST /shorten --> [ API ]
|
[ ID service ]
mint code / alias check
|
[ Mapping DB ]
code → long URL, TTL
|
[ Clicker ] -- GET /{code} --> [ Edge / CDN ] --> [ Redirect service ]
| |
cache hit cache miss → DB
| |
+-- 302/301 ------> browser
|
[ Analytics queue ] → aggregate store
Who owns what. ID/create owns uniqueness. Mapping store owns truth. Redirect owns latency. Analytics owns counts and is allowed to lag.
In the interview: narrate one create, then one redirect that never waits on analytics.
Detailed design
Write path — create
- Client sends long URL, optional custom alias, optional expiry.
- If custom alias: check reserved words + uniqueness; reject if taken.
- Else mint a code (take next ID from a machine range, encode base62; or hash/random and retry on conflict).
- Insert
code → long_url, expires_atwith a uniqueness constraint. Conflict → retry mint or return alias taken. - Optionally warm cache. Return
https://short.example/{code}.
Read path — redirect
- Look up
codein edge/CDN or Redis. - On hit: if not expired, return redirect. Emit click event async.
- On miss: load from mapping DB, populate cache, redirect. Protect with singleflight/lock so one miss does not stampede the DB.
- Missing or expired → 404.
Analytics path
- After the redirect response is decided, enqueue
{code, ts, geo, ua}(sampled if needed). - Consumers aggregate counts. Dashboards read the aggregate store, never the redirect path.
Deep dive: unique codes without a global lock
The interview fight is often “how do you generate billions of unique short codes?”
- Range allocation: a small coordinator hands each create-worker a block of integers (e.g. 1M IDs). Workers encode locally in base62. No per-request lock on a single counter row.
- Hash of long URL: deterministic and dedupes identical URLs, but collisions need retry with a salt; custom aliases still need their own uniqueness path.
- Random: simple, but needs collision retry and enough entropy so codes are hard to guess.
- Say how long the code is and why the keyspace fits your create volume for years.
- For security, avoid trivially sequential public IDs if neighboring codes must stay private—add opacity (shuffle/permute) or longer random codes for sensitive links.
Key challenges
- Cache miss storms on popular or newly viral codes if singleflight is missing.
- Analytics on the hot path adding tail latency.
- Custom alias abuse (phishing, reserved brands) without a blocklist and rate limits.
- 301 browser caching vs needing accurate per-click counts.
- Expiry that still returns a correct 404 without scanning the whole table every time.
Scaling the system
- Scale redirect tier and cache horizontally; keep create tier smaller.
- Partition mapping by code prefix or hash.
- Replicate mapping read-locally for multi-region redirects; accept short lag on brand-new links.
- Put CDN/edge in front for the hottest codes when product allows.
- Archive or delete expired rows on a schedule; lazy-expire on read is fine as a first cut.
Failure handling
| Failure | What the user sees | What the system does |
|---|---|---|
| Cache miss spike | Slightly slower redirects | Singleflight + DB; widen cache TTL for hot keys |
| Create conflict | Retry or “alias taken” | Unique constraint is source of truth |
| Mapping DB blip | Some misses fail | Serve cache hits; fail create loudly |
| Analytics backlog | Counts lag | Redirect still succeeds; drain queue |
| Expired code | 404 | Check expires_at on read; async cleanup |
API design
Hottest calls:
| API | Purpose |
|---|---|
POST /api/shorten | Create mapping (optional alias, TTL) |
GET /{code} | Redirect |
GET /api/stats/{code} | Click aggregates (async-fed) |
Creator API Mapping Cache
|-- POST /shorten -->| | |
| |-- mint + insert ->| |
| |-- optional warm ---------------------->|
|<-- short URL ------| | |
Clicker Redirect Cache Mapping
|-- GET /{code} ---->| | |
| |-- get ----------->| |
| | miss ------------|-- get ----------->|
| |<-- URL -----------|<-- set -----------|
|<-- 302 ------------| | |
| |-- enqueue click (async) |
Green Dashboard. Angry Users. The Production Mindset System Design Interviews Expect.
Dashboards can be green while marketers rage. Classic case: create QPS and error rates look fine, but p99 redirect blew up because a viral code missed cache and every click hit the database—while analytics still reported “healthy.”
What it looks like. Support hears “the link is slow.” Average latency looks okay. Create path is quiet. One code owns the traffic.
Why it happens. Teams alerted on average latency and create errors, not on cache hit ratio or redirect p99 for hot keys.
What good teams do. Track cache hit rate, redirect p99, singleflight waiters, and create conflict rate. Alert when hit ratio drops under load. Prefetch or pin known campaign codes.
How to use this in an interview. One war story: viral code → cache miss storm → measure hit ratio + singleflight → fix. One failure, one metric, one fix.
Bottlenecks and tradeoffs
- Counter ranges vs random IDs: coordination vs collision retries.
- 301 vs 302: browser cache vs countable clicks.
- Strong consistency on every regional redirect vs faster local cache (new links may 404 briefly in a far region).
- Deduping identical long URLs saves storage but couples privacy and update semantics.
Interview tips
You might say: “Creates mint a base62 code from a range-allocated counter and store code→URL. Redirects read cache first, then DB on miss, and emit click events asynchronously.”
Interview Push: “What if two creates get the same code?”
Land here: “The mapping table has a uniqueness constraint. Conflict means retry with the next ID or reject a custom alias. The database is the source of truth, not the in-memory counter alone.”
You might say: “Click analytics never block the redirect response.”
Interview Push: “How do you keep redirects under 100 ms?”
Land here: “Cache (and CDN when allowed) on the read path, minimal hops, async analytics, and singleflight on miss so the DB is not stampeded.”
What should stick
- State read:write before picking stores.
- Redirect is a cache-first path; create is a smaller correctness path.
- Uniqueness is enforced by the mapping store, with a clear mint strategy.
- Custom aliases need uniqueness + reserved words.
- Analytics are async.
Key Takeaways
- Start from create + redirect, with the ratio spoken out loud.
- ID strategy + cache-first redirect + async analytics are the core trio.
- Measure cache hit ratio and redirect p99, not only create success.
- Keep multi-region and deep abuse tooling thin unless the interviewer asks.
Related Topics
- How to Prepare for System Design Interviews - Multi-week study plan and pacing
- Distributed Cache - Cache miss storms and singleflight patterns
- Rate Limiter - Protect create APIs from abuse
- Design Ticketmaster - Hot-key contention under spike traffic
- System design interview guides - Full guide catalog
Quick revision notes
The problem in your own words. Turn long URLs into short codes and redirect taps fast, without putting the database or analytics on every click.
The design in one breath. Mint unique codes (range counter→base62 or hash/random+retry), store code→URL, serve redirects from cache with DB fill on miss, and count clicks asynchronously. Custom aliases use a unique index.
The choices you must defend. ID strategy. Cache/CDN on redirect. 301 vs 302. Where analytics live. How expiry works.
The mistakes that cost points. DB on every redirect, global counter lock per create, analytics in the request path, and no collision/uniqueness story.
What interviewers expect
Redirect hot path under 100 ms—CDN, cache, minimal hops. ID strategy—base62 counter vs hash vs random; collision handling; custom alias uniqueness. Storage—SQL vs KV; separate analytics store. Scale math—state assumptions for writes/s and read QPS.
Interview workflow (template)
- Clarify requirements. Confirm functional scope, users, consistency needs, and which non-functional goals matter most (latency, availability, cost).
- Rough capacity. Estimate QPS, storage, and bandwidth so your data model and partitioning story are grounded.
- APIs and core flows. Define a minimal API and walk 1–2 critical read/write paths end to end.
- Data model and storage. Choose stores for each access pattern; call out hot keys, indexes, and retention.
- Scale and failure. Add caching, sharding, replication, queues, or fan-out as needed; say what breaks in failure modes.
- Tradeoffs. Name alternatives you rejected and why (e.g. strong vs eventual consistency, sync vs async).
Frequently asked follow-ups
- How do you generate unique short URLs?
- How do you handle redirects at billions of reads?
- SQL or NoSQL for the mapping?
- How do custom aliases work?
- How do you track click analytics without slowing redirects?
Deep-dive questions and strong answer outlines
How do you generate unique short codes?
Base62 from distributed counter (range per machine), or hash long URL + retry on collision. Custom aliases need unique index. Mention non-guessable IDs for security.
Redirect flow at scale?
Cache mapping in Redis/CDN; async DB on miss; 301/302 choice; geo DNS. Read path is 100:1—optimize reads.
Where is data stored?
KV or SQL for id→long URL; object store if large payloads; analytics in column store or stream.
Custom alias collision?
Check uniqueness on create; reserve blocked words; rate-limit creates per API key.
Analytics without slowing redirect?
Fire-and-forget event to Kafka; aggregate async; optional sampled logging on edge.
AI feedback on your design
After a practice session, InterviewCrafted summarizes strengths, gaps, and interviewer-style expectations—similar to a written debrief. See a static example report, then practice this problem to get feedback on your own answer.
FAQs
Q: 301 vs 302?
A: 301 permanent—browser caches; 302 if you may change destination or need click counting on every hit.
Q: Do I need multi-region?
A: For global latency yes—replicate mapping, CDN for redirect; mention eventual consistency on new links.
Q: How long are URLs?
A: 6–8 base62 chars ≈ billions of space; show you did the math.
Q: Expiration?
A: TTL column + lazy delete or compaction job; expired links return 404.
Practice interactively
Open the practice session to use the canvas and stages, then review AI feedback.