System Design Part 9 Design problems

Design Problem: A URL Shortener, from Estimates and Code Generation to Phishing Abuse

Bill.Lin 17 min read

System Design series Part 9-1 | Previous: Abuse Prevention | Next: News Feed | Series map

Part 9 is design problems: each one starts from requirements and estimates, puts together the building blocks from the previous eight parts, and ends with a threat model using STRIDE from the series introduction.

Scenario and problem

The talk platform is opening a URL-shortening feature to speakers and corporate customers, for sharing talk pages and tracking clicks from different marketing channels. For example, https://lec.tw/a8Kd2xQ redirects to https://lectures.example.com/lectures/42?utm_source=line.

Functional requirements

  • Create a short link: enter the original URL and get a short code; corporate customers can choose a custom code (lec.tw/acme2026)
  • Redirect: opening the short link takes you to the original URL
  • Expiry and disabling: links stop working after the event ends; a link reported as malicious must be disabled immediately
  • Click statistics: for each link, per day, the number of clicks, unique visitors, and sources

Non-functional requirements

  • Redirects must be fast and reliable: short links are printed on posters and slides, so a failed redirect means the entrance to the whole event is broken
  • Codes must never repeat; a short link always maps to exactly one original URL
  • Statistics can lag by a few minutes and can be slightly off

Scale estimates (the method from the Napkin Math post)

Item Estimate
New links per month 30 million → about 12 writes per second on average; peak estimated at 5x, about 60
Read/write ratio 100 : 1 → 3 billion redirects per month, about 1,200 per second on average
Redirect peak A popular talk posts the link during a livestream; estimated at 10x the average, about 12,000 per second
Links kept for 5 years 30 million × 12 × 5 = 1.8 billion
Link storage About 500 bytes each (URL, owner, timestamps, status) → about 900 GB
Click events 3 billion per month × about 100 bytes = about 300 GB of raw events per month
The two paths of a URL shortener1 / 5
The two paths of a URL shortenerVisitorRedirect svcLink dataLink ownersCreate linkClick statsLink ownersCreate linkLink datalong URLsave a8Kd2xQVisitorRedirect svcLink datalec.tw/a8Kd2xQlook up codeVisitorRedirect svc12k a secondEntrance must not failLink dataDisable bad links nowRedirect svcClick stats3B clicks/monthMinutes of delay is OK
  1. Create a short linkSpeakers and corporate customers enter the original URL and get a short code; corporate customers can also choose a custom code. 30 million new links a month, about 60 writes per second at peak.
  2. RedirectOpening the short link takes you to the original URL. The read/write ratio is 100 : 1: 3 billion redirects a month, about 1,200 per second on average, and almost all of them are single-key lookups.
  3. Link posted during a livestreamA popular talk posts the link during a livestream: an estimated 10x the average, about 12,000 per second. Short links are printed on posters and slides, so a failed redirect means the entrance to the whole event is broken.
  4. Disable at onceLinks must stop working after the event ends; a link reported as malicious must be disabled immediately.
  5. Click statisticsEvery redirect is a click event, about 3 billion a month. Statistics can lag by a few minutes and be slightly off, and this write-heavy path must not be tied to redirects.

This is a system where reads far outnumber writes, and almost every read is a single-key lookup. Click statistics are a separate path with heavy writes, and must not be tied to redirects.

The simplest approach and its limits

One application server plus one MySQL table, with codes made by converting an auto-increment ID to base62:

sql
CREATE TABLE short_link (
    id       BIGINT AUTO_INCREMENT PRIMARY KEY,
    long_url VARCHAR(2048) NOT NULL,
    clicks   BIGINT NOT NULL DEFAULT 0
);
-- On redirect: SELECT long_url ...; UPDATE short_link SET clicks = clicks + 1 WHERE id = ?
  • Codes can be enumerated: sequential codes let anyone try everything from lec.tw/1 to lec.tw/9999999, and every link meant “only for certain people” (an unpublished talk recording, for example) gets found; how fast the codes grow also leaks your business volume (Distributed IDs post)
  • Every click writes the same row: a popular link runs more than 10,000 UPDATEs a second against the same row, all fighting for the same row lock (Transactions and Isolation Levels post), and click counting drags down redirect latency
  • A single database: a 900 GB link table plus more than 10,000 reads a second eventually means facing replication and sharding

Core mechanism

How codes are generated

Approach How Pros Problems
Auto-increment ID to base62 Convert a database sequence or a Snowflake ID to base62 Guaranteed unique, no check needed Enumerable (Snowflake IDs can also be roughly guessed); a Snowflake ID becomes about 11 characters, which is on the long side
Hash of the original URL Take the first 7 characters of an MD5 or SHA-256 hash The same URL gets the same code Truncated hashes can still collide, which must be handled; different users shortening the same URL share the code and its statistics
Random code SecureRandom generates 7 base62 characters, with uniqueness checked on write Unpredictable, simple to build Collisions must be handled
Pre-generated code pool A separate service generates and hands out batches of unused codes ahead of time No check needed on write One more service to operate; the pool’s state must be reliable

The space of 7 base62 characters is 62⁷ ≈ 3.5 trillion. Even after 5 years with 1.8 billion links stored, the chance that a new random code hits an existing one is about 1.8 billion ÷ 3.5 trillion ≈ 0.05%, so on average only one in 2,000 creations needs a retry. So random codes plus a unique key constraint, with a retry on collision, are enough. With 6 characters (about 57 billion), the collision chance after 5 years rises to around 3%, which still works, but it does not save much length.

Custom codes (acme2026) live in the same table under the same unique key as random codes. Custom codes need a minimum length and a reserved-word list (admin, login, api), so they cannot take over system paths or pass themselves off as official.

301 or 302

Status code Browser behavior Suited to
301 Moved Permanently Can cache the redirect and go straight to the original URL afterwards, no longer going through your service Links that never change and need no statistics
302 Found (or 307) Comes back to ask every time Links that need statistics, may change destination, or may be disabled

301 cuts traffic a lot, but once a link is cached by the browser, disabling it has no effect: after a malicious link is reported, people who clicked it before are still taken straight to the malicious site. The talk platform’s links need statistics and disabling, so it uses 302, plus Cache-Control: no-store so that neither browsers nor caches in between keep the redirect.

Read path: caching and codes that do not exist

flowchart LR
    U[Browser] --> LB[Load balancer]
    LB --> R[Redirect service]
    R -->|1 check cache| C[(Redis)]
    R -->|2 on miss| DB[(Link database<br/>sharded by code)]
    R -.async.-> K[[Kafka<br/>click events]]
    K --> S[Stream aggregation] --> A[(Stats database)]
  • Cache: clicks follow a long-tail distribution, with a few popular links taking most of the traffic, so cache-aside gets a high hit rate (Caching post). Set the cache TTL to a few minutes, and actively delete the cache entry when a link is disabled
  • Codes that do not exist: an attacker tries large numbers of random codes, and every one of them goes past the cache to the database. Cache “does not exist” briefly as well, or use a Bloom filter to stop codes that definitely do not exist (Bloom Filter post)
  • Database: the access pattern is almost always fetching one row by code, which suits sharding by the hash of the code, or simply a key-value store (SQL vs NoSQL post, Sharding post). 900 GB still fits on one MySQL server, so the first version can skip sharding and use replicas to share the reads

At a peak of 12,000 redirects per second with a 95% cache hit rate, the database only handles about 600 queries per second, which one replica can take.

Click statistics: do not tie them to redirects

Writing to the database synchronously on every redirect makes redirect latency depend on the statistics writes. Instead:

  1. The redirect service sends a click event (code, time, source, a summary of the user agent) and does not wait for the write to finish
  2. Stream processing aggregates by code and by minute (Batch and Stream Processing post) and writes to a stats table
  3. Unique visitors are estimated with HyperLogLog, which needs only 12 KB per link per day, instead of storing every visitor’s ID

Click events may be lost in small numbers (at-most-once from the Pub/Sub post is an acceptable choice): when Kafka temporarily cannot take writes, the redirect must still succeed; the clicks from those few seconds just go uncounted. Redirect availability always comes before complete statistics.

The talk platform has one region in Taiwan and one in Japan. The primary of the link database is in Taiwan, and Japan reads from a replica. A speaker creates a link in Taiwan and posts it in a group right away. When a user in Japan opens it, the replica may not have received the row yet and responds 404 (Replication post).

The fix: when the replica cannot find the code, check the primary once before deciding whether to respond 404. Codes that really do not exist are rare (unless it is an attack), and attack traffic has already been stopped by the negative cache and the Bloom filter, so checking the primary costs little.

But a code the Bloom filter judges as “definitely not present” never reaches the replica or the primary at all. If the Japan region’s Bloom filter is updated asynchronously, a newly created code gets stopped by it first and ends in the same 404. So when you create a link, add the code to every region’s Bloom filter synchronously, and only then respond that the link was created. Creation traffic is only a few dozen per second, so a few dozen extra milliseconds of cross-region latency is acceptable. If adding the code fails in some region, that region stops using its Bloom filter and falls back to checking the primary until the filter is rebuilt.

Expiry and disabling

  • Check expires_at and the status at read time; do not rely on a background job to delete links right on time
  • A background job periodically moves links that expired long ago to a history table, keeping the main table lean
  • Do not reassign expired codes to someone else: old posters and old emails still contain the URL, and reassigning it sends someone else’s traffic to a new destination

Comparing options

Decision Choice Rejected alternatives and why
Code 7-character random base62, unique key plus retry Auto-increment ID: enumerable; hash: collisions to handle, and shared codes; code pool: one more service
Redirect 302, no caching allowed 301: no statistics, no disabling
Storage MySQL plus replicas, lookups by code; shard by the hash of the code as it grows A distributed database from day one: 900 GB does not need it yet
Cache Redis cache-aside, plus negative caching Caching redirects at the CDN: statistics would have to come from CDN logs, and disabling a link means purging the CDN; consider it when traffic grows another order of magnitude
Statistics Async events + stream aggregation + HyperLogLog Synchronous writes: lock contention on a hot row slows down redirects

In Java

1. The table

sql
CREATE TABLE short_link (
    code        VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,   -- case-sensitive
    long_url    VARCHAR(2048) NOT NULL,
    owner_id    BIGINT       NOT NULL,
    status      VARCHAR(10)  NOT NULL DEFAULT 'ACTIVE',                       -- ACTIVE, DISABLED
    expires_at  TIMESTAMP(3) NULL,
    created_at  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    PRIMARY KEY (code),
    KEY idx_owner (owner_id, created_at)
);

ascii_bin is the key: MySQL’s default collation is case-insensitive, so a8Kd2xQ and A8KD2XQ are treated as the same value. That cuts the base62 space by well over half, and it causes errors like “creation says the code is taken, but the lookup returns someone else’s link”.

java
@Service
public class ShortLinkService {

    private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
    private static final int CODE_LENGTH = 7;
    private static final int MAX_ATTEMPTS = 3;

    private final JdbcClient jdbc;
    private final LinkTargetValidator validator;
    private final SecureRandom random = new SecureRandom();

    public ShortLinkService(JdbcClient jdbc, LinkTargetValidator validator) {
        this.jdbc = jdbc;
        this.validator = validator;
    }

    public String create(long ownerId, String longUrl, Instant expiresAt) {
        URI target = validator.validate(longUrl);           // scheme, length, and malicious-URL checks; see the threat model
        for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
            String code = randomCode();
            try {
                jdbc.sql("""
                                INSERT INTO short_link (code, long_url, owner_id, expires_at)
                                VALUES (:code, :url, :owner, :expiresAt)
                                """)
                        .param("code", code)
                        .param("url", target.toString())
                        .param("owner", ownerId)
                        .param("expiresAt", expiresAt == null ? null : Timestamp.from(expiresAt))
                        .update();
                return code;
            } catch (DuplicateKeyException e) {
                // about a 0.05% chance; retry with another code
            }
        }
        throw new IllegalStateException("Code collided " + MAX_ATTEMPTS + " times in a row; check whether the code space is nearly full");
    }

    private String randomCode() {
        char[] code = new char[CODE_LENGTH];
        for (int i = 0; i < CODE_LENGTH; i++) {
            code[i] = BASE62[random.nextInt(BASE62.length)];
        }
        return new String(code);
    }
}

Three collisions in a row are almost impossible under normal conditions (0.05% cubed). If it does happen, the code space is nearly full or the random number generator has a problem, and the service should raise an alert rather than retry forever.

3. Redirecting

java
@RestController
public class RedirectController {

    private static final Pattern CODE = Pattern.compile("^[0-9A-Za-z]{4,16}$");

    private final LinkResolver resolver;
    private final ClickEventPublisher clicks;

    public RedirectController(LinkResolver resolver, ClickEventPublisher clicks) {
        this.resolver = resolver;
        this.clicks = clicks;
    }

    @GetMapping("/{code}")
    public ResponseEntity<Void> redirect(@PathVariable String code, HttpServletRequest request) {
        if (!CODE.matcher(code).matches()) {
            return ResponseEntity.notFound().build();         // reject malformed codes right away, without checking the cache or database
        }
        return resolver.resolve(code)                           // cache → replica → primary, including the negative cache
                .filter(link -> link.isActiveAt(Instant.now()))
                .map(link -> {
                    clicks.publish(code, request);              // async; a failure does not affect the redirect
                    return ResponseEntity.status(HttpStatus.FOUND)
                            .location(link.target())
                            .header(HttpHeaders.CACHE_CONTROL, "no-store")
                            .header("Referrer-Policy", "no-referrer")
                            .<Void>build();
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}
java
@Component
public class ClickEventPublisher {

    private final KafkaTemplate<String, ClickEvent> kafka;

    public ClickEventPublisher(KafkaTemplate<String, ClickEvent> kafka) {
        this.kafka = kafka;
    }

    public void publish(String code, HttpServletRequest request) {
        ClickEvent event = ClickEvent.from(code, request);       // keep only the fields statistics need; never the full IP
        try {
            kafka.send("link-clicks", code, event);             // do not wait for the result
        } catch (RuntimeException e) {
            // e.g. the local buffer is full: drop this click, redirect as usual
        }
    }
}
  • The click-event producer uses a smaller max.block.ms, so it fails fast when the broker is unreachable, instead of leaving the redirect thread stuck in send() waiting for metadata
  • Referrer-Policy: no-referrer keeps the short link itself (possibly an unpublished link) from leaking to the destination site through Referer

The code above is written against the official documentation for Spring Boot 4.1 and Spring for Apache Kafka, and has not been compiled or run. LinkResolver and LinkTargetValidator are illustrative components.

Pitfalls and gotchas

  • A case-insensitive collation on the code column: as explained above, this is the easiest mistake to miss
  • Thinking of statistics or disabling only after choosing 301: redirects that are already cached cannot be taken back
  • Click statistics written synchronously to the same row: redirect latency on popular links slows down along with the statistics
  • Reassigning expired codes: old URLs get sent to new destinations
  • Redirecting to yourself: a short link points to another short link, or to itself, forming a loop. Reject your own domain as a destination at creation time
  • Normalizing original URLs: the same URL can differ in case, trailing slash, and parameter order. If “the same URL shares a code”, decide the normalization rules first; the talk platform does not share codes, so it does not need them
  • Cross-region 404s: a link just created cannot be found in another region

Threat model

STRIDE Threat On the talk platform Defense
Spoofing Wrapping malicious URLs in your domain An attacker creates lec.tw/xxxx pointing to a phishing site, and users click because they trust lec.tw Check against malicious-URL lists at creation time (Google Safe Browsing, for example); show an interstitial page before redirecting for new accounts or unverified creators; a fast report-and-disable process
Tampering Changing the destination of someone else’s link The edit API checks only that you are logged in, not that you own the link Object-level authorization (8-2)
Repudiation The creator of a malicious link denies creating it No way to trace afterwards who created it Audit records of the creator, time, and source IP
Information disclosure Enumerating unpublished links; statistics leaking Trying sequential codes one by one to find recording links for unpublished talks Random codes; Referrer-Policy; object-level authorization on the statistics API; click events do not store full IPs
Denial of service Large numbers of nonexistent codes going past the cache; mass link creation Scans of random codes overload the database Format checks, negative caching, Bloom filter; rate limiting on link creation (8-5)
Elevation of privilege Reaching the internal network through the preview feature; javascript: URLs When “generating a link preview”, the server fetches the destination URL, which has been pointed at an internal service; a javascript: destination runs script in some contexts Allow only http and https; apply SSRF protection to the preview feature (8-2)

There is also a system-level risk: domain reputation. Once enough malicious links use your domain, browsers, email services, and messaging apps may list all of lec.tw as dangerous, and every legitimate link stops working along with it. This is the most serious operational risk for a URL shortener, so how fast malicious URLs are detected and disabled is a metric to monitor.

When to use it, and when not to

  • Build your own: when you need your own domain, statistics integrated with an existing account system, or control over the data (for example, corporate customers’ links must not pass through a third party)
  • Use an existing service: when you only need short links now and then, and the operating cost of building your own (especially handling malicious links) is not worth it
  • When to re-evaluate: when redirect volume grows another order of magnitude, consider handling redirects at the CDN edge; when the number of links approaches what one database can hold, shard by the hash of the code

References

Comments