System Design blueprint · Marketing & SaaS
URL shortener
How a link like sho.rt/abc123 is created once and resolved millions of times.
- Steps
- 6
- Subjective questions
- 32
- Objective questions
- 32
The problem and the outcome
Problem: Links in SMS, print and QR codes must stay short and resolve instantly at huge read volume.
Outcome: Billions of redirects served from cache in milliseconds.
Architecture
How it works, step by step
- The client sends a long URL to shorten, or opens a short code.
- A load balancer spreads requests across stateless app servers.
- Writes take a unique ID and encode it in Base62: 7 characters give about 3.5 trillion codes.
- Reads check the cache first, because a few hot links get most of the traffic.
- On a miss, the database lookup fills the cache for the next reader.
- The service answers with a 301/302 redirect to the long URL.
Tech stack
- Nginx / cloud load balancer
- Stateless app servers
- Redis cache
- Cassandra or DynamoDB
- Snowflake-style ID service
- CDN for redirects
Key design decisions
- Counter-based IDs encoded in Base62 instead of hashing the URL: no collisions to check, and codes stay short.
- A key-value store keyed by code: every read is a single lookup by primary key, which scales horizontally.
- 302 when you need click analytics on every visit; 301 when you want browsers and CDNs to cache the redirect.
Common mistakes
- Hashing the long URL and truncating it, then discovering collisions at scale.
- Sequential codes that let anyone enumerate every private link.
- Writing a click-analytics row synchronously on every redirect, which turns the hot read path into a write path.
What to measure
- Redirect p99 latency (target: tens of milliseconds)
- Cache hit ratio on hot codes
- Read:write ratio, often 100:1 or more
Most-asked interview questions
Subjective questions 32
1How would you generate unique short codes across many servers?Asked almost every time
Give each server a block of numeric IDs from a central counter (or use a Snowflake-style ID with machine bits), then encode the number in Base62. Seven Base62 characters cover about 3.5 trillion codes. Pre-allocated ranges mean no coordination on each write, and there is never a collision to resolve.
2What are the functional and non-functional requirements of a URL shortener?Asked almost every time
Functional: create a short link for a long URL, redirect from the short code, optional custom aliases, expiry and click analytics. Non-functional: very low redirect latency, high availability for reads, durability of mappings, unpredictable codes to prevent enumeration, and a read-to-write ratio often above 100:1.
3Walk through the high-level architecture of a URL shortener.Asked almost every time
Clients call a write API that validates the URL, generates a code and stores the mapping in a key-value store. Redirect requests hit a CDN or edge cache first, then a stateless redirect service backed by a cache (Redis) and the store. Click events go to a queue and an analytics pipeline asynchronously.
4How do you prevent collisions when generating codes?Asked almost every time
Use a unique counter or ID generator (database sequence, Snowflake IDs or pre-allocated ranges per server) and Base62-encode it, which cannot collide. With random or hashed codes, insert with a uniqueness constraint and retry on conflict.
5Hashing the long URL vs. a counter: which is better?Asked almost every time
Hashing (MD5 or SHA, truncated) gives the same code for the same URL but truncation causes collisions that need checks. A counter with Base62 is collision-free and short, but sequential codes are guessable unless you shuffle or encrypt the ID. Many designs use counter ranges plus a bijective scramble.
6Estimate the storage for 100 million new links a month kept for 5 years.Very often asked
100 M × 12 × 5 = 6 billion links. At roughly 500 bytes per record (code, long URL, owner, timestamps) that is about 3 TB, before replication. With three replicas, plan for around 9–10 TB. The point is to show the method: volume × record size × retention × replicas.
7How do you keep redirects fast when one link goes viral?Very often asked
Serve redirects from cache: an in-process LRU plus Redis, with the CDN caching 301 responses at the edge. Hot keys can be replicated across cache nodes. The database is only hit on a miss, and that result fills the cache for everyone after.
8How do you support custom aliases?Very often asked
Check the requested alias against a reserved word list and profanity filter, then insert it with a uniqueness constraint in the same namespace as generated codes; return a conflict if taken. Generated codes can use a different length or character set to avoid clashing.
9How do you handle link expiry?Very often asked
Store an expires_at with the mapping, check it on redirect and return 404 or 410 when expired, and clean up expired rows with a background job or the store's TTL feature. Set CDN cache lifetimes shorter than the remaining expiry.
10How do you collect click analytics without slowing redirects?Very often asked
Respond with the redirect immediately and publish a click event (code, timestamp, referrer, country, user agent) to a queue or log. Stream processors aggregate counts into a time-series or OLAP store for dashboards.
11How do you prevent abuse such as phishing links?Very often asked
Rate-limit link creation per user and IP, check destinations against safe-browsing and malware lists at creation and periodically, require accounts for high volume, allow reporting, and be able to disable a code instantly at the edge.
12How do you scale the database for billions of links?Very often asked
A key-value or wide-column store (DynamoDB, Cassandra) partitioned by code scales horizontally. Reads are served mostly from cache, writes are light, and replication across zones provides durability.
13How do you make redirects highly available?Very often asked
Run stateless redirect servers in multiple zones behind a load balancer, keep a replicated cache, serve popular codes from the CDN, and if the cache fails, fall back to the replicated store with a circuit breaker to avoid overload.
14301 vs. 302 redirects: which do you use and why?Very often asked
A 301 lets browsers and CDNs cache the redirect, reducing load, but you lose visibility of repeat clicks and cannot easily change the destination. A 302 (or 307) sends every click to your service, enabling analytics and edits. Many shorteners choose 302 for analytics.
15How would you support links that open different destinations on mobile and desktop?Very often asked
Store a set of rules with the mapping (device type, OS, country) and evaluate them in the redirect service using the User-Agent and geo headers. Keep a default destination, cache the rule set with the code, and avoid CDN-caching responses that vary unless the cache key includes the deciding header.
16How do you design a QR code feature on top of the shortener?Very often asked
Generate the QR image from the short URL, not the long one, so the printed code keeps working if the destination changes. Render on demand and cache the PNG or SVG in object storage behind the CDN, and tag QR scans with a parameter so analytics can separate them from link clicks.
17How long should codes be?Often asked
Size them for the expected total number of links with headroom: 62^7 is about 3.5 trillion codes. Start with 6 or 7 characters and allow growth; shorter codes are easier to share but run out sooner and are easier to guess.
18How do pre-allocated ID ranges work across servers?Often asked
A coordinator (or database) hands each app server a block of IDs, such as 1,000,000 at a time. Servers generate codes locally from their block without coordination and request a new block when exhausted, avoiding a hot sequence.
19How do you make codes non-sequential while staying collision-free?Often asked
Apply a reversible permutation to the numeric ID, such as format-preserving encryption or multiplication by a large odd number modulo the code space, then Base62-encode. Each ID still maps to one unique code, but neighbours look unrelated.
20How do you deduplicate the same long URL?Often asked
Optionally keep an index from a hash of the normalised long URL to its code, per user, and return the existing code. Many services skip global dedup because different users want separate analytics.
21How would you design the API?Often asked
POST /links with the long URL, optional alias and expiry returns the short URL; GET /{code} redirects; GET /links/{code}/stats returns analytics; DELETE /links/{code} disables it. Authenticate write and stats endpoints and rate-limit creation.
22What caching strategy fits redirects?Often asked
Cache-aside with Redis keyed by code, a long TTL since mappings rarely change, LRU or LFU eviction, plus CDN caching for the hottest codes. Invalidate on edit or delete.
23How do you estimate redirect QPS for capacity planning?Often asked
If 100 million links are created a month and each is read about 100 times, that is roughly 10 billion redirects a month, about 3,800 per second on average, with peaks several times higher. Size caches and servers for peak with headroom.
24How would you migrate to a new code format?Often asked
Keep old codes valid forever in the same store, generate new ones with the new scheme or prefix, and make the redirect service understand both. Never reuse codes.
25How would you let a team share and manage links under a branded domain?Often asked
Map each custom domain to a workspace, verify ownership with a DNS TXT record, provision TLS automatically, and namespace codes per domain so two domains can reuse the same code. The redirect service resolves the Host header first, then the code within that domain.
26How do you count unique visitors rather than raw clicks?Often asked
Derive a privacy-safe visitor key, such as a hash of IP prefix and user agent with a daily salt, and feed it to a HyperLogLog per link and day. HyperLogLog gives approximate distinct counts in a few kilobytes and merges across days or servers.
27How would you let users edit the destination of an existing link?Often asked
Update the mapping in the store, invalidate the cache key and purge the CDN entry, and keep an audit history of previous destinations. Because 302 redirects are not cached by browsers, the new destination takes effect on the next click.
28How do you design bulk link creation for a marketing campaign?Often asked
Accept a file or batch API call, validate and enqueue it, then generate codes from a pre-allocated ID block in a worker so the request returns quickly. Report progress and return a downloadable mapping of long URL to short code when done, with per-row errors.
29What security headers or checks apply to the redirect response?Sometimes asked
Validate that destinations use http or https only, avoid open redirects within your own domain, set no-referrer or a strict referrer policy if needed, and show an interstitial warning for flagged destinations.
30How do you handle a deleted link that is cached in CDNs?Sometimes asked
Purge the code from the CDN cache via its API when it is deleted or disabled, and keep CDN TTLs moderate so stale redirects expire even if a purge fails.
31What would you monitor for a URL shortener?Sometimes asked
Redirect latency percentiles, cache hit rate, error rates (404s and 5xx), creation rate per user, queue lag for analytics, storage growth and abuse reports.
32How would you keep the system compliant with data-retention rules?Sometimes asked
Separate link mappings from click logs, keep raw click data only as long as policy allows, aggregate older data into counts that hold no personal data, and support deleting a user's links and analytics on request, including from backups on their normal rotation.
Objective questions 32
1Which redirect status lets browsers cache the mapping and skip your server next time?Asked almost every time
Why: 301 is permanent, so browsers and CDNs may cache it. That saves load but hides later clicks from your analytics.
2What is the typical read-to-write ratio of a URL shortener?Asked almost every time
Why: Each link is created once and clicked many times.
3Which ID approach never collides?Asked almost every time
Why: Each counter value maps to exactly one code.
4Where should click analytics be recorded?Asked almost every time
Why: Redirect latency stays low when analytics are async.
5How many distinct codes do 7 Base62 characters give?Very often asked
Why: 62⁷ ≈ 3.52 × 10¹², roughly 3.5 trillion.
6Why might a shortener choose 302 over 301?Very often asked
Why: 301 lets browsers skip your server next time.
7What makes sequential codes a security concern?Very often asked
Why: Attackers can guess other users' links.
8What does a pre-allocated ID range avoid?Very often asked
Why: Servers generate codes locally from their block.
9How should expired links respond?Very often asked
Why: 410 Gone tells clients it was removed on purpose.
10Which store fits billions of code lookups best?Very often asked
Why: Lookups by key scale horizontally.
11What should happen when a destination is flagged as malware?Very often asked
Why: Abuse must be stoppable quickly.
12About how many codes do 6 Base62 characters give?Very often asked
Why: 62 to the power of 6.
13Which data structure estimates unique visitors in a few kilobytes?Very often asked
Why: HyperLogLog trades a small error for fixed, tiny memory per counter.
14What should a QR code encode for a short link?Very often asked
Why: Encoding the short URL keeps printed codes working when the destination changes.
15Which store fits the code → URL mapping best at very large scale?Often asked
Why: The access pattern is a lookup by key with no joins, which is exactly what key-value and wide-column stores scale for.
16Which cache eviction policy suits popular links?Often asked
Why: Hot codes stay in memory.
17What should custom aliases be checked against?Often asked
Why: Avoid conflicts with routes and other links.
18Which request creates a short link in a REST design?Often asked
Why: Creating a resource is a POST.
19What makes neighbouring IDs produce unrelated codes?Often asked
Why: Still collision-free, but not guessable.
20Roughly how many redirects per second is 10 billion a month?Often asked
Why: 10 billion divided by about 2.6 million seconds.
21Which schemes should destinations be limited to?Often asked
Why: Other schemes enable attacks.
22What should happen to old codes after a format change?Often asked
Why: Links in the wild must not break.
23Why rate-limit link creation?Often asked
Why: Bulk creation is a common abuse vector.
24What proves a customer owns a custom short domain?Often asked
Why: A DNS record can only be added by whoever controls the domain.
25When a destination is edited, what must be cleared?Often asked
Why: Stale cached redirects would keep sending users to the old page.
26How should a bulk import of 50,000 links be processed?Often asked
Why: Long jobs belong in a queue so the request can return immediately.
27Device-specific redirects require the CDN cache key to include…Often asked
Why: Otherwise one device's redirect would be served to every device.
28What must happen to a deleted link cached at the CDN?Sometimes asked
Why: Otherwise the CDN keeps redirecting.
29Which metric shows how well the cache protects the store?Sometimes asked
Why: Low hit rates push load to the database.
30Why is global deduplication of long URLs often skipped?Sometimes asked
Why: Per-user dedup is more common.
31What protects redirects if the cache cluster fails?Sometimes asked
Why: Prevents a stampede on the store.
32What should happen to raw click logs after the retention period?Sometimes asked
Why: Aggregates keep analytics useful without holding personal data.
Track your progress through every blueprint in your dashboard.
Start learning