Asked at
URL Shortener (TinyURL)
Asked from Junior level upFoundations & Storage
Distributed Rate Limiter
Asked from Mid level upAPI Gateway & Security
Distributed Key-Value Store
Asked from Senior level upFoundations & Storage
Distributed Notification Service
Asked from Mid level upMessaging & Queues
Distributed Web Crawler
Asked from Mid level upDistributed Systems
Metrics & Monitoring Platform
Asked from Senior level upObservability & Time-Series
Real-Time Chat App (like WhatsApp or Slack)
Asked from Mid level upReal-Time & WebSockets
Social News Feed (like X/Twitter)
Asked from Mid level upSocial & Feed Systems
Ride-Hailing App (like Uber)
Asked from Senior level upGeospatial & Real-Time
Low-Latency Stock Exchange Matching Engine
Asked from Staff level upFintech & Low Latency
Global Video Streaming Platform (like YouTube or Netflix)
Asked from Senior level upMedia & Streaming
Distributed Hotel & Ticket Reservation System
Asked from Mid level upE-Commerce & Transactions
Shared Document Editor (like Google Docs)
Asked from Staff level upReal-Time & Distributed State
Game Leaderboard
Asked from Junior level upCaching & Data Structures
File Sync Service (Dropbox / Google Drive)
Asked from Mid level upStorage
Payment System
Asked from Senior level upPayments & Transactions
Ad Click Aggregation
Asked from Senior level upStream Processing
AI Support Assistant (RAG)
Asked from Senior level upAI Systems
LLM Inference Platform
Asked from Senior level upAI Systems
Enterprise Semantic Search
Asked from Mid level upAI Systems
AI Code Completion
Asked from Senior level upAI Systems
LLM Gateway
Asked from Senior level upAI Systems
AI Agent That Takes Actions
Asked from Senior level upAI Systems
LLM Evaluation Platform
Asked from Senior level upAI Systems
AI Document Processing Pipeline
Asked from Mid level upAI Systems

Design a URL Shortener (TinyURL)

Asked from Junior level upDomain: Foundations & Storage
Concepts to know first:

Design a service that turns long links into short 7-character codes, sends people on to the long link, and counts the clicks.

An analogy

Think of TinyURL like a coat-check ticket at a theatre. You hand over a bulky winter coat, the long URL, and receive a tiny plastic token, the short code. Whenever you return the token, the attendant uses it to find your exact coat.

Where this design ends up. This is version 3 of 3. Part 5 builds it up from version 1 and says why each part was added.
  1. Client
    • Browser / App
  2. Edge / Ingress
    • Cloudflare Edge
    • Nginx L7 LB
  3. Application Tier
    • URL Service Pod A
    • URL Service Pod B
    • KGS (Key Gen)
  4. Cache Tier
    • Redis Cache
  5. Database Tier
    • Cassandra Ring

1. Requirements and scope

Functional Requirements
  • Given a long URL, generate a shorter, unique alias (e.g. tinyurl.com/a8B7d9).
  • When a user opens the short link, redirect them to the original URL (HTTP 302, so each click can be counted).
  • Support custom alias links and optional expiration dates (TTL).
  • Count clicks, and record where each click came from: the page that linked to it and the rough location of the user.
Non-Functional Requirements & SLAs
  • High availability (99.99% uptime, about 53 minutes of downtime a year): redirects matter most.
  • Fast redirects: an example target is under 15 ms when the edge already has the link.
  • Short codes should be hard to guess, so no one can walk through them in order and copy every link.
  • Read-to-write ratio: 100:1 (heavily read-heavy system).
Key Traffic Assumptions: 100 Million new URLs generated per month (~40 writes/sec). • 10 Billion redirections per month (~4,000 reads/sec average). • URL mapping stored for 5 years retention.

2. Back-of-the-envelope numbers

Writes and reads each second
  • Writes: 40 new links a second, on average (1%)
  • Reads: 4,000 redirects a second, on average (99%)

Read-heavy: about 100 reads for each write. A cache and extra read copies help most here.

Write Throughput
40 QPS (Avg), 100 QPS (Peak)
Read Throughput
4,000 QPS (Avg), 10,000 QPS (Peak)
Storage Growth
100M URLs × 500 Bytes × 12 = ~600 GB / year (3 TB over 5 years)
RAM Cache Footprint
20% of daily read volume = 20% × 330M × 500B = ~33 GB RAM

3. API

POST/api/v1/urlsCreate short URL. Request: { longUrl, customAlias?, expireAt? } → Response: { shortUrl }
GET/{shortCode}Redirect endpoint. Returns HTTP 302 with a Location header, so every click can be counted. Use 301 only if click counts do not matter.
GET/api/v1/urls/{shortCode}/analyticsRetrieve click statistics, referrers, and geo breakdown.

4. Data model and storage

Storage Strategy: NoSQL Key-Value Store (DynamoDB / Cassandra) or Relational (PostgreSQL) with Primary Key index.
URL_MAPPING Table:
- short_code VARCHAR(7) PRIMARY KEY  -- Base62 code
- original_url VARCHAR(2048) NOT NULL
- user_id BIGINT
- created_at TIMESTAMP
- expires_at TIMESTAMP
- click_count BIGINT DEFAULT 0

5. The design, in three versions

Version 1: Simple MVP Architecture

Single application server connected to a relational database. Good for <10,000 users.

TinyURL v1: Monolithic Server Version 1 of 3

The picture follows one request through the parts of this version, in order. Under it, switch a part off to see what the request does without it.

One request, step by step

Each numbered arrow is one step. Press "Simulate Request Flow" to follow them one at a time.

Browser / AppSingle Port 80Monolith AppPostgreSQL Primary1234
  • The order of the steps
  • A request or its reply

The parts: switch one off

1. Client

Browser / AppHTTP Client
Example figures
Technology
Chrome/iOS
Speaks
HTTPS/TLS
Time budget
0ms
Capacity
100K DAU

2. Edge / Ingress

Single Port 80Reverse Proxy
Example figures
Technology
Nginx / Maglev
Speaks
TCP/HTTP
Time budget
< 2ms
Capacity
50,000 QPS

3. Application Tier

Monolith AppShortener & Redirect
Example figures
Technology
Go / Java
Speaks
gRPC/HTTP
Time budget
< 8ms
Capacity
5,000 QPS

4. Cache Tier

Not in this version

5. Database Tier

PostgreSQL PrimaryURL Persistence
Example figures
Technology
PostgreSQL 16
Speaks
SQL / CQL
Time budget
< 12ms
Capacity
2,000 W/s

The steps in words0 of 4 steps shown

  1. Browser to NginxHTTPS · 12ms

    GET /abc1234

  2. LB to URL ServiceHTTP · 1.5ms

    Round-robin dispatch

  3. URL Service to DatabaseSQL · 8ms

    SELECT original_url WHERE short_code

  4. URL Service to BrowserHTTP/302 · 3ms

    Location: https://example.com/target

Why this version
Validates product with minimal operational complexity.
Next bottleneck
Single point of failure. Repeated database queries for popular links cause disk read bottleneck.

Write path, read path and failures

Each path follows one request through the final design (version 3), one hop at a time.

Write pathCreate a short link

  1. Client
  2. App servers
  3. Key generation service
  4. Sharded database
  1. Client to App servers

    The client sends POST /api/v1/urls with the long URL.

  2. App servers to Key generation service

    The app server takes the next unused code from its block of 1,000 codes. It asks for a new block only when the block runs out.

  3. App servers to Sharded database

    It saves the code and the long URL. The write is refused if the code already exists.

  4. App servers to Client

    It returns the short URL. Nothing is cached yet: the first read fills the cache.

Read pathOpen a short link

  1. Client
  2. CDN edge
  3. App servers
  4. Redis cluster
  5. Sharded database
  6. Kafka clickstream
  1. Client to CDN edge

    The browser asks for /a8B7d9. A nearby edge server answers if it has seen this code in the last minute, and logs the click.

  2. CDN edge to App servers

    On an edge miss, the request goes on to an app server.

  3. App servers to Redis cluster

    The app server looks the code up in Redis. Most lookups end here.

  4. App servers to Sharded database

    On a Redis miss, it reads the database and saves the answer in Redis with a TTL.

  5. App servers to Client

    It answers 302 with the long URL. Browsers do not keep a 302, so every click is seen and can be counted.

  6. App servers to Kafka clickstream

    Clicks from the app servers and from the edge logs go to Kafka. Counting happens later and never slows the redirect.

What breaks, and what happens then

  • Redis is down

    What users see
    Each click reads the database. As clicks grow, the database gets busy and each click waits longer.
    What the design does
    Read replicas are sized for the peak of 10,000 redirects a second. Each app server also keeps the hottest links in its own memory.
  • The key generation service is down

    What users see
    Redirects are not affected. New links work until each server's block of codes runs out.
    What the design does
    Run two copies of the service. Each hands out different ranges of numbers, so codes never collide.
  • Kafka is down

    What users see
    Redirects still work, but clicks are not counted for a while.
    What the design does
    App servers hold recent clicks in a small buffer and send them when Kafka returns. A few clicks may be lost; redirects never wait.
  • A database shard is down

    What users see
    Links on that shard cannot be created. Cached links still open.
    What the design does
    A replica of the shard takes over. Until then, the cache answers what it can.

6. Deep dives

Base62 Encoding vs MD5 Hash
MD5 gives a 128-bit hash (32 hex characters), too long for a short link, and cutting it short causes collisions. Better: take a number from a counter and scramble it with a secret, reversible mix, so codes cannot be guessed in order. Then write it in Base62 [a-z, A-Z, 0-9]. Seven characters give 62^7, about 3.5 trillion codes.
HTTP 301 vs HTTP 302 Redirection
A 301 answer (Moved Permanently) lets the browser keep the redirect. Its next clicks can skip your server, which saves work but loses those clicks from the counts. A 302 answer (Found) is not kept, so every click comes back to your server and can be counted.
Key Generation Service (KGS)
Makes unique 7-character Base62 codes ahead of time and keeps them in a key database. Each app server takes a block of 1,000 unused codes at a time, so a new link needs no collision check. A server that crashes loses only the unused codes in its block.

7. Follow-up questions

  • How do you purge expired short URLs? (Answer: Delete a link when someone opens it after it expired, and run a nightly batch job to sweep the rest).
  • What if a user requests a short URL that does not exist? (Answer: Return 404. Cache that miss for a short time, or use a Bloom filter, so repeated lookups skip the database).
  • How do you handle celebrity hot links? (Answer: Cache key in local process memory of application pods via Guava/Caffeine to protect Redis).

What it costs

Reads are about 100 times the writes, so the cache and the CDN carry most of the load. The data is small: about 600 GB a year. The first saving is to answer popular links at the edge, so they never reach your servers.

Another way to design it

You can skip the key service and hash the long link, then take the first 7 characters. That needs no shared counter. It does need a check for two links that give the same code. It suits a small service.

8. How answers are judged

A passing answer at Mid level. A complete design with numbers: about 40 new links and 4,000 redirects a second. It explains how codes stay unique and goes deep on one part, such as the cache or code generation.

How each level is judged
What is judgedJuniorMidSeniorStaff
BreadthHow much of the system does the answer cover?Names the core parts: clients, servers, a database and a cache.Covers the whole main flow, from the request to the stored data and back.Builds a complete design without being led through it.Covers the system, the systems around it and who owns each part.
DepthHow far does it go into the hard parts?Explains what each part does and why it is there.Goes deep on one part, such as the database or the cache.Goes deep on the two or three riskiest parts.Goes deepest where the risk is largest, and explains why the risk is there.
DrivingWho leads the conversation?Follows the interviewer, step by step.Moves forward alone, with an occasional nudge.Leads the conversation from start to finish.Changes the problem when the question asked is not the right one.
Trade-offsAre choices compared and justified?Names more than one option.Says why one option was picked over another.Compares options in detail, with what each one costs.Ties each choice to cost, speed and risk for the business.
Unclear questionsWhat happens when the question is vague?Answers the questions that are asked.Asks questions to make the problem clear.Sets the scope and says what is left out.Questions the assumptions behind the problem itself.
ScopeWhat does it consider beyond the normal path?Covers the normal path, when everything works.Adds what happens when a part fails.Adds growth: what breaks at ten times the load, and the fix.Adds abuse, cost and the daily work of running the system.

Requirements and scope

Strong answer
Before I design, I want to check the scope. Users create a short link and anyone can open it. Do links expire? Can users choose their own code? Do we count clicks? I will assume redirects must be fast and must never break, and that reads outnumber writes about 100 to 1.
Weak answer
Users paste a long link and get a short one back. When someone clicks the short link, they go to the long one. Let me start drawing the servers.

Shows: Unclear questionsThe difference: The weak answer starts drawing before asking about expiry, custom codes or click counts, so it may design the wrong system.

Estimates

Strong answer
About 100 million new links a month is roughly 40 a second. At 100 reads per write, that is about 4,000 redirects a second, and maybe 10,000 at peak. Each link takes about 500 bytes, so a year of links is about 600 GB. One database can store that.
Weak answer
This will get huge traffic from millions of users, so from day one we need many data centres, sharding and a large cache cluster.

Shows: ScopeThe difference: The weak answer designs for a scale it never measured. The strong one turns rough numbers into rates and storage, and lets them pick the design.

Core design

Strong answer
Each new link gets the next number from a counter. A secret one-to-one mix scrambles it, and it is written as 7 letters and digits (Base62). Each number is used once, so codes never collide, and nobody can guess the next code. One table maps codes to long links; redirects check the cache, then the database.
Weak answer
I hash the long link with MD5 and keep the first 7 characters as the code. I save the code and the long link in a table, and a cache in front serves the redirects.

Shows: DepthThe difference: Two different links can get the same 7 characters from the hash, and the weak answer never checks for that. A code from a counter cannot collide.

Deep dive

Strong answer
The hard part is handing out unique codes from many servers. One database counter copes with 40 writes a second, but if it is down, nobody can create links. So each server reserves 1,000 numbers at a time and hands them out from memory. Numbers lost in a crash leave gaps, which do no harm.
Weak answer
Redirects are the main load, so I would add more cache. With a big enough Redis cluster, nearly every redirect is a cache hit and the database is safe.

Shows: DepthThe difference: The weak answer spends its deep dive on the easy part. The strong one picks the riskiest part, unique codes across servers, and shows the failure it avoids.

Failures and trade-offs

Strong answer
If the cache fails, all 4,000 redirects a second fall on the database. Read replicas sized for the peak of 10,000 a second keep redirects working while the cache refills. I would also pick a 302 over a 301. Every click then reaches us and can be counted, at the cost of a little speed.
Weak answer
If a server fails, the load balancer sends traffic to the others. Everything is replicated, so nothing can go wrong.

Shows: Trade-offsThe difference: The weak answer names one failure and waves the rest away. The strong one follows a real failure to its effect, and names what a choice gives up.

We wrote this guide in our own words, informed by public interview guides such as AlgoMaster and Hello Interview. We are not connected to either site. Interviewers differ. The guide and the example answers show the direction each level takes, not a checklist.

9. One problem, four levels

The same question, "design a URL shortener", answered at four levels. Each column shows only what that level adds to the one before it.

What each level adds, part by part
Part of the answerJuniorMid addsSenior addsStaff adds
Requirements and scope
  • Create a short link from a long one, and send anyone who opens the short link to the long one.
  • Splits must-haves (create, redirect) from qualities: redirects are fast, links never break, and reads outnumber writes about 100 to 1.
  • Asks about custom codes, expiry and click counts before designing, and says which ones this answer leaves out.
  • Asks who uses the links and why. Marketing links need click analytics and custom domains, which change the design more than raw load does.
Estimates
  • Says the system is read-heavy: far more people open links than create them.
  • About 40 new links and 4,000 redirects a second on average, about 10,000 at peak, and about 600 GB of new links a year.
  • Uses the numbers to decide: 40 writes a second fit one database, so the load to plan for is the redirects.
  • Adds cost: 600 GB a year is cheap to store, so the money goes on fast redirects worldwide and on storing click data.
Core design
  • An API server and one table that maps each code to its long link, with a cache in front for popular links.
  • Codes come from a counter, written as 7 letters and digits (Base62). A secret one-to-one mix scrambles each number first, so codes never repeat and cannot be guessed.
  • Stateless app servers behind a load balancer. Each server reserves a block of numbers, so making a code needs no shared step.
  • Keeps click counting off the redirect path: clicks go onto a queue and are counted later, so slow analytics never slows a redirect.
Deep dive
  • Explains why the cache helps: popular links are read again and again, so most redirects never reach the database.
  • Explains 301 against 302: browsers remember a 301, which is faster but hides later clicks from the click count.
  • Goes deep on unique codes from many servers: blocks of numbers, a server dying while holding a block, and why gaps do no harm.
  • Goes deep on abuse: short links can hide spam and phishing, so it checks links, limits per user, and can disable a code.
Failures and trade-offs
  • Says the database needs a backup.
  • If the cache goes down, redirects still work from the database, only slower.
  • Sizes read replicas for 10,000 redirects a second while the cache refills, and keeps redirects working even if link creation is down.
  • Weighs a second region: faster redirects abroad and survival of a region outage, against the cost and the work of keeping regions in step.
Whole answer at:

Requirements and scope

  • Create a short link from a long one, and send anyone who opens the short link to the long one.
  • New at MidSplits must-haves (create, redirect) from qualities: redirects are fast, links never break, and reads outnumber writes about 100 to 1.

Estimates

  • Says the system is read-heavy: far more people open links than create them.
  • New at MidAbout 40 new links and 4,000 redirects a second on average, about 10,000 at peak, and about 600 GB of new links a year.

Core design

  • An API server and one table that maps each code to its long link, with a cache in front for popular links.
  • New at MidCodes come from a counter, written as 7 letters and digits (Base62). A secret one-to-one mix scrambles each number first, so codes never repeat and cannot be guessed.

Deep dive

  • Explains why the cache helps: popular links are read again and again, so most redirects never reach the database.
  • New at MidExplains 301 against 302: browsers remember a 301, which is faster but hides later clicks from the click count.

Failures and trade-offs

  • Says the database needs a backup.
  • New at MidIf the cache goes down, redirects still work from the database, only slower.

10. Check your design with your own AI

Write your design first. Then copy this prompt into the AI chat you already use, and add your design at the end. It asks for a score in each area, one fix for each, and two follow-up questions.

The site sends nothing anywhere. An AI review can be wrong, so check what it says against sections 8 and 9.

See the prompt
You are a system design interviewer. Review my design for the interview problem below.

Problem: Design a URL Shortener (TinyURL)
Design a service that turns long links into short 7-character codes, sends people on to the long link, and counts the clicks.

What users must be able to do:
- Given a long URL, generate a shorter, unique alias (e.g. tinyurl.com/a8B7d9).
- When a user opens the short link, redirect them to the original URL (HTTP 302, so each click can be counted).
- Support custom alias links and optional expiration dates (TTL).
- Count clicks, and record where each click came from: the page that linked to it and the rough location of the user.

How well it must work:
- High availability (99.99% uptime, about 53 minutes of downtime a year): redirects matter most.
- Fast redirects: an example target is under 15 ms when the edge already has the link.
- Short codes should be hard to guess, so no one can walk through them in order and copy every link.
- Read-to-write ratio: 100:1 (heavily read-heavy system).

Numbers to assume:
- 100 Million new URLs generated per month (~40 writes/sec).
- 10 Billion redirections per month (~4,000 reads/sec average).
- URL mapping stored for 5 years retention.

Judge my design at the Mid level.
A passing answer at this level: A complete design with numbers: about 40 new links and 4,000 redirects a second. It explains how codes stay unique and goes deep on one part, such as the cache or code generation.

For each area below, say whether my design is strong, fine or weak. Give one reason and one fix for each:
1. Requirements and scope
2. Estimates
3. Core design
4. Deep dive
5. Failures and trade-offs

Then ask me the two follow-up questions an interviewer would ask next.
Do not write a full model answer for me.

My design:
[Describe your parts, how one request moves through them, and why you chose each one.]