AlgoViz

Design a URL shortener

medium 45 min

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

See it run

Every flow of the design, one hop at a time: creating a link, following it, making codes, caching and counting clicks.

Operations

Create a link (write path)

Designed for correctness over speed: validate, get a unique ID, encode it, store it only if absent, warm the cache.

Step 1 of 13

Client sends the URL

Our systemClientAPI gatewayURL serviceZooKeeperDynamoDBRedis

input

example.com/long/path

POST /api/v1/urls with the long URL and an optional alias and expiry. Why: it captures what the user wants before any work.

Step 1: Client sends the URL

def create(req):    limiter.check(req.client)            # 429 if over    validate(req.long_url)               # scheme, host, length    safety.check(req.long_url)           # blocklist, Safe Browsing    n = ids.next()                       # from the local range    code = req.alias or base62(scramble(n))    db.put_if_absent(code, req.long_url) # 409 if taken    cache.set(code, req.long_url, ttl=DAY)    return 201, f"https://sho.rt/{code}"
Latency
100-200 ms
Load
1,150/s
Peak (3x)
3,500/s
Share of traffic
about 1%

The conditional write is the only place uniqueness is enforced. Any earlier check is a hint for the user.

In the real world

The same url shortener doing real jobs. Pick one and step through it.

50,000 clicks a second on one code, at the moment its edge copy expires.

Step 1 of 4

All from the edge

Our system100%35%5%Requests100%CDN edgehits 65%Redishits 30%DynamoDBlast 5%

origin

1 request a minute

The hot link is cached at the CDN and origin sees almost nothing.

Step 1: All from the edge

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Cache-Control: private on a response you want the CDN to cache

    critical

    private forbids shared caches from storing it, so the CDN hit rate is zero and the origin takes everything.

    Wrong
    Cache-Control: private, max-age=60
    Right
    Cache-Control: public, max-age=0, s-maxage=60
  • Calling sequential IDs unguessable

    major

    Base62 is not encryption. The code after 5ban is 5bao, so anyone can walk your links.

    Wrong
    code = base62(next_id())
    Right
    # reversible mix: gcd(MULT, 62**7) == 1code = base62(next_id() * MULT % 62**7).rjust(7, "0")
  • Checking an alias, then inserting it

    critical

    Two requests can both see it free and both insert. Only a conditional write decides.

    Wrong
    if not db.get(alias):    db.put(alias, url)
    Right
    try:    db.put_if_absent(alias, url)except AlreadyExists:    return 409
  • Adding up hourly unique visitors

    major

    Someone who clicks in two hours is counted twice.

    Wrong
    SELECT sum(unique_visitors) FROM hourly
    Right
    SELECT uniqMerge(visitors_state) FROM hourly
  • Waiting for analytics in the redirect

    major

    A slow analytics store then makes every link slow.

    Wrong
    clickhouse.insert(event)return 302
    Right
    producer.send(event)          # async, batchedreturn 302

Interview tips

  • Lead with numbers

    • "100 to 1 reads, so caching is critical."
    • 115K reads a second, 350K at peak; 1,150 writes.
    • Seven base62 characters, 3.5 trillion codes.
  • Explain trade-offs

    • 302 keeps control and analytics, 301 saves load.
    • Ranges avoid collisions; hashing avoids a coordinator.
    • Key-value store for links, relational for accounts.
  • Anticipate failures

    • Redis down: circuit breaker, read the store.
    • ZooKeeper down: IDs in memory for hours.
    • Kafka down: buffer, spill to disk, replay.
  • End with extensions

    • Custom domains, QR codes, webhooks.
    • Password-protected links and A/B tests.
    • Deep links for mobile apps.