Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SD
System Design
0/13 completed
Beginner
What is system design?How the internet worksBack-of-the-envelope estimation
Intermediate
Scaling basicsLoad balancersCachingDatabases at scale
Advanced
Sharding and consistent hashingMessage queues and event streamingConsistency, CAP and distributed transactionsReliability and observability
Pro
Designing a URL shortenerDesigning a chat app
Tracks / System Design / Pro

Designing a URL shortener

Let's put the track's ideas together on the most classic system design question: design a service like bit.ly or TinyURL. It looks simple (store a long URL, return a short one), but at scale it touches ID generation, encoding, databases, caching, sharding and analytics. We'll follow the method from the first lesson.

1. Requirements

Functional

  • Given a long URL, create a short link such as https://sho.rt/aZ3kQ9x.
  • Visiting the short link redirects to the long URL.
  • Optional: custom aliases (sho.rt/summer-sale), expiry dates, click analytics.

Non-functional

  • Very read-heavy: links are created once and clicked many times.
  • Redirects must be fast (under ~50 ms) and highly available: a broken short link breaks someone's campaign.
  • Short codes must be unique and not easily guessable (so people can't enumerate private links).

2. Estimates

Python · editable

Twelve billion links need at least 6 base62 characters (56.8 billion codes); 7 (3.5 trillion) leaves plenty of room and makes random guessing impractical. Read traffic of ~4,000/s (more at peak) says: cache aggressively. Six terabytes says: one big database could manage, but we should plan for sharding.

3. API

POST /api/links            { "url": "https://…", "alias": "summer-sale"?, "expiresAt": "…"? }
  → 201 { "code": "aZ3kQ9x", "shortUrl": "https://sho.rt/aZ3kQ9x" }

GET /{code}
  → 301 or 302 redirect, Location: https://…   (404 if unknown, 410 if expired)

GET /api/links/{code}/stats  → { "clicks": 1234, "byCountry": {…} }

301 or 302? A 301 (permanent) is cached by browsers, so repeat clicks never reach us: less load, but we lose analytics and can't change the target. Most shorteners use 302 (or 307) to count every click.

4. Generating short codes

This is the heart of the design. Three approaches:

A. Hash the URL

Take a hash (MD5, SHA-256) of the URL and keep the first 7 characters of its base62 form. The same URL always gives the same code, but collisions are possible (different URLs, same prefix), so every insert must check and retry, and the codes reveal whether a URL was already shortened.

B. A counter + base62

Give each link a unique number from a counter and encode it in base62. No collisions by construction:

Python · editable

Two problems: sequential codes are guessable (…aZ3, …aZ4), and one global counter is a bottleneck and a single point of failure. Fixes:

  • Ranges: a coordination service hands each app server a block of IDs (say 1,000 at a time), so servers generate codes locally with no contention.
  • Scramble the number before encoding (a reversible bit-mixing permutation, or encrypting it with a fixed key), so consecutive IDs give unrelated-looking codes.

C. Random codes

Generate 7 random base62 characters and insert with a uniqueness constraint; retry on the rare collision. Simple, unguessable, needs no coordination:

Python · editable

With 12 billion links stored, about 1 in 300 attempts needs a retry: perfectly fine. We choose random codes (or a scrambled counter), stored with a unique index.

5. High-level design

                    ┌─────────────── CDN / edge (optional redirect cache) ──────────┐
users ──▶ DNS ──▶ load balancer ──▶ redirect service (stateless, ×N) ──▶ Redis cache ──(miss)──▶ link database
                          │                         │                                            (sharded by code)
                          │                         └──▶ click events ──▶ queue/stream ──▶ analytics workers ──▶ analytics store
                          └──▶ API service (create links, auth, rate limits) ──▶ link database
  • Redirect path (the hot path): look up the code in Redis; on a miss, read the database and cache it. Popular links stay in memory, so most redirects never touch the database. Return the 302 immediately.
  • Analytics must never slow redirects: publish a small "click" event to a queue or stream (Kafka) and aggregate it asynchronously.
  • Create path: validate the URL (scheme, length, a blocklist of malicious domains), generate a code, insert with a unique constraint.

Data model

sql
CREATE TABLE links (
    code        VARCHAR(16) PRIMARY KEY,     -- the short code (or custom alias)
    long_url    TEXT NOT NULL,
    owner_id    BIGINT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at  TIMESTAMPTZ
);

The only query on the hot path is "find by code", a perfect fit for a key-value access pattern. PostgreSQL works well; DynamoDB or Cassandra are natural choices at very large scale. Shard by code (hash-based, consistent hashing): every lookup then goes to exactly one shard.

6. A working miniature

Python · editable

7. Deep dives and trade-offs

  • Availability: the redirect service is stateless and replicated across zones; the cache and database are replicated with failover. If analytics is down, redirects still work.
  • Hot links: a viral link is a "hot key"; keep a small in-process cache in each redirect server in front of Redis, or serve it from the CDN edge.
  • Abuse: rate-limit link creation per user and IP; scan targets against phishing and malware lists; let users report links.
  • Expiry: check expires_at on read; a background job deletes or archives expired rows.
  • Custom aliases share the code space: the unique constraint handles both.
  • Global latency: run redirect services in several regions with read replicas or a globally replicated key-value store, since reads dominate.

Practice

  1. Change the estimates for 1 billion new links a month. Does a 7-character code still suffice for 10 years?
  2. Add per-link click counting that doesn't write to the database on every click (batch the counts).
  3. How would you let users edit a link's destination, and what does that mean for caching and 301 vs 302?
✎ Check your understanding

1.Why do most URL shorteners use 302 rather than 301 redirects?

2.What's the main problem with encoding a single global counter in base62?

3.Why send click analytics through a queue instead of writing them during the redirect?

← Reliability and observability