SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a URL Shortener
  • Design Pastebin
  • Design a Rate Limiter
  • Design a Unique ID Generator
  • Design a Key-Value Store
  • Design a Scalable Parking System (Smart Parking)
System Design/Case Studies/Easy
Interview case study

Design a URL Shortener

Turn long links into short ones (like bit.ly) and redirect fast. The classic first design question.

⏱ 30 min readEasy case studyBeginner24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a URL shortener, like bit.ly.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Asking before drawingThe prompt has no numbers and no features. A strong candidate makes it specific first (custom links? expiry? analytics? how many?).
Estimation that drives the designRead-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 generationThis 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 performanceA redirect must feel instant. Caching, hot links, and what happens when the cache or database is down.
Judgement and trade-offs301 or 302, consistency of analytics, reuse of expired codes, abuse. There is no single right answer, only reasoned ones.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 100M new links a month is only about 40 writes per second and 4,000 redirects per second. 6 billion links in 5 years is about 3 TB, small for storage.
  • Codes: 7 base62 characters give 3.5 trillion codes, so 6 billion links use 0.17% of the space.
  • Code generation: a counter handed out in ranges, scrambled, then written in base62. No collisions, no per-request coordination.
  • Storage: a key-value store partitioned by code (hash), replicated across zones. A conditional write keeps codes unique.
  • Read path: Redis in front (cache-aside), a short in-process cache for hot links, HTTP 302 so every click can be counted and a link can change or expire.
  • Analytics: click events go to a queue, off the redirect path, and are counted later. A broken analytics pipeline must never break a redirect.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Scope: custom alias, expiry, analytics, scale. Say what is out of scope.
2. Estimate3Writes per second, reads per second, storage, cache size, code length.
3. API and data5Two endpoints, the record, and why a key-value store fits.
4. High-level design8Boxes, one write path, one read path.
5. Deep dives15Code generation, then the read path. Custom aliases, expiry and analytics if time allows.
6. Scale and failures7Hot links, cache down, database down, abuse, monitoring.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write down five questions that would change your design. Hint: think about who creates links, who clicks them, how long they live, and what you must be able to report.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Create a short link from a long URL
  • •Open a short link and be redirected to the long URL
  • •Optional custom alias and optional expiry date
  • •Owners can disable or delete their links
  • •Basic click counts per link (a few minutes late is fine)
Non-functional (how well)
  • •Redirects: 99.99% available, under 100 ms at the server
  • •Read-heavy: about 100 redirects for every new link
  • •Codes: unique, short, and not easy to guess in order
  • •Durable: a saved link must never be lost
  • •Scale: 100M new links a month, 5 years of data
Out of scope (say it)
  • •Link previews and QR codes
  • •A full analytics product (maps, devices, funnels)
  • •Branded custom domains
  • •Editing the long URL after creation
🎤
Say it out loud
“Let me confirm the scope. We create short links, optionally with a custom name and an expiry, and we redirect them. We need basic click counts, but they can be a few minutes late. I will design for about 100 million new links a month with roughly 100 redirects per new link, 99.99% availability on redirects, and five years of data. I will leave previews, QR codes and branded domains out. Does that match what you have in mind?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
Work out, on paper: writes per second, reads per second, and total storage for 5 years. Then ask: how many characters does the code need? Do this before you read the table.

Assumptions (say them first)

AssumptionValue
New links per month100 million
Read to write ratio100 : 1
Peak traffic vs average3 times the average
Size of one saved link (code, long URL, owner, dates)about 500 bytes
Retention5 years
Cache hit rate we aim for90% or better
Click event sizeabout 100 bytes
One app server can handleabout 2,000 redirects per second

The arithmetic, line by line

WhatMathsResult
New links per second (average)100,000,000 ÷ (30 × 86,400 s) = 100M ÷ 2.6Mabout 40 per second
New links per second (peak)40 × 3about 120 per second
Redirects per second (average)40 × 1004,000 per second
Redirects per second (peak)4,000 × 312,000 per second
Links stored after 5 years100M × 12 months × 5 years6 billion links
Possible 7-character codes62^73.5 trillion
How much of that space we use6 billion ÷ 3.5 trillion0.17%
Storage for 5 years6 billion × 500 bytes3 TB (about 9 TB with 3 copies)
Redirects per day4,000 × 86,400about 346 million
Cache size (80/20: keep the hottest 20%)0.2 × 346M × 200 bytesabout 14 GB
Database reads after the cache (90% hits)4,000 × 10%400 per second (1,200 at peak)
Redirect bandwidth at peak12,000 × 0.5 KB6 MB per second, about 48 Mbit/s
Click events per day4,000 × 100 bytes × 86,400about 35 GB per day
App servers for peak load12,000 ÷ 2,000, then 3 zones so one can fail6 needed, so 9 (3 per zone)
What the numbers tell us about the design
  • •40 writes per second is tiny. Writes are not the problem. Reads and availability are.
  • •3 TB is small. The data fits on a few machines. We shard for headroom, replication and operations, not because we must.
  • •7 characters is plenty: we use 0.17% of the space. 6 characters (56.8 billion codes) would also fit, at 10.6% used, but leaves less room to grow.
  • •The hot set (about 14 GB) fits in memory, so a cache can serve almost every redirect.
  • •Analytics is a bigger data stream (35 GB a day) than the links themselves, so keep it away from the redirect path.
🎤
Say it out loud
“Let me do the maths. 100 million a month is about 40 writes a second, 120 at peak. With 100 reads per write, that is 4,000 redirects a second, 12,000 at peak. Over five years that is 6 billion links, and at 500 bytes each, about 3 terabytes. Seven base62 characters give 3.5 trillion codes, so we use under 1% of the space. The hot set is about 14 gigabytes, so a cache serves nearly everything. The takeaway is that this is a read-heavy, availability-driven system, not a big-storage one.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the two endpoints you cannot do without, and the record you store. Which field is the key? What would you index?

Endpoints

MethodPathRequestResponseNotes
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}none302 Location: longUrlThe 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}/statsnone200 { total, byDay: [...] }Owner only. Counts can be a few minutes behind.
DELETE/v1/links/{code}none204Owner only. Marks the link deleted and removes it from the cache.

Data model

Field (links table)TypeNotes
code (key)string, up to 20Short code or custom alias. Partition key. Unique.
long_urlstring, up to 2,048The target. Validated and normalised.
owner_ididWho created it. Used for limits and the delete check.
created_attimestampFor listing and for support.
expires_attimestamp, optionalNull means never. Indexed for the cleanup job.
statusactive | disabled | deleted | blockedLets us stop a link without deleting data (and re-enable it).
Other storesHoldsKey
owner_links (secondary index)A user's links, newest firstowner_id, then created_at
click events (queue, then analytics store)One event per redirectcode, time, country, referrer
click_daily (aggregate table)Clicks per link per daycode, day
code ranges (small counter store)The next unused range of the counterone row
One saved link (example)
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"
📝Which store, and why
Every redirect is one lookup by key, and every create is one insert if the key is free. There are no joins and no range scans, so a key-value store (DynamoDB or Cassandra style, partitioned by code) fits well. A relational database with a unique index on code is also fine at 3 TB if you shard it. What matters is a conditional write: insert only if the code does not exist (a unique constraint, or put-if-absent). Pick one and say why. Do not spend long here.
🎤
Say it out loud
“Two main endpoints. POST /v1/links takes the long URL and an optional alias and expiry, and returns the short URL. GET /{code} returns a 302 with the long URL. The record is small: code as the key, long URL, owner, dates and a status. All access is by code, so I will use a key-value store partitioned by code, with a conditional write to keep codes unique.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes for a create request and a redirect request. Where does the cache sit? What stays out of the redirect path?
URL shortener: high-level design
👤Clientbrowser or API
→↓HTTPS
🌍CDN / edgeoptional, short TTL
→↓
⚖️Load balancerhealth checks
→↓
Stateless app servers (3 zones)
✍️Create servicevalidate, make code, save
↪️Redirect servicelook up, answer 302
Hot path
⚡Redis cachecache-aside, about 14 GB
↓miss
🗄️Key-value storesharded by code, 3 copies
Code ranges
🔢Range servicehands out 1M-code ranges
asked once per range, not once per link
Analytics (off the hot path)
📨Queue (Kafka)click events
↓
🧮Aggregatorcounts per link per day
↓
📊Stats store
Solid path = redirect (hot). The counter store is touched only once per range. Analytics runs on the side.
ComponentWhat 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 balancerSpreads traffic over app servers in three zones, and removes sick servers using health checks.
Create serviceValidates the URL, checks it is safe, takes the next code from its local range, saves it with a conditional write.
Redirect serviceLooks the code up (cache first), checks status and expiry, returns 302, and sends a click event without waiting for it.
Redis cacheHolds the hot links in memory. Cache-aside with a TTL that never outlives the link's expiry.
Key-value storeThe source of truth. Partitioned by hash of the code, three copies in different zones.
Range serviceA tiny, strongly consistent store (a database row, or ZooKeeper or etcd) that gives each app server a block of unused counter values.
Queue and aggregatorReceive click events, count them, and write daily totals. If they fall behind, redirects are not affected.
Write path (follow one request)
  1. Client sends POST /v1/links with the long URL (and maybe an alias and expiry).
  2. The create service checks the API key, applies the rate limit, and validates the URL (scheme http or https, length, not a link back to us).
  3. It checks the URL against a block list and a safe-browsing service.
  4. If there is no custom alias, it takes the next number from its local range, scrambles it, and writes it in base62 (7 characters).
  5. It saves the record with a conditional write (insert only if the code is free). If an alias is taken, it answers 409.
  6. It returns 201 with the short URL. It may also put the new link into the cache so the first click is fast.
Read path (follow one request)
  1. Browser opens https://sho.rt/k3Fz9aQ and reaches an app server through the load balancer.
  2. The redirect service looks in its small in-process cache, then in Redis.
  3. On a miss it reads the record from the key-value store (a nearby replica) and fills Redis. Unknown codes are cached briefly as ‘not found’.
  4. It checks status and expiry. Disabled or deleted links answer 410, expired ones 410, unknown ones 404.
  5. It drops a click event onto the queue without waiting (fire and forget).
  6. It answers 302 with the Location header set to the long URL.
🎤
Say it out loud
“Here is the picture. Clients reach stateless app servers through a load balancer. For a redirect, the server checks an in-process cache, then Redis, and only then the key-value store, which is the source of truth, sharded by code. It answers 302 and sends a click event to a queue without waiting. For a create, the server takes the next number from a range it already owns, turns it into a 7-character base62 code, and saves it with a conditional write. A small range service hands out those ranges, so it is touched about once per million links.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Making unique short codes

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.

OptionHow it worksGoodBad
Hash the long URL, keep 7 charactersMD5 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 base62One 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 checkMake 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).
Pick
A counter handed out in ranges, scrambled, then written in base62

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 serverTakes rangeNext numberCode (before scramble)
A0 to 999,9991250000021
B1,000,000 to 1,999,9991,000,0000004c92
C2,000,000 to 2,999,9992,000,0010008oi5
On each create request (sketch)
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 code
⚠️Be honest about the scramble
A simple ‘multiply by a constant, then take the remainder’ scramble hides the order from a casual look, but it is not secure: someone who collects a few codes can work out the constant. If guessing must be hard, use random codes (or a keyed shuffle such as a Feistel network). Also say the key point: a short link is not a secret. Never put private content behind a short link without a login.
📝How hard is guessing, in numbers?
With 6 billion of 3.5 trillion codes in use, a random guess hits a real link 0.17% of the time. At 1,000 guesses a second, an attacker finds a live link about every 0.6 seconds. Two defences: rate limit by IP, and use 8 characters (62^8 is 218 trillion, so a guess hits only 0.003% of the time).
🎤
Say it out loud
“I will compare four ways. Hashing is stateless but collides, about five million pairs at our size, so it needs a check and retries. A single counter never collides but is a bottleneck and guessable. Random codes plus a check are simple, and a key service pre-makes codes. I would pick a counter handed out in ranges: each app server owns a block of a million numbers, so no two servers collide and the range service is touched about once every few days per server. I scramble the number so codes are not in order, and write it in base62 at 7 characters.”
5.2

Making redirects fast and always available

The 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.

OptionHow it worksGoodBad
Database onlyEvery 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 serverA 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 cachingLet 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.
Pick
Layers: in-process cache, then Redis (cache-aside), then replicated key-value store

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.

ProblemWhat 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 deleteOn disable or delete, remove the key from Redis. In-process copies expire in seconds. Say this delay is accepted.
Cache entry outliving the linkSet the TTL to the smaller of the normal TTL and the time left before expires_at.
🎤
Say it out loud
“A redirect should almost never reach the database. I would layer it: a one to five second in-process cache for viral links, then Redis with cache-aside holding the hot 14 gigabytes, then the replicated key-value store. That cuts database reads to about 400 a second. I would protect against stampedes by letting one request per code refill the cache, cache not-found answers briefly, and keep the cache TTL below the link's expiry. If the database is down, cached links still redirect.”
5.3

Custom aliases, expiry and cleanup

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.

OptionHow it worksGoodBad
Check, then insertRead 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 readWhen 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.
Pick
Conditional insert for aliases, plus lazy delete on read and a background sweeper for expiry

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.

💡Keep custom names apart from generated codes
Generated codes could, by chance, equal someone's custom alias. Avoid this by rule: for example, custom aliases must be at least 8 characters or contain a hyphen, while generated codes are always 7 letters and digits. The conditional insert stays as a safety net.
Alias ruleWhy
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 wordsBrand safety and abuse.
Decide on case: treat ‘Sale’ and ‘sale’ as different (base62 is case sensitive), or fold to lower casePick one rule and say it. Mixing causes support problems.
Soft delete first (status = deleted), hard delete after a retention periodAllows undo and lets us purge caches and queues in order.
🎤
Say it out loud
“For custom aliases I avoid check-then-insert, because two people can both see it free. I use one conditional insert that fails if the key exists, and return 409. I keep custom names apart from generated codes by a simple rule, such as at least 8 characters. For expiry, every read checks expires_at, so links stop on time, and a background sweeper deletes in small batches. I would not reuse an expired code for a long time, because old links in emails could then point at a stranger.”
5.4

Counting clicks without slowing redirects

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.

OptionHow it worksGoodBad
Increment a counter in the link rowUPDATE 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 batchesEach 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.
Pick
Fire-and-forget events through a queue, then stream aggregation into daily totals

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.

🎤
Say it out loud
“I never want a counter write on the redirect path. The server sends one small event to a queue and answers right away. An aggregator turns events into counts per link per day, so stats are a few minutes late, which we agreed is fine. If the queue is unhealthy we drop analytics, not redirects. Delivery is at least once, so I de-duplicate by event id, or accept a small error for plain click counts.”
VisualizerShort codes: strategy, length and collisionsSwitch between hashing, a counter and random codes. Slide the length and the number of stored links to see how much of the space is used and how many retries a new link needs. Then type a counter value to see its base62 code.
How are short codes made?
An example short link
sho.rt/3OLD2Wh
looks random, but is a fixed demo value (this page uses no random numbers)
Possible codes
62^7
3,521,614,606,208
Space used
0.03%
1.0 billion links stored
Tries per new link
1.0003
average, with a check
Clashing pairs without a check
142 thousand
birthday estimate
Plenty of room (0.03% used), so almost every insert succeeds on the first try (1.0003 tries on average). But about 142 thousand pairs of links would share a code if you did NOT check. At this size the check must exist: a collision is rare, not impossible.
Try the base62 encoder

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.

Without padding it is 21. Check by hand: 125 = 2 × 62 + 1, so its digits are “2” and “1”, which is “21”.

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.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Ask yourself: if traffic grows 100 times, what breaks first? If one zone disappears, what still works? If one link goes viral, what happens?

What breaks first, and the fix

BottleneckFix
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 serviceIt 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 shardsA separate index keyed by owner, so it does not scan every shard.
Global users far from the serversServe reads from regional replicas and caches. See the multi-region question below.

What if a part fails?

FailureHow the design copes
A cache node failsConsistent 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 downFall 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 failsThree copies in three zones. Reads and conditional writes continue on the others. The load balancer drops dead app servers.
The database is unreachableCached links keep redirecting. Creates return 503 with Retry-After. Reads are the priority.
The range service is downServers keep using the block they hold (days of codes). Alert early, restore, no user impact.
An app server crashes with part of a rangeThe rest of its range is simply never used. Nothing to repair.
The analytics pipeline is down or behindRedirects are unaffected. Events are buffered or dropped. Counts catch up when it recovers.
What to monitor
  • •Redirect latency (p50, p95, p99) and error rate, split by 302, 404 and 410
  • •Cache hit rate at each layer, and database reads per second
  • •Creates per second, 409 conflicts and 429 rate-limit hits
  • •Range service: free numbers left per server and age of the last reservation
  • •Queue lag for click events, and aggregator errors
  • •Rate of newly blocked links and abuse reports
Security and abuse
  • •Only allow http and https targets. Block javascript:, data: and file: links.
  • •Check each target against a safe-browsing list at creation, and re-check popular links later, because a page can turn bad.
  • •Rate limit creation by user, API key and IP, with stricter limits for anonymous users. Ask for a CAPTCHA when a pattern looks like spam.
  • •A shortener is an open redirect by design. Show a warning page for unknown or flagged targets, and give people a way to report a link.
  • •Disabling a link must work fast: set status = blocked, then purge the cache.

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat 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 hashingNo 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 TTLsVery fast redirects and a database that stays calm.A disabled link may still redirect for a few seconds from some caches.
Analytics through a queueRedirects never wait for counting.Counts are a few minutes late and may be slightly off.
A key-value storeSimple, horizontal scale, conditional writes.Fewer ad hoc queries than SQL. Listing needs a secondary index.
A new code for every create requestEach link has its own owner, expiry and stats.Several codes may point to the same URL, which uses more storage.
If we had more time, we would…
  • •Multi-region: regional replicas and caches, and separate code ranges per region so codes stay unique.
  • •A richer analytics product: referrers, devices, funnels, unique visitors.
  • •Stronger abuse tools: link reputation, phishing detection, review queues.
  • •Branded custom domains, and QR codes.
  • •Load test the cache-miss path, and run a failure drill: kill a cache node, then a zone.
🎤
Say it out loud
“To recap: stateless services, a key-value store sharded by code, codes from per-server counter ranges written in base62, and a layered cache so almost every redirect never reaches the database. I chose 302 so we can count, change and expire links. Analytics runs through a queue so it can never slow a redirect. The main trade-offs are the extra traffic from 302 and counts that are a few minutes late. If I had more time I would cover multi-region and abuse tooling.”

Q&ACross-questions (24)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Codes and collisions

The part interviewers push hardest. Know the numbers.

Scale and performance

Data, aliases and cleanup

Analytics, abuse and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat 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 lossWrite 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 codeHash 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 creationNever use 301. Update the row and purge caches. Keep a version history for audit.
10 times more traffic, global audienceEdge 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 previewsA separate service reads the same data. Previews fetch pages, so they need a safe sandbox, caching and abuse limits.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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.
EstimationNo 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.
DesignA 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 depthSays ‘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 failuresCannot 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.
CommunicationSilent 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.

AvoidCommon mistakes on this question

MistakeDo this instead
Jumping to the database before asking questionsSpend 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 stoppingState the collision problem, give the birthday numbers, and compare with a counter and random codes.
A single auto-increment counter with no discussion of failureShow 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 expiryExplain 301 vs 302 and pick 302 by default, with a reason.
Writing a counter on every redirectSend an event to a queue. Never put analytics on the redirect path.
No numbers, or numbers that never change the designSay 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 immediatelyDo not reuse, or quarantine for months. Explain the risk to old links.

Revise60-second revision sheet

  • ✔Scale: 100M links a month is about 40 writes a second, 4,000 reads a second (100:1), 6 billion links and 3 TB in 5 years.
  • ✔Code: 7 base62 characters = 62^7 = 3.5 trillion codes. 6 billion links use 0.17%.
  • ✔Generation: counter ranges per server, scrambled, then base62. No collisions, no per-request coordination.
  • ✔Hashing: a 7-character hash collides (about 5 million pairs at 6 billion links). It needs a check and a retry.
  • ✔Store: key-value, partitioned by hash of the code, conditional insert for uniqueness (409 on a duplicate alias).
  • ✔Read path: in-process cache, then Redis cache-aside (about 14 GB), then the database. 302, not 301.
  • ✔Hot link: short in-process cache on every server, coalesce misses, cache ‘not found’.
  • ✔Analytics: event to a queue, off the hot path. Counts a few minutes late. Drop events before redirects.
  • ✔Expiry: check on read, sweep in the background, do not reuse codes soon.
  • ✔Abuse: allow only http(s), safe-browsing check, rate limits, kill switch. A short link is not a secret.

Read these topics next

Caching Strategies→

Cache-aside and TTLs, used on the redirect path.

Hot Keys→

What to do when one link gets most of the traffic.

Cache Stampede→

Why a cache miss on a hot key can flatten the database.

Distributed Unique ID Generation (Snowflake, UUID)→

More ways to make unique IDs without a central counter.

Shard Keys, Hot Shards and Resharding→

Picking the code as shard key, and adding shards safely.

Consistent Hashing→

How adding a node moves only a small part of the data.

Rate Limiting→

Limiting creation per user, key and IP.

Key-Value Databases→

The store that fits access by one key.

← Previous
Talking About Trade-offs and Bottlenecks
Next →
Design Pastebin