RandomWits

life is too short for a diary




URL shortener

Tags: system design java

Author
Written by: Tushar Sharma

Day 1 of Advent of System Design

Live Demo

Problem Description

Your marketing team wants short links for every ad campaign they run, with click counts. Your goal is to design the service that turns a long URL into a short one and sends people on their way.

How do we shorten a URL?

The service generates a short code, stores it alongside the long URL, and uses that code to look up the destination when someone clicks the link.

Option 1 : Hashing the URL

My first thought was to hash the URL with SHA-256. The same URL produces the same hash, but the full hash takes 64 hexadecimal characters. Taking just the first few characters gives us a shorter code and makes collisions more likely. Two different URLs can share the same prefix, so we'd still need a way to handle that.

Option 2: Generating a random Base62 code

We can make the string shorter by converting it to Base62. Also Base62 only uses letters and digits.

A simple program in Java

private static final String BASE62_ALPHABET =
        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

private String generateCode() {
    StringBuilder code = new StringBuilder(CODE_LENGTH);

    for (int index = 0; index < CODE_LENGTH; index++) {
        code.append(BASE62_ALPHABET.charAt(random.nextInt(BASE62_ALPHABET.length())));
    }

    return code.toString();
}

Quick note: Base 2 uses two digits, 0 and 1. A six-character binary code has two choices per position, giving 2^6 = 64 possible codes. Likewise, Base62 uses 62 characters, so a six-character Base62 code has 62^6 possible combinations.

Design

sequenceDiagram
    participant C as Client
    participant S as Short link service
    participant D as Database

    Note over C,D: Create the short link
    C->>S: POST /api/shorten<br/>Content-Type: application/json<br/>{"url":"https://example.com/campaign"}
    S->>D: Save x7Kp2 and its destination
    D-->>S: Saved
    S-->>C: HTTP 200 OK<br/>Content-Type: application/json<br/>{"code":"x7Kp2","shortUrl":"https://sho.rt/x7Kp2"}

    Note over C,D: Follow the short link
    C->>S: GET /x7Kp2 on sho.rt
    S->>D: Look up x7Kp2 and increment its click count
    alt Code exists
        D-->>S: Return the destination
        S-->>C: HTTP 302 Found<br/>Location: https://example.com/campaign<br/>Cache-Control: no-store
    else Unknown code
        D-->>S: No matching link
        S-->>C: HTTP 404 Not Found
    end

How do we count a click?

Each link has a row in the short_urls table with a click_count of zero when it’s created. Each GET request that reaches the service for a valid short link adds one. If the service handles three requests for the same link, its row stores click_count = 3.

The service increments the count and retrieves the destination in a single sql statement. e.g. in postgres

UPDATE public.short_urls
SET click_count = click_count + 1
WHERE code = :code
RETURNING original_url;

If two requests arrive for the same code at the same time, sql locks the row during the first update. The second update waits for the first to commit, then increments the updated count. Both clicks count even if different instances of the service handle them.

If the statement returns a destination, the service responds with 302 Found, puts the URL in the Location header, and sets Cache-Control: no-store. If no row matches the code, the service returns 404 Not Found.

A 302 Found signals a temporary redirect, while a 301 Moved Permanently signals a permanent one. With either status, the Cache-Control: no-store response header tells browsers and shared caches to avoid storing the redirect. That lets repeat visits reach the short-link service and be counted.


comments powered by Disqus