Skip to lesson

Design a URL shortener

ShopLite's marketing team wants posters and SMS to carry sl.in/aZ3k9Qx instead of a 90-character product link. Small to describe, yet this one question touches estimates, APIs, ids, databases and caching.

Your turn: ShopLite share links

Marketing will print 1 million new short links a day on posters, SMS and QR codes, and every scan must open the right product page fast. Before reading on, take two minutes and think:

  • What does the server store, and what happens when someone opens a short link?
  • Is this system mostly writing or mostly reading? Roughly how many requests per second?
  • How would you make sure two links never get the same code?

Write your answers down, then compare them with the design below.

Requirements and estimates

Read-to-write ratio is how many times a stored item is read for each time it is written. A short link is created once and opened many times, so a shortener has a high ratio, such as 100 reads for every write.

The requirements, then a short program that turns 1 million links a day into writes and reads per second and into storage.

Example 1 · Back-of-envelope estimates in code

ShortenerEstimateDemo.javaJava
public class ShortenerEstimateDemo {    public static void main(String[] args) {        long newLinksPerDay = 1_000_000;        int readsPerWrite = 100;        int peakFactor = 5;        int bytesPerRow = 500;        int years = 5;        int secondsPerDay = 86_400;
        long writesPerSecond = Math.round((double) newLinksPerDay / secondsPerDay);        long readsPerDay = newLinksPerDay * readsPerWrite;        long readsPerSecond = Math.round((double) readsPerDay / secondsPerDay);        long totalLinks = newLinksPerDay * 365 * years;        double storageGb = (double) totalLinks * bytesPerRow / 1_000_000_000;        long codeSpace = (long) Math.pow(62, 7);
        System.out.println("Writes per second (avg): " + writesPerSecond);        System.out.println("Reads per second (avg):  " + readsPerSecond);        System.out.println("Reads per second (peak): " + readsPerSecond * peakFactor);        System.out.println("Links in " + years + " years: " + totalLinks);        System.out.printf("Storage: about %.0f GB%n", storageGb);        System.out.println("7-char base62 codes: " + codeSpace);        System.out.printf("Codes used after %d years: %.3f%%%n", years, 100.0 * totalLinks / codeSpace);    }}
Output
Writes per second (avg): 12
Reads per second (avg):  1157
Reads per second (peak): 5785
Links in 5 years: 1825000000
Storage: about 913 GB
7-char base62 codes: 3521614606208
Codes used after 5 years: 0.052%

What this code does

  • Reads are writes times 100, divided by 86,400 seconds in a day: 1,157 per second on average and about 5,800 at a 5x peak.
  • 1.8 billion links of about 500 bytes need roughly 913 GB, which is close to 1 TB with indexes, so storage is not the hard part.
  • 7-character base62 codes give 3.5 trillion values; five years use only 0.052% of them.

Functional requirements say what the system does: create a short link for a long URL, and redirect a short link to its long URL. Non-functional requirements say how well: redirects under about 50 ms on our side, always available, and a code never points to the wrong URL.

With 1 million new links a day and 100 reads per write, that is about 12 writes and 1,157 reads per second on average. Codes must be short, so they are written with 62 symbols (base62); the section on codes shows how.

These numbers are assumptions you say aloud. Interviewers care that you state them and use them, not that they match a real company.

API: create a link and redirect with 301 or 302

301 vs 302 is the choice between two redirect status codes. A 301 Moved Permanently may be cached by the browser, which then skips our server; a 302 Found is temporary, so every click comes back to us.

The two API calls as curl commands, then a Java sketch of create and redirect that prints the status codes.

Terminal
curl -i -X POST https://sl.in/api/v1/urls \  -H "Content-Type: application/json" \  -d '{"longUrl": "https://shoplite.in/products/42?ref=fest"}'curl -i https://sl.in/aZ3k9Qx# HTTP/1.1 302 Found# Location: https://shoplite.in/products/42?ref=fest

Example 2 · Create and redirect, with 301 and 302

RedirectDemo.javaJava
import java.util.HashMap;import java.util.Map;
class ShortLinkApi {    private final Map<String, String> links = new HashMap<>();    private final boolean permanent;
    ShortLinkApi(boolean permanent) {        this.permanent = permanent;    }
    String create(String code, String longUrl) {        if (links.putIfAbsent(code, longUrl) != null) {            return "409 Conflict: code " + code + " is taken";        }        return "201 Created: https://sl.in/" + code;    }
    String redirect(String code) {        String target = links.get(code);        if (target == null) {            return "404 Not Found";        }        String status = permanent ? "301 Moved Permanently" : "302 Found";        return status + " | Location: " + target;    }}
public class RedirectDemo {    public static void main(String[] args) {        ShortLinkApi api = new ShortLinkApi(false);        System.out.println("POST /api/v1/urls -> " + api.create("aZ3k9Qx", "https://shoplite.in/products/42?ref=fest"));        System.out.println("POST /api/v1/urls -> " + api.create("aZ3k9Qx", "https://shoplite.in/cart"));        System.out.println("GET /aZ3k9Qx -> " + api.redirect("aZ3k9Qx"));        System.out.println("GET /nope123 -> " + api.redirect("nope123"));
        ShortLinkApi cached = new ShortLinkApi(true);        cached.create("b7Pq2Lm", "https://shoplite.in/sale");        System.out.println("GET /b7Pq2Lm -> " + cached.redirect("b7Pq2Lm"));    }}
Output
POST /api/v1/urls -> 201 Created: https://sl.in/aZ3k9Qx
POST /api/v1/urls -> 409 Conflict: code aZ3k9Qx is taken
GET /aZ3k9Qx -> 302 Found | Location: https://shoplite.in/products/42?ref=fest
GET /nope123 -> 404 Not Found
GET /b7Pq2Lm -> 301 Moved Permanently | Location: https://shoplite.in/sale

What this code does

  • putIfAbsent creates the link only when the code is free, so a second create with the same code answers 409 Conflict.
  • An unknown code gets 404 Not Found; a known one gets a redirect status and a Location header.
  • The second service is built with permanent = true and answers 301, which browsers may cache.

The API has two calls. POST /api/v1/urls with a JSON body {"longUrl": "..."} creates a link and answers 201 Created with the code. GET /{code} answers with a redirect: a status code plus a Location header that holds the long URL.

Choose 302 (or 307) when you need click analytics or may change or expire the link later. Choose 301 when you only want the lowest server load and the link never changes.

Predict the output

Pick the redirect status

Read each situation and choose the status the server should send.

Round 1 of 2

Marketing wants every click on the short link counted by our server.

GET /aZ3k9Qx
-> ??? Location: https://shoplite.in/products/42

Generating short codes: counter or hash

Base62 writes a number using 62 symbols: the digits 0–9 and the letters a–z and A–Z. A counter value such as 56,800,235,584 becomes a short code, and seven symbols can hold about 3.5 trillion different values.

Two ways to make a code, as programs: base62 of a counter, and a hash with a collision check.

Example 3 · Base62 encoding of a counter

Base62Demo.javaJava
class Base62 {    static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static String encode(long n) {        if (n == 0) {            return "0";        }        StringBuilder sb = new StringBuilder();        while (n > 0) {            sb.append(ALPHABET.charAt((int) (n % 62)));            n /= 62;        }        return sb.reverse().toString();    }
    static long decode(String code) {        long n = 0;        for (char c : code.toCharArray()) {            n = n * 62 + ALPHABET.indexOf(c);        }        return n;    }}
public class Base62Demo {    public static void main(String[] args) {        long[] ids = {0, 61, 62, 3_843, 3_844};        for (long id : ids) {            System.out.println(id + " -> " + Base62.encode(id));        }
        long start = 56_800_235_584L; // 62^6, the first 7-character number        System.out.println("First 7-char id: " + start + " -> " + Base62.encode(start));        long id = start + 1_000_000;        String code = Base62.encode(id);        System.out.println(id + " -> " + code + " -> back to " + Base62.decode(code));        System.out.println("Last 7-char code: " + Base62.encode(3_521_614_606_207L));    }}
Output
0 -> 0
61 -> Z
62 -> 10
3843 -> ZZ
3844 -> 100
First 7-char id: 56800235584 -> 1000000
56801235584 -> 1004c92 -> back to 56801235584
Last 7-char code: ZZZZZZZ

What this code does

  • encode takes the remainder by 62 as the last symbol, divides by 62, and repeats; reverse puts the symbols in the right order.
  • 62⁶ is the first number with 7 base62 digits, so a counter that starts there always gives 7-character codes.
  • decode turns the code back into the same number, which proves no two ids share a code.

Example 4 · Hash plus collision check

HashCodeGenDemo.javaJava
import java.math.BigInteger;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.HashMap;import java.util.Map;
class HashShortener {    static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";    private final Map<String, String> db = new HashMap<>();    private final int length;    int retries = 0;
    HashShortener(int length) {        this.length = length;    }
    static BigInteger sha256(String text) {        try {            byte[] hash = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));            return new BigInteger(1, hash);        } catch (NoSuchAlgorithmException e) {            throw new IllegalStateException(e);        }    }
    String codeFor(String text) {        BigInteger n = sha256(text);        StringBuilder sb = new StringBuilder();        BigInteger base = BigInteger.valueOf(62);        for (int i = 0; i < length; i++) {            sb.append(ALPHABET.charAt(n.mod(base).intValue()));            n = n.divide(base);        }        return sb.toString();    }
    String shorten(String longUrl) {        int attempt = 0;        while (true) {            String code = codeFor(attempt == 0 ? longUrl : longUrl + "#" + attempt);            String existing = db.putIfAbsent(code, longUrl);            if (existing == null || existing.equals(longUrl)) {                return code;            }            attempt++;            retries++;        }    }
    int size() {        return db.size();    }}
public class HashCodeGenDemo {    public static void main(String[] args) {        HashShortener seven = new HashShortener(7);        String first = seven.shorten("https://shoplite.in/products/42");        String again = seven.shorten("https://shoplite.in/products/42");        System.out.println("Same URL twice: " + first + " and " + again);
        HashShortener tiny = new HashShortener(2);        for (int i = 1; i <= 300; i++) {            tiny.shorten("https://shoplite.in/products/" + i);        }        System.out.println("2-char codes: " + tiny.size() + " links, collision retries: " + tiny.retries);
        for (int i = 1; i <= 300; i++) {            seven.shorten("https://shoplite.in/products/" + i);        }        System.out.println("7-char codes: " + seven.size() + " links, collision retries: " + seven.retries);    }}
Output
Same URL twice: lfGTlmY and lfGTlmY
2-char codes: 300 links, collision retries: 13
7-char codes: 300 links, collision retries: 0

What this code does

  • The same URL always gives the same hash, so it gets the same code (lfGTlmY twice).
  • With only 2 characters there are 3,844 codes, so 300 links already caused 13 collisions; each one is retried with #1, #2 added to the input.
  • With 7 characters the space is huge and there were no retries, but the check must stay because a collision is still possible.

Base62 of a counter gives each new link the next number from a counter and writes it in base62. Codes never collide, so no check is needed. Start the counter at 62⁶ (56,800,235,584) so every code has exactly 7 characters. All app servers share the counter, for example through a database sequence or a range allocator: each server takes a block of 1,000 numbers at a time and rarely calls the shared counter. The downside: the next code is the current one plus one, so counter codes are easy to guess.

Hash plus collision check hashes the long URL (for example with SHA-256) and keeps the first 7 base62 characters. Two different URLs can get the same code, which is a collision, so you must check the database and retry with a changed input when the code is taken.

Data model, cache and the read path

LRU cache is a cache that, when it is full, drops the item that was used least recently. A link nobody opened for the longest time is the least likely to be opened next.

One table, the read path drawn as a diagram with a cache in front of it, then an LRU cache written in Java.

Text
[Browser] --(1) GET /aZ3k9Qx--> [Load balancer] --> [App server x3][App server] --(2) get code--> [(Redis cache)]    hit  --> (3a) 302 Location: long URL    miss --> (3b) read --> [(MySQL urls table)] --> put in cache --> 302[App server] ..(4) click event..> [[clicks queue]] ..> [Analytics worker]
A redirect request goes from the browser to an app server, which looks in the Redis cache first. On a hit the long URL comes back at once. On a miss the app reads the row from MySQL, puts a copy in the cache, then answers 302.

Example 5 · LRU cache on the read path

ReadPathCacheDemo.javaJava
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;
class LruCache<K, V> extends LinkedHashMap<K, V> {    private final int capacity;
    LruCache(int capacity) {        super(16, 0.75f, true); // accessOrder = true: a get moves the entry to the end        this.capacity = capacity;    }
    @Override    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {        return size() > capacity;    }}
class RedirectService {    private final Map<String, String> database = new HashMap<>();    private final LruCache<String, String> cache = new LruCache<>(10);    int hits = 0;    int misses = 0;
    void save(String code, String url) {        database.put(code, url);    }
    String resolve(String code) {        String url = cache.get(code);        if (url != null) {            hits++;            return url;        }        misses++;        url = database.get(code); // the slow read in a real system        if (url != null) {            cache.put(code, url);        }        return url;    }}
public class ReadPathCacheDemo {    public static void main(String[] args) {        RedirectService service = new RedirectService();        for (int i = 0; i < 5; i++) {            service.save("hot" + i, "https://shoplite.in/sale/" + i);        }        for (int i = 0; i < 100; i++) {            service.save("cold" + i, "https://shoplite.in/p/" + i);        }
        for (int round = 0; round < 100; round++) {            service.resolve("hot" + (round % 5));            service.resolve("hot" + ((round + 2) % 5));            service.resolve("cold" + round);        }
        int total = service.hits + service.misses;        System.out.println("Requests: " + total);        System.out.println("Cache hits: " + service.hits);        System.out.println("Cache misses (database reads): " + service.misses);        System.out.printf("Hit ratio: %.1f%%%n", 100.0 * service.hits / total);    }}
Output
Requests: 300
Cache hits: 195
Cache misses (database reads): 105
Hit ratio: 65.0%

What this code does

  • LinkedHashMap with accessOrder = true keeps entries in the order they were last used, and removeEldestEntry drops the oldest when there are more than 10.
  • The 5 hot links miss once each and then always hit; the 100 cold links are each opened once, so they always miss.
  • A 65% hit ratio means the database sees only 105 of 300 requests. Real traffic is usually even more skewed toward hot links.

One table is enough: urls(code CHAR(7) PRIMARY KEY, long_url VARCHAR(2048), user_id INT, created_at, expires_at). Every redirect is a lookup by primary key, which is the fastest query a database has. About 1.8 billion rows fit on a few servers; shard by code if one server is not enough.

With 1,157 reads per second on average and a peak of about 5,800, stateless app servers behind a load balancer plus a shared cache such as Redis handle the reads. The database sees only the misses.

Order of execution

The read path on a cache miss

Put the steps in the order the app server takes them.

Extras: custom aliases, expiry and click analytics

Custom aliases, expiry and click counting added to the same table; clicks go through a queue so the redirect stays fast.

Example 6 · Custom alias, expiry and clicks through a queue

ShortenerExtrasDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.TreeMap;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;
record Link(String url, long expiresAt) {}
class Shortener {    private static final Set<String> RESERVED = Set.of("api", "admin", "login");    private final Map<String, Link> links = new HashMap<>();    private final BlockingQueue<String> clicks;
    Shortener(BlockingQueue<String> clicks) {        this.clicks = clicks;    }
    String createAlias(String alias, String url, long expiresAt) {        if (RESERVED.contains(alias)) {            return "400 Bad Request: '" + alias + "' is reserved";        }        if (links.putIfAbsent(alias, new Link(url, expiresAt)) != null) {            return "409 Conflict: '" + alias + "' is taken";        }        return "201 Created: sl.in/" + alias;    }
    String open(String code, long now) {        Link link = links.get(code);        if (link == null) {            return "404 Not Found";        }        if (now >= link.expiresAt()) {            return "410 Gone (expired)";        }        clicks.offer(code); // the click is counted later; the redirect does not wait        return "302 -> " + link.url();    }}
public class ShortenerExtrasDemo {    static final String STOP = "<stop>";
    public static void main(String[] args) throws InterruptedException {        BlockingQueue<String> clicks = new LinkedBlockingQueue<>();        Map<String, Integer> totals = new TreeMap<>();        Thread worker = new Thread(() -> {            try {                for (String code = clicks.take(); !code.equals(STOP); code = clicks.take()) {                    totals.merge(code, 1, Integer::sum);                }            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        });        worker.start();
        Shortener s = new Shortener(clicks);        long day = 86_400;        System.out.println(s.createAlias("fest2026", "https://shoplite.in/fest", 30 * day));        System.out.println(s.createAlias("fest2026", "https://other.in", 30 * day));        System.out.println(s.createAlias("admin", "https://shoplite.in/x", 30 * day));        System.out.println(s.createAlias("flash", "https://shoplite.in/flash-sale", 1 * day));
        System.out.println("Day 0: " + s.open("fest2026", 0));        System.out.println("Day 0: " + s.open("flash", 10));        s.open("fest2026", 100);        s.open("flash", 200);        s.open("fest2026", 5 * day);        System.out.println("Day 2: " + s.open("flash", 2 * day));
        clicks.offer(STOP);        worker.join();        System.out.println("Click totals: " + totals);    }}
Output
201 Created: sl.in/fest2026
409 Conflict: 'fest2026' is taken
400 Bad Request: 'admin' is reserved
201 Created: sl.in/flash
Day 0: 302 -> https://shoplite.in/fest
Day 0: 302 -> https://shoplite.in/flash-sale
Day 2: 410 Gone (expired)
Click totals: {fest2026=3, flash=2}

What this code does

  • createAlias rejects reserved words with 400 and taken aliases with 409, using one putIfAbsent call.
  • open checks expiresAt with the current time passed in, so the test can move time forward; the flash link answers 410 Gone on day 2.
  • Each redirect only calls clicks.offer; the worker thread adds up the totals. join waits for it, so the printed totals are complete.

A custom alias lets a user choose the code, such as sl.in/fest2026. Store it in the same table, block reserved words such as api and admin, and insert only if the code is free (a primary key insert that fails on a duplicate does this in one step).

Expiry stores expires_at with the link. A redirect checks it and answers 410 Gone (or 404) after that time; a cleanup job deletes old rows later. Click analytics must not slow the redirect. The app server puts a small click event on a queue and redirects at once. A background worker reads the queue and adds up the counts, so a slow analytics database never delays a user.

Next step

Check your understanding

12 quick questions