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.
System design walkthrough
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.
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.
| 301 Moved Permanently | 302 Found | |
|---|---|---|
| Browser caching | Browsers may remember the target and skip your server on repeat clicks. | Not cached by default, so each click asks your server. |
| Server load | Lower. | Higher, one request per click. |
| Click analytics | Repeat clicks from the same browser are invisible to you. | Every click is counted. |
| Changing the target later | Hard, because browsers keep the old answer. | Easy. |
| Choose it when | Links never change and you do not need per-click data. | You sell analytics, expiry, or editable links. |
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.
| Approach | How it works | Collisions | The catch |
|---|---|---|---|
| Hash and truncate | MD5 or SHA-256 of the long URL, keep the first 7 characters. | Possible | Check the database on every create and retry with a salt on a clash. The same URL always gets the same code. |
| Random string | Pick 7 random characters. | Rare at first, more likely as the table fills | One read before every write to check the code is free. |
| Counter + base62 | A shared counter hands out increasing integers. | Never | Needs a distributed counter. Codes are sequential, so people can guess neighbours. |
| Snowflake-style ID | Timestamp, machine ID and sequence packed into 63 bits. | Never | Needs 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.
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.
# 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; } }
| TLS | Terminated once here, so API servers speak plain HTTP on the private network. |
| Rate limiting | Token bucket per IP or API key. Create is limited tightly, redirects loosely. |
| Balancing | Round robin works because API servers are stateless. Any server can answer any request. |
| Health checks | Failed upstreams are skipped for a cooling-off period. |
| Keepalive | Reuses connections to API servers instead of opening one per click. |
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.
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.
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);
});
| Layer | When it applies |
|---|---|
| Browser | Only with a 301 or explicit cache headers. |
| CDN edge | If you allow edge caching of redirects. Fastest, but clicks never reach you. |
| In-process LRU | A tiny cache inside each API server for a few seconds. Shields Redis from one viral link. |
| Redis | The main cache for code to URL. |
| Database | Last resort on a miss. Primary key lookup on a replica. |
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.
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);
| Call | Result |
|---|---|
| POST /api/v1/shorten | 201 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}/stats | Click totals by day, country, device and referrer from the analytics store. |
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.
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.
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.
Check expires_at on read, cap the Redis TTL at the time left, and run a batch job off-peak to delete expired rows.
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.
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.
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.
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.
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.
Delete the row, then delete the cache key, then purge any CDN copy. Serve 410 Gone afterwards so crawlers drop it.
Sequential IDs let anyone enumerate links and estimate your volume. Pass the ID through a reversible shuffle before base62 encoding.
Each step fixes the bottleneck the previous one exposes. Do not start at step 7.