Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 22 of 44

Case study: design a URL shortener

A senior-level walkthrough: requirements, estimates, API and data model, the high-level design, low-level ID generation in C#, the redirect path, scale, abuse and the follow-ups interviewers use to push.

Case studyApplied16 min readUpdated

  • 2 architecture diagrams
  • 2 sequence flows
  • 3 data models
  • 2 API designs
  • 1 code sample
  • 7 interviewer follow-ups
  • 1 decision checkpoint
  • 1 capacity calculator
  • 3 self-checks

Read first: A framework for system design interviews, Caching, Replication and sharding, Queues and asynchronous work

By the end you will be able to
  • Run the full framework on a concrete problem, including numbers.
  • Draw the high-level design and walk the read and write paths.
  • Design the low-level pieces: schema, ID allocation and the classes around them.
  • Answer the senior follow-ups: hot keys, failover, multi-region, exactness and abuse.

1 code sample (85 lines), collapsed so the explanation stays in focus.

A URL shortener turns a long link into a short one and redirects whoever opens it. It is a favourite interview question because it is small enough to finish and deep enough to expose judgment. This lesson treats it the way a senior round would: first the high-level design (HLD), the boxes and the flows between them; then the low-level design (LLD), the schema, the algorithm and the classes; then the follow-ups an interviewer uses to push past the textbook answer.

HLD

Clarify the URL shortener problem

Spend the first five minutes on questions. Each one changes the design.

AskWhy it matters
Custom aliases? Expiry? Editing a link later?Aliases need a uniqueness check on a user-chosen key. Editing rules out permanent redirects that browsers cache.
Is click analytics required, and how exact?Exact counts push work onto the hot path; approximate counts do not.
Read to write ratio and expected scale?Decides cache and sharding effort.
Can links be deleted or taken down?Abuse handling and code reuse policy.
Availability target for redirects?A dead link on a printed poster is a permanent failure, so redirects need the higher bar than creation.

Functional: create a short URL, redirect visitors, optional alias and expiry, basic analytics. Non-functional: redirects are fast and highly available, codes are unique and not trivially enumerable, reads vastly outnumber writes. Out of scope: accounts, editing, a UI.

HLD

Estimate URL shortener traffic and storage

State assumptions out loud; they are illustrative and the interviewer may change them.

Example · estimate
new links:   100,000,000 / month = 100M / (30 x 86,400 s) = ~40 writes/s
redirects:   100 : 1 read ratio = ~4,000 reads/s average
peak:        ~3 x average = ~12,000 reads/s
5 years:     100M x 12 x 5 = 6 billion links
storage:     ~500 bytes per row x 6B = ~3 TB
code length: base62, 7 chars = 62^7 = ~3.5 trillion (586x headroom)
             6 chars = 62^6 = ~56.8 billion (only 9.5x headroom)
hot cache:   assume 100M distinct links read per day,
             keep the hottest 20% x ~500 B = ~10 GB (one Redis node)

Move the sliders to see what the numbers do: the creators in the estimator are the 100 million new links a month spread over a day, which is why a read-to-write ratio of 100 is the interesting input.

Try it · capacity estimatorShort links created and redirected

Three conclusions: writes are trivial (40 per second), reads are modest but must be very reliable, and the whole hot set fits in memory. The 3 TB total fits on one machine but offers no redundancy or read scaling, so we replicate from day one and shard for headroom. Seven characters is the safe code length.

HLD

The URL shortener API contract

Define the API before the boxes. Notice the idempotency key: clients retry creation, and a retry must not mint a second code.

POST/v1/links
auth
bearer token
idempotency
Idempotency-Key header, same key returns the same link
body
{ "url": "https://example.com/a/very/long/path", "alias": "optional", "expires_at": "optional ISO time" }
  • 201created, returns { "code": "aZ3kP9x", "short_url": "https://sho.rt/aZ3kP9x" }
  • 400invalid or disallowed URL
  • 409alias already taken
  • 429creation rate limit exceeded
GET/{code}
note
the hot path; no auth, cached at the edge when possible
  • 302redirect, Location is the original URL
  • 404unknown code
  • 410link expired or taken down

LLD

The URL shortener data model

The only read is "given a code, find the URL", so a key-value shape fits. The analytics table is separate because its access pattern (append only, aggregate later) is different.

linkskey-value or SQL
  • codevarchar(8)

    base62; the shard key, so every lookup hits one shard

    PKSHARD KEY
  • long_urltext

    the destination

  • owner_idbigint

    who created it; null for anonymous

    INDEXNULL
  • created_attimestamptz

  • expires_attimestamptz

    null means never

    NULL
  • statussmallint

    active, expired, blocked

Lookup is always by code. Shard by hash(code); no cross-shard queries are needed.

click_eventsappend-only log
  • event_iduuid

    makes retries idempotent downstream

    PK
  • codevarchar(8)

    INDEX
  • tstimestamptz

  • countrychar(2)

    derived at the edge

    NULL
  • referrertext

    NULL

Written through a queue, never by the redirect path directly.

id_rangescoordinator
  • next_freebigint

    one row; advanced atomically by the block size

Each app server leases a block of IDs (say one million) with a single atomic update.

HLD

The URL shortener high-level design

Fig. The system: a read path, a write path and an analytics path
Fig. The system: a read path, a write path and an analytics path

Read it as three paths. Redirects (left) are optimised for speed: edge cache first, then Redis, then the database. Creation (right) does a small amount of work: get a unique code, insert, return. Analytics hangs off a queue so counting never slows a redirect.

The read path

Fig. Redirect: the common case and the cache miss
Fig. Redirect: the common case and the cache miss

The write path

Fig. Create a link, including a collision
Fig. Create a link, including a collision

LLD

Generating the short code

This is the part the interview is really about. Every strategy trades uniqueness, coordination and guessability. Before the table, pick one.

Decision checkpoint · pick one

You create about 40 links a second from many app servers. Codes must never collide, must not be easy to enumerate, and creating a link should not wait on one machine. How do you generate the code?

Commit to an answer first. The reasoning for every option appears after you pick.

StrategyUniquenessCoordinationWeakness
Hash the URL, keep the first 7 charsCollisions possibleNoneMust detect and retry; the same URL always gives one code
Random 7 chars, check the databaseCollision chance rises with fillA read-then-write per createExtra round trip; races need a unique constraint
One global counter, base62GuaranteedEvery create hits one counterSingle bottleneck; sequential codes are guessable
Counter blocks per server, scrambledGuaranteedOne tiny lease per million createsGaps after a crash (harmless)

The block approach wins: servers lease a range of IDs once, hand them out from memory with no network call, and encode them in base62. Because consecutive IDs would be easy to enumerate, scramble each ID with a multiplication that is a bijection modulo 62 to the 7th power, so every ID still maps to a distinct code.

C# · ID allocation, scrambling and base6285 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Text;

const long Space = 3_521_614_606_208L; // 62^7 possible 7-character codes

// A fake coordinator: one atomic counter. In production this is a single-row atomic update.
long counter = 0;
long Lease(long size) { var first = counter; counter += size; return first; }

var a = new IdRangeAllocator(Lease, 1_000);
var b = new IdRangeAllocator(Lease, 1_000);
var seen = new HashSet<long>();
for (int i = 0; i < 2_500; i++)
{
    bool freshA = seen.Add(a.Next()); // keep side effects out of Debug.Assert: it is removed in Release builds
    bool freshB = seen.Add(b.Next());
    Debug.Assert(freshA && freshB, "an allocator repeated an ID");
}
Debug.Assert(counter == 6_000, "each allocator leased three blocks of 1000");

// Base62 round trip and fixed width.
Debug.Assert(Base62.Encode(0) == "0000000");
Debug.Assert(Base62.Encode(61) == "000000z");
Debug.Assert(Base62.Decode(Base62.Encode(123_456_789_012)) == 123_456_789_012);

// Scrambling must be a bijection: no two IDs may produce the same code.
var codes = new HashSet<string>();
for (long id = 0; id < 100_000; id++) codes.Add(Base62.Encode(Scrambler.Scramble(id, Space), 7));
Debug.Assert(codes.Count == 100_000, "scramble produced a duplicate code");
Debug.Assert(Base62.Encode(Scrambler.Scramble(1, Space)) != Base62.Encode(Scrambler.Scramble(2, Space)));

sealed class IdRangeAllocator
{
    private readonly Func<long, long> _lease; // reserves `size` IDs atomically and returns the first
    private readonly long _size;
    private readonly object _gate = new();
    private long _next, _end;

    public IdRangeAllocator(Func<long, long> lease, long size) { _lease = lease; _size = size; }

    public long Next()
    {
        lock (_gate)
        {
            if (_next >= _end) { _next = _lease(_size); _end = _next + _size; }
            return _next++;
        }
    }
}

static class Scrambler
{
    // Odd and not a multiple of 31, so it shares no factor with 62^7 = 2^7 * 31^7: a bijection mod Space.
    private const long Multiplier = 2_654_435_761L;
    public static long Scramble(long id, long space) => (long)(new BigInteger(id) * Multiplier % space);
}

static class Base62
{
    private const string Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static string Encode(long n, int minLength = 7)
    {
        if (n < 0) throw new ArgumentOutOfRangeException(nameof(n));
        var sb = new StringBuilder();
        do { sb.Insert(0, Alphabet[(int)(n % 62)]); n /= 62; } while (n > 0);
        while (sb.Length < minLength) sb.Insert(0, '0');
        return sb.ToString();
    }

    public static long Decode(string s)
    {
        long n = 0;
        foreach (var c in s)
        {
            int d = Alphabet.IndexOf(c);
            if (d < 0) throw new FormatException($"Not a base62 character: {c}");
            n = n * 62 + d;
        }
        return n;
    }
}

The classes around it

Fig. Low-level design: who depends on whom
Fig. Low-level design: who depends on whom

Keep the HTTP layer thin, put the rules in a service, and depend on interfaces for the generator, the repository and the clock. Each seam is a place an interviewer may ask "how would you test this?" or "swap the generator for random codes", and the answer is one implementation.

HLD

The redirect path in detail

Which status code? The choice is a product decision, not a detail.

CodeBrowser behaviourUse when
301 Moved PermanentlyCached by browsers and proxies, often indefinitelyLinks never change and you do not need every click
302 FoundNot cached; every click reaches youYou need analytics, expiry or the ability to change or remove a link

Default to 302 when analytics, expiry or takedown matter, and say why: a cached 301 is a promise you cannot take back.

What to cache. Cache the code to URL mapping at the CDN for hot links and in Redis behind it, using cache-aside with a TTL. Also cache negative results (unknown codes) for a short time, because random probing otherwise hits the database every time. A Bloom filter of valid codes in front of the cache is a cheap way to reject most unknown codes without any lookup.

Senior depth

Scaling a URL shortener and surviving failure

Scaling reads. The CDN absorbs the hottest links, Redis absorbs the rest of the hot set, and read replicas serve misses. Only a small trickle reaches the primary.

Scaling storage. Shard by hash of the code, ideally with consistent hashing so adding a shard moves little data. Every query has the code, so no query spans shards. Explore the ring in the consistent hashing lab.

FailureWhat happensMitigation
Redis is downEvery miss hits the databaseCircuit breaker, rate-limit the database, serve hot links from the CDN
A database shard is downLinks on that shard cannot be resolvedReplicas with automatic failover; the CDN keeps serving cached links
The ID coordinator is downServers can still allocate from their leased blocksLease large blocks; creation pauses only when a block runs out
A server crashes with an unused blockThe unused IDs are never usedHarmless gaps; codes are plentiful
Analytics queue is slow or downCounting lagsRedirects are unaffected because events are sent asynchronously and buffered
  • Abuse. Shorteners are used to hide phishing and malware. Check destinations against a reputation service asynchronously, support takedown (status blocked, served as 410), and rate limit creation per account and per IP (more layers in encryption, secrets and abuse).
  • Alias squatting. Reserve words (admin, api, login) and profanity; enforce a minimum length.
  • Expiry. Check expires_at when resolving (lazy expiry), and run a background sweeper to reclaim storage. Do not reuse an expired code for a long grace period, or an old printed link could open an unrelated page.

Senior depth

Questions that push past the textbook URL shortener answer

Interviewer follow-upL5A single link goes viral and receives 200,000 requests per second. What happens?How to answer

The CDN should absorb nearly all of it because the redirect is cacheable. Behind it, a hot key on one Redis node can still be a bottleneck, so add a tiny in-process cache on each redirect server (a few seconds of TTL) and coalesce concurrent misses so a thousand simultaneous misses cause one lookup. If one cache shard is still hot, replicate that key across several nodes. The database never sees it.

Interviewer follow-upL5Two users create the alias "sale" at the same instant. What stops both succeeding?How to answer

A unique constraint (or an insert-if-not-exists) on the code. The check-then-insert pattern races; the constraint makes the database the arbiter, and the loser gets a duplicate-key error that maps to 409. Never rely on an application-level "does it exist?" read.

Interviewer follow-upL6The ID coordinator fails over. How do you guarantee two servers never receive the same block?How to answer

The block lease is one atomic, durable increment. If the coordinator is a database row, the update is serialised by the database. If it is a replicated service, it must use consensus so that after failover the new leader starts from at least the last acknowledged value. If there is any doubt, skip ahead: gaps cost nothing, duplicates are a correctness bug. Fencing the lease with an epoch or version protects against a stale server that kept running during a partition.

Interviewer follow-upL6Product wants exact click counts per link. How exact can you be?How to answer

Exactly-once is not achievable end to end, so aim for at-least-once delivery plus deduplication. Give every click an event ID, write events to a log, and aggregate idempotently by event ID. Be explicit that counts lag by seconds. For unique visitors use an approximate structure such as HyperLogLog and say so. Do not put the counter increment on the redirect path.

Interviewer follow-upL6The database is down. What still works?How to answer

Cached redirects keep working: the CDN serves hot links and Redis serves the rest of the hot set, ideally with stale-while-revalidate so an expired entry is still used while the database is unreachable. Creation fails fast with a 503 and the client retries with its idempotency key. Cold links that are not cached are the only casualties, and a replica in another zone shrinks even that.

Interviewer follow-upL7You must serve a second region with active-active writes. What breaks?How to answer

Random or block-allocated codes are fine, because each region leases disjoint ID ranges and codes never collide. Custom aliases are the problem: two regions could accept the same alias concurrently. Either route alias creation to one home region, use a globally consistent store for aliases only, or accept a brief window and resolve conflicts deterministically. Reads can be served locally everywhere. State which consistency you choose and the user-visible cost.

Interviewer follow-upL7Why not just hash the long URL?How to answer

Hashing gives you collisions that you must detect and handle, and it makes the code a function of the URL, so two users who shorten the same link share a code and you cannot give each their own analytics or expiry. It also ties codes to URL content, which is awkward if the destination can be edited. If you want deduplication, do it deliberately with a separate lookup rather than by accident through hashing.

HLD

How to spend the 45 minutes on a URL shortener

MinutesDo
0 to 5Clarify requirements and scope
5 to 10Estimate and conclude what the numbers imply
10 to 15API and data model
15 to 25High-level design, then walk the read and write paths
25 to 35Deep dive: code generation and caching
35 to 45Failures, scale, abuse, and the interviewer's follow-ups

Check yourself

QuestionWhy lease blocks of IDs instead of calling a counter for every new link?Reveal answer

A per-link call makes the counter a bottleneck and a single point of failure. Leasing a block (say one million IDs) means each server touches the coordinator once per million creates, then allocates from memory, and it keeps working for a while even if the coordinator is briefly down.

QuestionWhy choose 302 over 301 for a shortener that offers analytics and expiry?Reveal answer

A 301 is cached by browsers, so later clicks never reach you: you lose the count, you cannot expire the link, and you cannot change or remove it. A 302 is not cached, so every click is observable and controllable.

QuestionWhy is the multiplicative scramble safe to use for codes?Reveal answer

Multiplying by a number that shares no factor with the code space (62 to the 7th power) is a bijection modulo that space, so different IDs always produce different codes. It hides sequence but is not cryptographic security.

Lesson 22 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 23Case study: design a news feedA senior-level walkthrough of a social feed: estimates that expose the fan-out problem, push versus pull versus hybrid with a cost rule, a merge that paginates without repeats, ranking with a fallback, and fan-out lag as a queue.

Send a message

It goes straight to my inbox. I usually reply within a few days.