AlgoViz

Design a URL shortener

medium 45 min

Turn a long URL into a short code and redirect anyone who opens it.

Deep dives

Compare the options before you open them, then say which you would pick.

Deep dive 1

Generating unique IDs

How do many servers make codes that never clash?

BreaksFirst characters of a hash, stored without a check
How
Hash the long URL and keep seven characters.
Limit
With 3.5 trillion possible codes, the first clash is expected after roughly 2 million links. One user's link would then open another user's page.
Choose when
Never without a uniqueness check.
WorksRandom code, inserted only if absent
How
Draw seven random characters, write with a condition, retry on a clash.
Limit
Each create needs a conditional write, which we do anyway. After five years about 5% of draws clash (182.5B of 3.5T), so retries stay cheap.
Choose when
Codes must be hard to guess, or you want no coordinator.
WorksOne shared counter
How
Every create increments a counter in Redis or a database, then encodes it.
Limit
A network call per link, and creates stop when it does. If failover loses recent increments, numbers repeat, so the conditional write must stay.
Choose when
Modest volume and an existing highly available store.
StrongLeased ranges, scrambled
How
Lease a million numbers, count in memory, scramble, encode.
Limit
Some numbers are wasted on a crash. Scrambling hides order; it does not make codes secret.
Choose when
High create rates and short codes: our choice.
ApproachGoodBad
Range allocation (our choice)No collisions, no network per ID, survives outagesNeeds a coordinator; order leaks unless scrambled
Hash of the URL, cut to 7No coordinator, natural dedupCollisions: check and retry; same URL for two users
Random 7 charactersUnguessableCheck on insert
Snowflake IDNo range leases; time-ordered64 bits is 11 characters; needs machine IDs and clocks
UUIDNo coordination36 characters, far too long
Database auto-incrementTrivialA call per link, single point of failure, guessable

Leasing a range

Compare-and-set on the version makes the update atomic. A crash wastes the rest of a range, which is fine with 3.5 trillion codes.

Deep dive 2

Base62 and unguessable codes

Someone is walking through codes to find links. What do you do?

BreaksPlain sequential codes
How
Encode 1, 2, 3 as they come.
Limit
Anyone can add one and read the next link, or count how many you issue.
Choose when
Only for links that are all public and whose volume is not sensitive.
WorksScramble with a secret mix
How
A reversible multiply before encoding, plus rate limits on misses.
Limit
Enough known pairs reveal a simple multiplier. A keyed cipher over the number (format-preserving encryption) resists that.
Choose when
Public links where you only want to deter browsing.
StrongRandom codes and real access control
How
Cryptographically random codes, longer for private links, and a sign-in or password before the redirect.
Limit
More friction, and private links cannot be cached at a shared edge.
Choose when
Anything behind the link is private.

Base62 uses 0-9a-zA-Z. Divide by 62 repeatedly and read the remainders backwards: 1234567 gives 23, 10, 11, 5, so 5ban. Seven digits became four characters.

Encoding1234567Verdict
Decimal1234567 (7)Longer, and easy to enumerate
Hex12d687 (6)Longer for the same ID
Base584 charactersDrops 0, O, I, l: good when people type codes
Base625ban (4)Short and URL-safe
Base644 characters+, / and = are not URL-safe (the URL variant uses - and _)

Scramble before encoding

f(n)=(n⋅a) mod 627,gcd⁡(a,627)=1  ⟺  a is odd and 31∤af(n) = (n \cdot a) \bmod 62^7, \qquad \gcd(a, 62^7) = 1 \iff a \text{ is odd and } 31 \nmid a
A reversible mix keeps codes unique while neighbours look unrelated. It only deters casual walking: for private content use random codes or real access control, plus rate limits.

Deep dive 3

Multi-tier caching

One link gets 50,000 clicks a second. How is it served?

BreaksRead the database each time
How
Every click is a key lookup.
Limit
One key lives in one partition. In DynamoDB that is about 3,000 strongly consistent or 6,000 eventually consistent small reads a second.
Choose when
Cold links only.
WorksRedis in front
How
Cache-aside with a TTL.
Limit
One hot key sits on one node, and when it expires every server asks the database at once.
Choose when
Normal popularity; add request coalescing.
StrongEdge, then a small in-process cache, then Redis
How
The CDN answers most clicks; each server keeps the hottest links for a second or two; misses are coalesced into one read.
Limit
Seconds of staleness in several places; takedowns must purge all of them.
Choose when
Viral links are expected, as here.

Each tier filters the next

A browser asks the CDN edge, which answers 65% of requests; misses go to the redirect service and Redis, which answers 30%; the last 5% reach DynamoDB.

Average latency

0.65×12.5+0.30×40+0.05×75≈24 ms0.65\times 12.5 + 0.30\times 40 + 0.05\times 75 \approx 24\ \text{ms}
Midpoints of 5-20 ms (edge), 30-50 ms (Redis) and 50-100 ms (DynamoDB). Redis hits 86% of what reaches it: 0.35×0.86≈0.300.35 \times 0.86 \approx 0.30.
Python
def handle_redirect(code):    url = cache.get(code)                      # 1. try the cache    if url is None:        url = db.find_long_url(code)           # 2. miss: read the database        cache.set(code, url or MISSING, ttl=DAY if url else MINUTE)    if url is None or url is MISSING:        return 404    return 302, {"Location": url}
Cache-aside on the read path. Unknown codes are cached briefly too, so a bot scanning codes cannot hammer the database.

301 or 302? RFC 9110 lets clients cache a 301, so browsers may skip you on later clicks. A 302 keeps them coming back. Choose 301 to cut load when you need neither per-click data nor edits; otherwise 302.

Deep dive 4

The analytics pipeline

How do you count clicks?

BreaksAdd one to the link's row
How
UPDATE links SET clicks = clicks + 1 on each redirect.
Limit
Writes pile up on one hot row and the redirect waits for them.
Choose when
A hobby project.
WorksCount in memory, flush each second
How
Every server keeps totals and adds them to Redis or the database in batches.
Limit
A crash loses up to a second of counts, and you cannot break them down later.
Choose when
Only a total is needed and small loss is fine.
StrongEvents, a queue and rollups
How
Send an event without waiting; a stream job deduplicates and aggregates.
Limit
More to operate, results minutes late. If the local buffer is lost before Kafka accepts it, those clicks are gone.
Choose when
Breakdown by country, device and time is a requirement.

Ten billion clicks a day

The redirect service sends click events to Kafka without waiting, a stream job makes one-minute rollups into ClickHouse, and the link owner opens a dashboard that queries it. Each system has its own boundary inside one dashed outline.
  1. 1

    Fire and forget

    Look up, return 302, send the event. If Kafka is slow, the redirect is not. Event: id, code, time, hashed IP, country, city, referrer, device, browser.

  2. 2

    One-minute tumbling windows

    Drop repeated event IDs, group by code, country, referrer and device. 1,500 events become one row.

  3. 3

    Hourly rollups

    AggregatingMergeTree merges parts in the background. Re-inserting a batch would count twice, so deduplicate before this step.

  4. 4

    Retention

    Raw events 7 days, rollups by month. 1 TB a day raw becomes about 100 GB, and about 10 GB after columnar compression.

Edge cases

What can go wrong

CaseSeverityProblemAnswer
Alias collisionmedium"my-brand" is takenConditional write, 409 with suggestions; the UI's availability check is only a hint
Hash collisionlowTwo inputs, one codeImpossible with counted IDs; with hashing, check and retry
Expiry racelowExpires during a redirectCheck expires_at at read time, 410; optional 5-minute grace. TTL deletion is lazy, so never rely on it
Malicious URLhighPhishing linkCheck on create, re-scan later, disable, notify and report
Thundering herdhighHot link's edge copy expiresStale-while-revalidate and request coalescing
Redis downmediumLatency risesCircuit breaker after 3 failures, read the database, warm from logs
DynamoDB downcriticalCold links failMulti-region replicas, health-check failover, serve what Redis has
ZooKeeper downmediumNo new rangesRanges in memory last for hours
Kafka downlowClicks delayedBuffer, retry with backoff, spill to disk and replay
CDN downhighAll traffic hits originA second CDN with DNS failover, autoscaling

Failure priorities

  • Reads (99%): availability

    A slightly stale redirect beats a 503.

  • Writes (1%): correctness

    Reject a request rather than issue a duplicate code.

  • Analytics: eventually

    Buffer and retry; late is fine.

Failure drill: say it before you read it

  1. 1

    Redis is gone

    The store sees 35% of traffic instead of 5%: 40,250 reads a second instead of 5,750. Trip the breaker, lengthen edge TTLs, shed the coldest requests, then warm slowly.

  2. 2

    A range lease is given twice

    The conditional write refuses the second owner. The server drops that range and leases another. No link is overwritten.

  3. 3

    A takedown must work now

    Mark it inactive, delete the Redis key, purge the edge. In-process copies expire in a second or two. Browsers that stored a 301 cannot be reached: one more reason for 302.

  4. 4

    The home region is down

    Redirects continue from replicas. Generated codes continue elsewhere because ranges are separate. Custom aliases wait.