Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

System Design: How to Design a URL Shortener (like Bitly)

A step-by-step system design walkthrough for a URL shortener like Bitly or TinyURL: requirements, capacity estimates, API, short code generation with base62, database schema, caching, 301 vs 302 redirects, analytics and scaling.

Sumit KumarUpdated Oct 11, 20265 min readSystem Design
System Design: How to Design a URL Shortener (like Bitly)

"Design a URL shortener" is one of the most common system design interview questions, and a great way to practise the whole process: clarify requirements, estimate scale, design the API and data model, then scale the hot path. Let's design a service like Bitly or TinyURL step by step.

Step 1: Clarify requirements#

Functional#

  • Given a long URL, return a short link such as https://jio.co/aZ3k9Qx.
  • Visiting the short link redirects to the original URL.
  • Optional: custom aliases, expiry dates and click analytics.

Non-functional#

  • Very low redirect latency (under ~50 ms server time).
  • High availability: broken short links are very visible.
  • Short codes should be unpredictable enough that people can't enumerate private links.
  • The workload is read-heavy: far more redirects than creations.

Step 2: Back-of-the-envelope estimates#

AssumptionValue
New links per month100 million (~40 writes/sec, peaks ~400/sec)
Read:write ratio100:1 → ~4,000 redirects/sec, peaks ~40,000/sec
Retention5 years → 6 billion links
Size per record~500 bytes
Total storage6B × 500 B ≈ 3 TB (plus replicas)
Cache (hot 20% of daily reads)A few GB fits in Redis memory

How long must the code be? With base62 (a–z, A–Z, 0–9): 626 ≈ 56.8 billion and 627 ≈ 3.5 trillion. Seven characters gives plenty of headroom. See Big O notation for estimating growth.

Step 3: High-level architecture#

URL shortener system design: clients call an API behind a load balancer, which generates base62 short codes, stores mappings in a database, caches hot links in Redis and redirects with HTTP 301 or 302
Text
Client ─▶ CDN / Load balancer ─▶ Stateless app servers ─┬─▶ Redis cache
                                                       ├─▶ Database (code → URL)
                                                       ├─▶ ID generator / key service
                                                       └─▶ Kafka ─▶ Analytics workers

Step 4: API design#

HTTP
POST /api/v1/links
Content-Type: application/json
Authorization: Bearer <token>

{ "url": "https://jiocoder.com/articles/binary-search-algorithm",
  "customAlias": null,
  "expiresAt": "2027-12-31T00:00:00Z" }

201 Created
{ "code": "aZ3k9Qx", "shortUrl": "https://jio.co/aZ3k9Qx" }

GET /aZ3k9Qx
302 Found
Location: https://jiocoder.com/articles/binary-search-algorithm

301 or 302?#

StatusBrowser behaviourTrade-off
301 Moved PermanentlyBrowser caches the redirectLess server load, but you lose click counts and can't change the target
302 Found / 307Browser asks the server each timeAccurate analytics and editable links, slightly more load

Most commercial shorteners use 302 so they can count clicks.

Step 5: Generating short codes#

Option A: hash the URL#

Take MD5/SHA-256 of the URL and keep the first 7 base62 characters. It's simple, but collisions must be detected and retried, and the same URL always maps to the same code.

Generate a unique 64-bit integer, then encode it in base62. No collisions by construction.

Java
public final class Base62 {
    private static final String ALPHABET =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String encode(long id) {
        if (id == 0) return "0";
        StringBuilder sb = new StringBuilder();
        while (id > 0) {
            sb.append(ALPHABET.charAt((int) (id % 62)));
            id /= 62;
        }
        return sb.reverse().toString();
    }

    public static long decode(String code) {
        long id = 0;
        for (char c : code.toCharArray()) {
            id = id * 62 + ALPHABET.indexOf(c);
        }
        return id;
    }
}
// encode(125_000_000_000L) → "2crtgcg"  (7 characters)

Where do unique IDs come from across many servers?

ID sourceHowNotes
Database sequenceAuto-incrementSimple; a bottleneck at very high scale
Range allocationEach server grabs a block (e.g. 1,000 IDs) from a counter in ZooKeeper/RedisFast, few coordination calls
Snowflake IDsTimestamp + machine ID + sequenceNo coordination; IDs are time-ordered
Sequential codes are guessable

Encoding consecutive IDs gives consecutive codes (aZ3k9Qx, aZ3k9Qy…), so anyone can enumerate links. Shuffle the ID with a reversible bijective scramble (for example multiply by a large odd number modulo 627, or a small Feistel cipher) before encoding.

Option C: pre-generated key service#

A separate Key Generation Service creates random 7-character codes offline, stores them in an "unused keys" table, and hands batches to app servers. Codes are random and creation is instant, at the cost of another service to run.

Step 6: Data model#

SQL
CREATE TABLE links (
  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 idx_links_user ON links (user_id, created_at DESC);

Access is a simple key-value lookup by code, so both a sharded relational database and a key-value store such as DynamoDB or Cassandra work well. See SQL vs NoSQL databases.

Step 7: The redirect hot path#

JavaScript
app.get("/:code", async (req, res) => {
  const { code } = req.params;

  let url = await redis.get(`link:${code}`);              // 1. cache
  if (!url) {
    const row = await db.findLink(code);                  // 2. database
    if (!row || (row.expires_at && row.expires_at < new Date())) {
      await redis.set(`link:${code}`, "__404__", { EX: 60 }); // cache misses too
      return res.status(404).send("Link not found");
    }
    url = row.long_url;
    await redis.set(`link:${code}`, url, { EX: 86400 });
  }
  if (url === "__404__") return res.status(404).send("Link not found");

  kafka.send({ topic: "clicks", messages: [{ key: code, value: JSON.stringify({
    code, ts: Date.now(), ua: req.get("user-agent"), ref: req.get("referer") }) }] });

  res.redirect(302, url);                                 // 3. redirect
});
  • Cache-aside with Redis serves most redirects from memory; an LRU eviction policy keeps hot links.
  • Negative caching stops repeated lookups of non-existent codes from hammering the database.
  • Analytics are asynchronous: click events go to Kafka so the redirect never waits for a write. See Kafka vs RabbitMQ.

Step 8: Scaling and reliability#

  • App tier: stateless servers behind a load balancer; add instances as traffic grows (horizontal scaling).
  • Database: shard by code using consistent hashing; add read replicas.
  • Availability over consistency: a newly created link being unavailable for a second on a replica is acceptable, so an AP-leaning store is fine.
  • Multi-region: replicate data and serve redirects from the region nearest the user.
  • Rate limiting on creation to stop spam, plus malware/phishing URL checks.
  • Expiry cleanup: a background job, or database TTLs, removes expired links.

Common follow-up questions#

QuestionShort answer
Same long URL twice: same code?Optional; keep a long_url_hash → code index per user if deduplication is required
Custom aliases?Check uniqueness with an insert that fails on conflict; reserve words like "api" and "admin"
Hot links (a viral tweet)?Cache in Redis and at the CDN edge; use local in-process caches for the very hottest keys
Counting clicks at scale?Stream events to Kafka, aggregate with stream processing, store in a column store such as ClickHouse

Key takeaways#

  • Start with requirements and estimates: the system is read-heavy, and 7 base62 characters cover trillions of links.
  • Generate codes from unique IDs encoded in base62 (scrambled to avoid guessable links), or from a pre-generated key service.
  • Store a simple code → URL mapping in a sharded key-value or relational store.
  • Serve redirects from a Redis cache with negative caching, and push analytics asynchronously through Kafka.
  • Use 302 redirects for analytics, stateless app servers for horizontal scaling and rate limiting to prevent abuse.