Case study V.1Basic

Design a URL Shortener Like TinyURL

The classic warm up. A small surface area that still tests estimation, ID generation, caching and the difference between a 301 and a 302.

The short answer

Requirements. Create a short link for a long URL, with an optional alias and expiry; send every visit on to the long URL in a few milliseconds; stay up, because a dead link breaks someone else’s page; never reuse a code.

Writes
40 per second100M new links a month
Redirects
4,000 per secondpeak about 8,000
Storage
about 6 TB12B links over 10 years
Code length
7 charactersbase62, 62⁷ ≈ 3.5T codes

The design. Stateless web servers behind a load balancer take a unique ID from a range they lease in blocks of 1,000, write it in base62 as a 7 character code, and store code and long URL in one table keyed by the code. A redirect reads the code from a Redis cache first, falls back to the store only on a miss, and answers 302 so every click passes through and can be counted. Click events go to a queue so redirects never wait for analytics, and the store is replicated for availability, not sharded, until the numbers demand it.

Interview prompt

Design a service like TinyURL: given a long URL, return a short one that redirects to it.

Requirements and estimates

Functional requirements

  • Create a short URL for a long one, with optional custom alias and expiry.
  • Visiting the short URL redirects to the long one.
  • Optional: click counts per link.

Non-functional requirements

  • Redirects are fast, a few milliseconds at the server.
  • Highly available: a dead short link is a broken page on someone else’s site.
  • Codes are never reused and are hard to enumerate.

Estimates

New URLs    100M per month ÷ 2.6M s        ≈ 40 writes/s
Redirects   100 reads per write             ≈ 4,000 reads/s, peak ≈ 8,000
Total URLs  100M × 12 months × 10 years     = 12B
Storage     12B × 500 B                     ≈ 6 TB
Code space  62⁶ ≈ 56.8B, 62⁷ ≈ 3.5T         → 7 characters gives plenty of headroom

Calculator: run the numbers yourself

Writes per second
Redirects per second
Peak redirects per second
Storage
Shortest code
Cache, 80/20 method

What the numbers decide

    Numbers behind the estimates

    NumberValueUsed for
    Seconds in a day, a month86,400 ≈ 105; ≈ 2.6MTurning daily or monthly volume into per second rates
    Memory read≈ 100 nsWhy hot redirects are served from a cache
    Random SSD read, HDD seek≈ 16 µs, ≈ 2 msMemory is about 160× faster than an SSD, and an SSD over 100× faster than a spinning disk
    SSD random reads≈ 100,000 IOPSPeak reads beyond this cannot come from one disk
    HDD random reads100 to 200 IOPSWhy nobody serves hot reads from spinning disks
    One Redis instance100,000+ ops/sCache nodes needed at peak; the global ID counter
    Network latency: same AZ, across AZs, across regions< 1 ms; 1 to 2 ms; 50 to 150 msThe 100 ms redirect budget; why a CDN helps distant users
    Network bandwidth per instance25 Gbps standard, 50 to 100 high endBandwidth is never the limit for 500 byte rows
    One large machine512 GiB RAM, 128 vCPUs; up to 24 TB RAM; up to 60 TB local SSDWhether data and cache fit on one box

    The point of these numbers is that modern machines are huge. Rules like “split the database at 100 GB” are long outdated, and sharding before the numbers demand it is a common interview mistake. The 6 TB this design reaches after ten years still fits on the disks of one large database server, and for the first years it is a few hundred GB; replicate it for availability, and shard only when throughput or size truly requires it.

    API and data model

    API

    POST /api/v1/urls
    { "longUrl": "https://example.com/a/long/path",
      "alias": null, "expiresAt": null }
    → 201 { "shortUrl": "https://sho.rt/zn9edcu" }
    
    GET /zn9edcu
    → 302 Found
      Location: https://example.com/a/long/path

    Data model

    urls
      code        CHAR(7)    PRIMARY KEY
      long_url    TEXT
      owner_id    BIGINT
      created_at  TIMESTAMP
      expires_at  TIMESTAMP  NULL

    Every read is a lookup by primary key, so a key value store (DynamoDB, Cassandra) or a relational table both work.

    Whiteboard

    What you sketch in the first five minutes, before any of the detail below. Draw the boxes, then walk each path out loud.

    1. Boxes and the two paths

    Say: reads outnumber writes 100 to 1, so the redirect path must be fast and the shorten path must never hand out the same code twice.

    writes 40/s, redirects 4,000/s: 100 reads per writeclientLBwebserverscachecode → URLURL storeIDs1 hit?2 miss302 + URLlease 1,000write code, URLredirect pathshorten pathclicks → queue → analytics
    1. Draw client, load balancer and a row of stateless web servers.
    2. Redirect: cache first, the store only on a miss, answer 302 with the long URL.
    3. Shorten: take the next ID from a leased block, turn it into a code, write code and URL.

    Next question: why 302 and not 301? A 301 is cached by the browser, so you lose click counts and cannot expire the link.

    2. From an ID to a code

    Say: each server leases 1,000 IDs at a time, so it only talks to the coordinator once per thousand links.

    ID coordinatorserver Aserver B…674000 to…674999…675000 to…675999next ID at A2,009,215,674,938number ÷ 62restchar200921567493830u3240670443412c52268878113d843046414e13597599219323n3535zread bottom up: zn9edcu7 chars cover 62⁷ ≈ 3.5 trillion IDs
    1. Divide the ID by 62 and keep the remainder; repeat until nothing is left.
    2. Map each remainder to a character: 0 to 9, a to z, A to Z.
    3. Read the characters from the bottom up.

    Next question: sequential IDs give guessable codes. Shuffle the bits of the ID before encoding if that matters.

    Architecture: the redirect path and the shorten path

    Generating the short code: hash, base62 or a key service

    ApproachHowProsCons
    Hash and truncateHash the long URL (MD5, SHA-256), keep the first 7 base62 charactersSame URL gives the same code; no coordinationCollisions: check the store, rehash with a salt; an extra read on every write
    Base62 of a unique ID Common pickEach server leases a block of IDs (say 1,000) from a coordinator, encodes each ID in base62No collisions, no extra reads, simpleSequential codes are guessable unless you shuffle the bits
    Key generation servicePre-generate random codes offline; servers claim batchesRandom and collision freeOne more service; claimed keys are lost if a server crashes

    Lab: shorten a URL both ways

    Base62 of the ID

    Number÷ 62RemainderChar

    Divide by 62 until nothing is left, then read the remainders from the bottom up. Alphabet: 0 to 9, a to z, A to Z.

    Hash and truncate

    301 or 302 redirect for a URL shortener

    A 301 Moved Permanently is cached by the browser, so repeat visits never reach you. Less load, but you lose click analytics and cannot change or expire the link for that visitor. A 302 Found sends every click through your servers: more load, complete analytics. Most commercial shorteners use 302 because analytics is the product.

    Scaling redirects with a cache and the CDN

    Redirects outnumber writes 100 to 1, and clicks concentrate on recent and viral links. Cache code → long URL in Redis with LRU eviction. If the hottest 20% of a month’s links take most of the clicks, that is 20M × 500 B = 10 GB, which fits in one Redis node. Add read replicas behind the cache, and for extreme traffic answer redirects at the CDN edge.

    What the interviewer probes next

    How do custom aliases work?

    Same table, same unique key. Check availability on create and reserve words like api and login. To keep aliases from colliding with generated codes, generated codes are always exactly 7 characters and aliases must be another length, or both go through the same uniqueness check.

    How do expired links get cleaned up?

    Lazily on read (return 410 Gone when expired) plus a low priority job that deletes expired rows in batches. Never recycle codes: an old link printed in a book would suddenly point at a stranger’s page.

    How do you count clicks without slowing redirects?

    Redirect first, then publish a click event to a queue such as Kafka. Stream processors aggregate counts per link per minute into an analytics store. The redirect never waits on analytics.

    How do you stop abuse?

    Rate limit creation per user and IP, check new URLs against malware and phishing lists such as Google Safe Browsing, and require an account for high volume.

    Building blocks used here

    Want to run this as a mock interview? See interview prep.

    © 2026 Arman Ajabkhani · armantik.com · Privacy