System Design Atlas
LOCAL GUEST MODERead and practice without an account.

Your saved topics and reading progress stay in this browser. Sign in to sync supported profile and progress data.

URL Shortener (Bitly)

Design a service that turns a long URL into a short link and redirects anyone who opens it.

Save, progress and topic tools
○ Easy
My progress

Problem statement

Save a destination once and resolve its short code on every visit. Redirects must stay fast even when click reporting falls behind.

Functional requirements

  • Shorten a URL with an optional alias and expiry.
  • Redirect active links to their destination.
  • Let owners disable links and see approximate daily clicks.
Where to stop

Leave account management and custom domains for a follow-up. Neither changes how a code is claimed or a redirect is served.

Non-functional requirements

  • Keep codes unique and generated codes hard to guess.
  • Target redirects under 50 ms in-service and 100 ms from a same-region client.
  • Target 99.99% redirect availability. Allow bounded staleness on reads and enforce unique alias claims on writes.
  • Support 1B stored links and 100M daily active users. Redirects dominate traffic.

Scale assumptions

  • 10M new links per day. Size writes for peak traffic and storage for retained links.
  • 1B redirects per day. At roughly 100 opens per create, cache popular links.

Entities

RecordKey fields
LinkCode, destination, owner, expiry, status, version
Create requestOwner + request ID → code and payload fingerprint
ClickEvent ID, code, timestamp
Daily click totalOne count per code and day, updated by click workers.

API design

EndpointResult
POST/links201 · short URL / 409 · alias taken
GET/{code}302 · Location header / 404 · missing or inactive
DELETE/links/{code}204 · disabled / 412 · version changed
GET/links/{code}/stats200 · daily counts for the owner

High-level design

How to draw the four boundaries

How to draw this design

  1. CreateCreate service · code allocation
  2. StorePostgreSQL · link ownership
  3. RedirectRedirect service · Redis
  4. ReportKafka · click workers

Link creation commits to PostgreSQL. Redirects use Redis. Click reporting runs asynchronously.

State ownership
PostgreSQL owns the short-code mapping.
Scale
Cache popular links close to readers. Partition mappings when measured load or retained size warrants it.
Correctness
A unique constraint prevents two destinations from owning one code.
Failure and recovery
hot-key misses and cap fallback reads when Redis fails.

URL Shortener · create, redirect and report

Start with creation across the top. Follow the visitor through the middle. Reporting runs below the request path and writes daily totals separately from link mappings.

URL Shortener · create, redirect and report
What changes if one link goes viral?

A single code accounts for half the clicks. Adding database partitions still sends those reads to the same partition. Cache the popular mapping near readers and combine simultaneous misses into one lookup.

Before caching closer to readers, agree on how quickly a disabled link must stop working. That deadline limits the cache lifetime.

G client->write 1. POST /links write->map 2. Insert unique code write->client 3. 201 · link ready reader->read 4. GET /{code} read->cache 5. Look up by code read->map 6. Miss · read row read->cache 7. Cache until expiry read->reader 8. 302 · Location read->evt 9. Emit click event evt->ana 10. Read retained clicks ana->map 11. Commit count + ID client Link owner URL + request ID write Link creation API Random Base62 read Redirect API Check expiry map PostgreSQL One row per code cache Redis mapping cache Mapping + expiry evt → Kafka click log Replayable clicks ana Click aggregation workers Daily totals reader Visitor’s browser Follow Location
  • Edge
  • Compute
  • State
  • Messaging

━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault

Select a component or follow a numbered connection.

Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.

Read the journeys step by step
Create a link
Open a link
Count a click

High-level design component walkthrough

Client / user

Link owner

Sends the destination and optional alias or expiry. If the response is lost, resends the same request ID and payload to recover the original link.

Why, tradeoff and connected operations

Retain the request ID when retrying creation.

Tradeoff: A timeout can hide a successful create.

Connected operations: POST /links; 201 · link ready

Backend service

Link creation API

Checks the owner and destination, then proposes a random code or uses the requested alias. PostgreSQL decides which writer owns that code.

Why, tradeoff and connected operations

Commit the mapping and retry result together. Rate-limit creates and reject unsupported schemes.

Tradeoff: An automatic collision needs a fresh code.

Connected operations: POST /links; Insert unique code; 201 · link ready

Backend service

Redirect API

Handles GET /{code}. Checks status and expiry before returning the destination, whether the mapping came from Redis or PostgreSQL.

Why, tradeoff and connected operations

A separate read path can scale with click traffic.

Tradeoff: Cache misses consume database capacity.

Connected operations: GET /{code}; Look up by code; Miss · read row; Cache until expiry; 302 · Location; Emit click event

Relational database

PostgreSQL

Stores the destination, owner, status, version and expiry. A unique index settles competing claims. Separate tables hold create-request results and daily click totals.

Why, tradeoff and connected operations

One transaction enforces uniqueness and records the result for retries.

Tradeoff: Growing indexes and retained links consume disk.

Connected operations: Insert unique code; Miss · read row; Commit count + ID

Cache / in-memory index

Redis mapping cache

Holds a versioned copy of a link for fast reads. A cache miss says nothing about whether the link exists. The redirect service asks PostgreSQL.

Why, tradeoff and connected operations

Memory lookups absorb most repeated reads.

Tradeoff: Missed invalidations can leave a stale entry.

Connected operations: Look up by code; Cache until expiry

Queue / event stream

Kafka click log

Retains accepted click events so workers can catch up after a pause. Each event carries a stable ID for recognizing retries.

Why, tradeoff and connected operations

Consumers can replay retained events after an outage.

Tradeoff: A full publisher buffer can drop clicks.

Connected operations: Emit click event; Read retained clicks

Stream / batch processing

Click aggregation workers

Groups clicks by code and day. Records the event ID and increments the count together before acknowledging progress.

Why, tradeoff and connected operations

Reporting can catch up independently of redirects.

Tradeoff: Recent totals may lag.

Connected operations: Read retained clicks; Commit count + ID

Client / user

Visitor’s browser

Requests the short code, receives a destination in the Location header, then makes a separate request to that site. A redirect alone cannot confirm that the page loaded.

Why, tradeoff and connected operations

The browser makes the next request directly to the destination.

Tradeoff: A redirect only proves that the shortener issued a response.

Connected operations: GET /{code}; 302 · Location

Simulation and engineering control room

Deep dives — decisions, failures and recovery

How should we generate short codes?

ApproachHow it worksWhat you give up
Random Base62 (our choice)Pick letters and digits. Insert the code into a unique index.Retry if the generated code is taken. Longer codes reduce collisions.
Counter in blocksGive each server a separate range of numbers to encode.Generated IDs stay unique, but sequential codes are easy to guess.
Hash the destinationUse part of a URL fingerprint as the code.Different URLs can collide. Reusing a code also couples owners who need separate expiry or stats.
Deep dive 1

Who gets the short code?

Any server can suggest a code. PostgreSQL gives it to the first owner whose insert succeeds.

Staff lens — Retry a generated collision. If someone already owns a requested alias, return 409.

What if two people request the same alias?

Create the candidate code, then try to insert it directly. Checking availability first leaves a gap in which another writer can take it. Commit the mapping and the owner’s request ID together.

Two owners want /launch

Two owners ask for /launch at the same time. PostgreSQL commits one mapping. The other insert hits the unique constraint and the service returns 409.

When the create response gets lost

After a lost response, repeating the same request ID and payload returns the original code. Reject a changed payload.

How PostgreSQL enforces uniqueness ↗

Deep dive 2

What if one link goes viral?

Keep its destination in Redis. When the entry expires, let waiting requests on each server share one database lookup.

Staff lens — Adding a database spreads different links around. One viral link still hits one .

What happens when the popular link drops out of cache?

On each redirect server, the first miss for a code starts a read. Other callers share its result.

Ten thousand opens per second

Suppose one link gets 10,000 opens per second. At a 99% hit rate about 100 reads per second reach storage. If its entry disappears, all 10,000 can miss together. Let one request per server fetch the row while its neighbors wait for that result.

If Redis goes offline

If Redis goes offline, bypass it. Limit concurrent fallback reads across the fleet and return 503 when the budget runs out. A timeout tells you nothing about whether the code exists. Caching that timeout as 404 would break a valid link after recovery.

How overload spreads between dependencies ↗

Deep dive 3

What counts as a click?

Count redirects the shortener sends. The browser can leave before the destination loads, and the dashboard can catch up later.

Staff lens — A worker can replay events Kafka received. It cannot recover clicks lost before they reached Kafka.

Which clicks can we recover?

A bounded publisher buffer feeds Kafka. Workers aggregate clicks by code.

Try a reporting outage

In the simulator, take Kafka offline and open the link ten times. All ten visits redirect. Three events fit in the local buffer, seven are lost. Pausing only the workers gives a different result: Kafka keeps the events and the dashboard catches up later.

If a worker counts the same event twice

Give each event a stable ID. When a worker retries after saving a count but losing its acknowledgment, record the ID and increment the total in one transaction so replay cannot count it twice. cannot recover an event that never reached Kafka.

Deep dive 4

How quickly does disable take effect?

Send a temporary redirect with Cache-Control: no-store so browsers check back. The Redis copy has its own expiry.

Staff lens — An old database read can put a disabled link back in Redis after you clear the cache.

How can a disabled link reappear?

Send 302 with Cache-Control: no-store. Owners disable a link using its current version in If-Match.

A slow read races with disable

A reader fetches version 7 just before the owner disables the link at version 8. Deleting the Redis key leaves an empty slot for that slow reader to refill. Instead, keep a version-8 disabled marker and accept a refill only if its version is current.

If the cache update is lost

If invalidation is lost, expire the cached entry within the agreed delay. Bound in-flight lookups and retain the disable marker through that interval so an old response cannot restart the stale window.

How HTTP temporary redirects work ↗

Deep dive 5

Why does a new link work in only one region?

Someone creates a link and immediately shares it overseas. The nearest replica may still be waiting for the new mapping.

Staff lens — A regional miss can mean replication is late. Only the owning region can confirm the link is missing in this design.

What if the owning region is offline?

A local replica makes distant redirects fast. Because changes arrive asynchronously, an empty lookup might mean the create is still in transit. Ask the owner within a short deadline. Return 404 only when the authoritative lookup confirms absence.

The first click after creation

A customer creates /launch just before the primary region goes offline. The recovery replica has not received that row yet. Returning 404 would tell the customer their valid link never existed.

When to resume writes

Return 503 for an uncertain lookup. Keep alias creation paused until ownership is fenced and the new writer has the committed mappings needed to enforce uniqueness.

90-second interview summary

I would split link creation from redirects. The create service validates the destination, generates a short code and saves it in PostgreSQL. A unique constraint settles collisions. Saving the request ID in the same transaction lets the client retry safely if the response is lost.

Most traffic is redirects, so I would check Redis first. If a popular code disappears from cache, each server shares its lookup among waiting requests. I would limit total fallback reads to protect PostgreSQL. The redirect includes the destination in the Location header.

Click reporting runs through Kafka. A reporting delay is acceptable for basic counts, as is losing some clicks during a prolonged outage. For disabled links, version checks and expiry bound how long cached data can be used. If a region fails, I would keep a single writer and return a temporary error wherever the surviving replica cannot give a trustworthy answer.

Test your design decisions

Redraw the system from memory

Draw the create and redirect paths. Mark where a code becomes unique and where a click can be lost.

A create request times out. Can the client retry?

Reveal answer

Yes. Reuse the same request ID and payload to recover the committed result.

How do a missing link and an unavailable database differ?

Reveal answer

Return 404 for an authoritative miss and 503 when the lookup cannot be completed.

Can a reporting outage break a valid link?

Reveal answer

The redirect remains available. A full event buffer can leave click counts incomplete.

Rehearsal checklist

  • Trace a cache hit and a miss.
  • Defend the alias claim and retry rule.
  • State the limit on stale redirects.
60-minute interview outline

60-minute interview walkthrough

TimeFocusWhat to cover
0–5 minIntroductionsIntroduce yourself briefly and confirm the interview format.
5–15 minScope and scaleScope link creation and redirection. Estimate redirect traffic, the read-to-write ratio, and the number of codes needed.
15–30 minHigh-level designDraw the create service, redirect service, PostgreSQL and Redis. Add the Kafka branch for click counts.
30–45 minDeep divesExplain collision handling and how a popular link can be served without a database lookup on every redirect.
45–55 minFailure and recoveryWalk through a hot link losing its cached copy. misses, bound database reads, and explain when to shed load.
55–60 minWrap-upSummarize the design and its main tradeoff. Leave time for questions.

On this page
  1. Problem
  2. Requirements
  3. Numbers, entities and APIs
  4. Trace the architecture
  5. Simulation and engineering control room
  6. Decisions and failures
  7. Interview summary
  8. Test your decisions
  9. Recall questions
  10. Checklist
  11. 60-minute rehearsal

Save & sync your Atlas progress

Sync your profile and topic progress across browsers, then return to the same study desk.

Google sign-in will appear here after its Azure provider is configured.

Architecture diagram