Sign in

Designing a URL shortener from scratch to scale

Design, implement, and scale a production-ready URL shortener service while learning key system design patterns.

MonksBit Desk

November 21, 2026 · 10 min read · 102 views

Read

A URL shortener is a service that accepts a long Uniform Resource Locator (URL) and generates a compact alias called a short URL. When a client accesses the short URL, the service issues an HTTP redirect instruction that forwards the client to the original long URL.

You will need. Basic knowledge of HTTP request and response cycles · Familiarity with hash maps and key-value storage · Understanding of integer base conversion

How well do you know this already?

The full lesson

Level 1 · Beginner: Core concept and in-memory URL mapping

A URL shortener exposes two basic operations: writing a new URL and reading an existing URL. The write operation takes a long URL string and maps it to a unique, short token. The read operation takes that short token, looks up the corresponding long URL in storage, and returns an HTTP redirect response such as status code 301 or 302.

Consider a small trace where the user submits the URL https://monksbit.com/algorithms/trees. We can use an auto-incrementing integer identifier starting at 1. The first URL gets identifier 1. We store the mapping of 1 to https://monksbit.com/algorithms/trees. To make the URL compact and web-safe, we convert this integer 1 into a Base62 string composed of numbers 0 through 9, lowercase letters a through z, and uppercase letters A through Z.

In Base62 encoding, the integer 1 maps directly to the character '1'. The shortened address becomes https://sho.rt/1. When a user requests that address, the system extracts the token '1', decodes it back to integer 1, retrieves the original URL from memory, and directs the user to the destination.

Minimal in-memory URL shortener using sequential integer IDs

class SimpleUrlShortener:    def __init__(self, domain: str = "https://sho.rt/"):        self.domain = domain        self.url_to_id = {}        self.id_to_url = {}        self.counter = 1    def shorten(self, long_url: str) -> str:        if long_url in self.url_to_id:            return self.domain + str(self.url_to_id[long_url])                url_id = self.counter        self.counter += 1        self.url_to_id[long_url] = url_id        self.id_to_url[url_id] = long_url        return self.domain + str(url_id)    def resolve(self, short_token: str) -> str:        url_id = int(short_token)        return self.id_to_url.get(url_id, "")shortener = SimpleUrlShortener()token_url = shortener.shorten("https://monksbit.com/algorithms/trees")print(token_url)print(shortener.resolve("1"))

Key takeaways

  • A URL shortener requires two primary endpoints: creation and redirection.
  • The simplest implementation relies on an incrementing integer ID stored in a key-value structure.
  • Sequential numbers can represent shortened tokens but expose predictable patterns without encoding.

Level 2 · Intermediate: Base62 encoding, persistence, and redirect semantics

Using plain decimal numbers for URLs is inefficient because an identifier like 10,000,000 takes 8 characters. Base62 uses 62 distinct alphanumeric characters: ten digits (0-9), twenty-six lowercase letters (a-z), and twenty-six uppercase letters (A-Z). With 7 characters in Base62, we can represent 62 to the power of 7, which equals over 3.5 trillion unique URLs.

Base62 conversion works by repeatedly dividing an integer by 62 and using the remainder as an index into the character set. To decode back to an integer, we iterate through the characters from left to right, multiplying the accumulated value by 62 and adding the character's numeric value.

When handling redirection, HTTP distinguishes between 301 Moved Permanently and 302 Found. A 301 response directs the browser to cache the redirect locally, reducing load on our servers for subsequent clicks. However, this prevents the service from recording analytics for every click. A 302 response forces the browser to check with our server on each request, allowing precise click tracking at the expense of higher server traffic.

Edge cases must be addressed carefully. Empty inputs and malformed URLs should be rejected with an HTTP 400 Bad Request error. If a requested token does not exist in the database, the server must return an HTTP 404 Not Found error.

Base62 conversion and robust shortener service implementation

class Base62Codec:    CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"    BASE = len(CHARS)    INDEX_MAP = {char: idx for idx, char in enumerate(CHARS)}    @classmethod    def encode(cls, num: int) -> str:        if num == 0:            return cls.CHARS[0]        digits = []        while num > 0:            digits.append(cls.CHARS[num % cls.BASE])            num //= cls.BASE        return "".join(reversed(digits))    @classmethod    def decode(cls, s: str) -> int:        num = 0        for char in s:            if char not in cls.INDEX_MAP:                raise ValueError(f"Invalid character in token: {char}")            num = num * cls.BASE + cls.INDEX_MAP[char]        return numclass RobustUrlShortener:    def __init__(self, base_url: str = "https://sho.rt/"):        self.base_url = base_url        self.id_to_url = {}        self.url_to_id = {}        self.current_id = 100000    def shorten(self, long_url: str) -> str:        if not long_url or not isinstance(long_url, str):            raise ValueError("URL must be a non-empty string")                if long_url in self.url_to_id:            url_id = self.url_to_id[long_url]            return self.base_url + Base62Codec.encode(url_id)        url_id = self.current_id        self.current_id += 1        self.id_to_url[url_id] = long_url        self.url_to_id[long_url] = url_id        token = Base62Codec.encode(url_id)        return self.base_url + token    def resolve(self, token: str) -> str:        if not token or not isinstance(token, str):            raise ValueError("Token must be a non-empty string")        try:            url_id = Base62Codec.decode(token)        except ValueError:            return None        return self.id_to_url.get(url_id)service = RobustUrlShortener()short = service.shorten("https://monksbit.com/system-design")token = short.replace("https://sho.rt/", "")assert service.resolve(token) == "https://monksbit.com/system-design"assert service.resolve("invalidToken!") is None

Key takeaways

  • Base62 representation significantly shrinks token lengths compared to standard decimal numbers.
  • HTTP 301 enables client-side caching, while HTTP 302 ensures the server can count every click for analytics.
  • Input validation and boundary handling are mandatory before running base conversion algorithms.

Level 3 · Advanced: Distributed scaling, caching, and token generation strategies

In a real-world system with millions of requests per second, a single auto-incrementing counter becomes an unsustainable single point of failure and bottleneck. System designers employ either a distributed ID generator (such as Twitter Snowflake) or a pre-generated token service (Key Generation Service, or KGS). A KGS generates unique random strings in advance and stores them in a pool. When a write request arrives, an unused token is fetched and marked as used, avoiding synchronization locks on numerical counters.

URL shorteners are heavily read-intensive; read traffic often outnumbers write traffic by a ratio of 100 to 1. To protect the primary database from read exhaustion, an in-memory caching layer using Redis or Memcached sits in front of the database. When resolving a short token, the application checks the cache first. If a cache miss occurs, the backend reads from the database, writes the entry into the cache with an expiration policy, and returns the response.

Data partitioning, or sharding, becomes necessary when storage exceeds a single machine. Sharding can be performed using consistent hashing based on the short token. Consistent hashing distributes keys evenly across storage nodes and minimises data movement when nodes are added or removed from the cluster.

Security considerations include URL enumeration and malicious link distribution. Sequential identifiers allow attackers to scrape every stored link by incrementing IDs. Using pre-generated random tokens or applying Feistel cipher transformations over sequential integers obscures token predictability without creating collisions.

Simulation of a distributed token store with an LRU cache and collision-free token leasing

import collectionsimport secretsclass KeyGenerationService:    def __init__(self, initial_pool_size: int = 1000):        self.chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"        self.available_tokens = set()        self._refill(initial_pool_size)    def _refill(self, count: int):        while len(self.available_tokens) < count:            token = "".join(secrets.choice(self.chars) for _ in range(7))            self.available_tokens.add(token)    def get_token(self) -> str:        if not self.available_tokens:            self._refill(100)        return self.available_tokens.pop()class ScaledShortenerService:    def __init__(self, cache_capacity: int = 100):        self.kgs = KeyGenerationService()        self.database = {}        self.cache = collections.OrderedDict()        self.cache_capacity = cache_capacity    def shorten(self, long_url: str) -> str:        token = self.kgs.get_token()        self.database[token] = long_url        return token    def resolve(self, token: str) -> str:        if token in self.cache:            self.cache.move_to_end(token)            return self.cache[token]        long_url = self.database.get(token)        if long_url is not None:            if len(self.cache) >= self.cache_capacity:                self.cache.popitem(last=False)            self.cache[token] = long_url        return long_url

Key takeaways

  • Read-to-write ratios in URL shorteners typically exceed 100:1, demanding an aggressive caching tier.
  • A dedicated Key Generation Service eliminates the counter lock bottleneck across distributed application servers.
  • Predictable sequential IDs create vulnerability to automated scraping, requiring random token distribution or ID encryption.

Complexity

  • Time: O(1) average case for write and read operations; O(k) worst case where k is token length.
  • Space: O(N) where N is the total number of shortened URLs stored in the system.

Hash map lookups, cache checks, and Base62 encoding operations run in constant time proportional to the fixed token length (k <= 7). Space scales linearly with the number of unique records preserved in persistent storage.

Common mistakes

  • Using MD5 or SHA-256 hashes directly and truncating them without collision handling, which causes distinct URLs to overwrite each other.
  • Relying on a single auto-incrementing database column across multiple parallel database instances without shard-level offsets or distributed ID generators.
  • Using an HTTP 301 permanent redirect when real-time click analytics or link expiration features are business requirements.
  • Failing to validate inputs, allowing recursion where a user shortens a short URL pointing back to the shortening service.

Practice problems

  1. Implement Base62 decoder with character validation (easy). Hint: Process each character one by one, raising an exception if the character is not in the allowed 62-character alphabet.
  2. Implement an in-memory Least Recently Used cache for URL lookups (medium). Hint: Use a doubly linked list combined with a hash table, or standard ordered dictionary primitives, tracking access order.
  3. Design a collision-free distributed token generation scheme using worker node IDs (hard). Hint: Partition the 64-bit ID space into a timestamp component, a worker node component, and a local sequence counter.

Summary

Designing a URL shortener starts with understanding core mapping semantics between short tokens and long URLs. By introducing Base62 conversion, the system reduces integer IDs to compact web-safe tokens. Scaling to high throughput requires mitigating single-node database bottlenecks with in-memory caching tiers, choosing between HTTP 301 and 302 redirect mechanics, and utilizing distributed Key Generation Services.

Finish the Prove step above to complete this lesson.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!