System design walkthrough

A short code in,
a long URL out.

How a Bitly-style link shortener is put together: reverse proxy, stateless API servers, an ID service, Redis, a database with replicas and shards, and an analytics pipeline. Each flow plays as an animation you can pause and step through.

https://www.example.com/products/shoes/running?utm_source=newsletter&utm_campaign=autumn-sale&ref=home-banner&session=9f2c1a
sho.rt/2crtgcW
100 : 1
Clicks per link created. Reads dominate, so the design protects the redirect path.
62⁷
3,521,614,606,208 possible codes from 7 characters of a–z, A–Z, 0–9.
302
The redirect status to use when every click has to reach your servers and be counted.

How a request moves through the system

Pick a flow. The orange dot is the request, and the highlighted line is the hop it is on. Use Back and Next to step, or click any step on the right.

    synchronous call background or async current hop

    Which redirect status to send

    301 Moved Permanently302 Found
    Browser cachingBrowsers may remember the target and skip your server on repeat clicks.Not cached by default, so each click asks your server.
    Server loadLower.Higher, one request per click.
    Click analyticsRepeat clicks from the same browser are invisible to you.Every click is counted.
    Changing the target laterHard, because browsers keep the old answer.Easy.
    Choose it whenLinks never change and you do not need per-click data.You sell analytics, expiry, or editable links.

    Turning a number into a short code

    The API server holds a unique integer ID, then writes it in base 62. Dividing by 62 repeatedly gives the digits, and each digit maps to one character. Change the ID and watch the code rebuild.

    Alphabet: 0–9 are values 0–9, a–z are 10–35, A–Z are 36–61. The code is read from the last remainder to the first.

    Short code (7 characters)
    Divide by 62 until the quotient is 0

    Four ways to produce the ID

    ApproachHow it worksCollisionsThe catch
    Hash and truncateMD5 or SHA-256 of the long URL, keep the first 7 characters.PossibleCheck the database on every create and retry with a salt on a clash. The same URL always gets the same code.
    Random stringPick 7 random characters.Rare at first, more likely as the table fillsOne read before every write to check the code is free.
    Counter + base62A shared counter hands out increasing integers.NeverNeeds a distributed counter. Codes are sequential, so people can guess neighbours.
    Snowflake-style IDTimestamp, machine ID and sequence packed into 63 bits.NeverNeeds no coordination, but base62 of 63 bits is 11 characters, not 7.

    The diagram above uses counter + base62 with block leasing. Each API server asks the ID service for 1,000 IDs at once, then serves them from memory, so the ID service sees one call per 1,000 new links. To hide the sequence, run the ID through a reversible shuffle before encoding.

    Reverse proxy and load balancer

    Nginx (or a cloud load balancer) is the only public entry point. It ends TLS, limits abusive callers, and spreads requests across API servers. Stop a server below. The proxy keeps sending to it until its health check fails, retries the failed request on another server, then drops it from rotation.

    0requests sent
    0retried on another server
    0failed with 503
    nginx.conf (excerpt)
    # 10 create requests per second per IP, bursts of 20
    limit_req_zone $binary_remote_addr zone=shorten:10m rate=10r/s;
    
    upstream api {
        server api-1:8080 max_fails=2 fail_timeout=5s;
        server api-2:8080 max_fails=2 fail_timeout=5s;
        server api-3:8080 max_fails=2 fail_timeout=5s;
        keepalive 64;
    }
    
    server {
        listen 443 ssl;
        server_name sho.rt;
        # ssl_certificate and ssl_certificate_key go here
    
        location = /api/v1/shorten {
            limit_req zone=shorten burst=20 nodelay;
            proxy_pass http://api;
        }
    
        location / {
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_next_upstream error timeout http_502 http_503;
            proxy_pass http://api;
        }
    }

    What the proxy layer does

    TLSTerminated once here, so API servers speak plain HTTP on the private network.
    Rate limitingToken bucket per IP or API key. Create is limited tightly, redirects loosely.
    BalancingRound robin works because API servers are stateless. Any server can answer any request.
    Health checksFailed upstreams are skipped for a cooling-off period.
    KeepaliveReuses connections to API servers instead of opening one per click.

    The cache that takes most of the traffic

    Redis sits beside the API servers using cache-aside. Read the cache first, go to the database only on a miss, then store the answer. With maxmemory-policy allkeys-lru, Redis evicts the key used longest ago when memory is full. A few links get most of the clicks, so a small cache covers a lot. Send requests and watch it.

    most recently usedevicted next
    0%cache hit rate
    0 msaverage redirect lookup
    0clicks so far
    0database reads

    Click popularity follows a Zipf-like curve over 12 links: the first code gets the most clicks and the twelfth the fewest. Latency assumes 1 ms for a cache read and 15 ms for a database read. Those two numbers are illustrative, so measure your own.

    Redirect handler (pseudocode)
    app.get('/:code', async (req, res) => {
      const { code } = req.params;
    
      let url = await redis.get(code);          // 1. cache first
      if (!url) {
        const row = await replica.findOne(code); // 2. miss: read replica
        if (!row || (row.expires_at && new Date() > row.expires_at)) {
          return res.sendStatus(404);
        }
        url = row.long_url;
        await redis.set(code, url, 'EX', 86400); // 3. refill, 24h TTL
      }
    
      // 4. fire and forget: never wait on analytics
      kafka.send('clicks', { code, ts: Date.now() }).catch(() => {});
    
      res.redirect(302, url);
    });

    Where a click can be answered

    LayerWhen it applies
    BrowserOnly with a 301 or explicit cache headers.
    CDN edgeIf you allow edge caching of redirects. Fastest, but clicks never reach you.
    In-process LRUA tiny cache inside each API server for a few seconds. Shields Redis from one viral link.
    RedisThe main cache for code to URL.
    DatabaseLast resort on a miss. Primary key lookup on a replica.

    Database, replicas and shards

    The core access pattern is one lookup by code, which fits a key-value store as well as a relational table. Postgres, MySQL, DynamoDB, Cassandra and MongoDB all work with code as the key. Writes go to a primary, cache misses read from replicas, and when one primary can no longer take the writes, split the table across shards by a hash of the code.

    Schema
    CREATE TABLE urls (
      code        VARCHAR(10)  PRIMARY KEY,
      long_url    TEXT         NOT NULL,
      user_id     BIGINT,
      created_at  TIMESTAMPTZ  NOT NULL DEFAULT now(),
      expires_at  TIMESTAMPTZ
    );
    CREATE INDEX urls_user_idx ON urls (user_id, created_at DESC);
    
    CREATE TABLE users (
      id          BIGSERIAL    PRIMARY KEY,
      email       TEXT         UNIQUE NOT NULL,
      api_key     TEXT         UNIQUE NOT NULL,
      created_at  TIMESTAMPTZ  NOT NULL DEFAULT now()
    );
    
    -- analytics store (ClickHouse): append-only
    CREATE TABLE clicks (
      code     String,
      ts       DateTime,
      country  LowCardinality(String),
      device   LowCardinality(String),
      referrer String
    ) ENGINE = MergeTree ORDER BY (code, ts);

    API surface

    CallResult
    POST /api/v1/shorten201 with the short URL. 409 if a custom alias is taken. 429 when rate limited.
    GET /{code}302 to the long URL. 404 if unknown or expired.
    DELETE /api/v1/links/{code}204. Removes the row and the cache key.
    GET /api/v1/links/{code}/statsClick totals by day, country, device and referrer from the analytics store.

    Sharding by hash of the code

    3,000 sample codes are spread across the shards. The numbers show what happens when you add one more shard. Plain hash mod N reassigns most keys, which means a huge data move. Consistent hashing places shards on a ring, so a new shard takes keys from its neighbours only.

    0%of keys move with hash mod N when adding a shard
    0%of keys move with consistent hashing when adding a shard

    Capacity math

    Back-of-the-envelope numbers decide how many servers, how much cache and how much disk you need. Change the assumptions and the results update.

    0link creations per second (average)
    0redirects per second (average)
    0redirects per second at peak (5× average)
    0storage for all stored links
    0redirects per day
    0cache to hold 20% of a day's redirects (upper bound)

    Edge cases that break naive versions

    Custom alias clashes

    Counter IDs never collide, but a user-chosen alias can. Make code the primary key and return 409 on a unique-constraint error instead of checking first.

    Expired links

    Check expires_at on read, cap the Redis TTL at the time left, and run a batch job off-peak to delete expired rows.

    Cache stampede on a viral link

    When a hot key expires, thousands of requests miss at once. Let one request refill the cache while the rest wait, and add random jitter to TTLs.

    One hot key

    A single celebrity link can saturate one Redis node. Keep a small in-process cache on each API server for a few seconds, or replicate hot keys.

    Replica lag

    A brand-new link can 404 if read from a replica that has not caught up. The create path writes to Redis, and a miss on a recently created code can fall back to the primary.

    Bots guessing codes

    Scanners hit random codes. Cache "not found" for about a minute, rate limit by IP, and consider a Bloom filter in front of the database.

    Abuse and malware

    Accept only http and https targets, refuse to shorten your own domain to avoid loops, and check destinations against a safe-browsing list when links are created.

    Deleting a link

    Delete the row, then delete the cache key, then purge any CDN copy. Serve 410 Gone afterwards so crawlers drop it.

    Guessable sequences

    Sequential IDs let anyone enumerate links and estimate your volume. Pass the ID through a reversible shuffle before base62 encoding.

    A sensible build order

    Each step fixes the bottleneck the previous one exposes. Do not start at step 7.

    1. One API server and one Postgres. Auto-increment ID, base62 encode, 302 redirect.
    2. Redis cache-aside on the redirect path. This removes most database reads.
    3. Nginx in front with two or more API servers, health checks and rate limits.
    4. Read replicas for cache misses, keeping the primary for writes.
    5. ID block leasing so API servers stop depending on one database sequence.
    6. Kafka click events and an analytics store, so counting never slows a redirect.
    7. Shard the urls table by hash of the code once one primary cannot take the writes.