From Hashing Algorithms to Distributed Caching and Database Sharding
By The Coding Gopher
Published: 2026-09-29
URL: https://thecodinggopher.substack.com/p/designing-a-url-shortener
A URL shortener is one of the most common system design interview questions, and for good reason: it’s simple to describe, but touches nearly every core concept in distributed systems — encoding schemes, database design, caching, load balancing, and scaling reads versus writes. This article walks through how to design one from scratch.
A URL shortener is an online tool that changes a long web address into a short, easy-to-share link, like Bitly or TinyURL. When people click the short link, they go right to the original page.
The Basic Problem
A user submits a long URL, like https://example.com/articles/2026/how-to-design-systems-at-scale, and the service returns a short one, like short.ly/aZ9kLm. Visiting the short URL redirects the user to the original long URL. That’s the entire product on the surface. The interesting design work is in how you generate the short code, store the mapping, and serve redirects fast at scale.
Requirements First
Before designing anything, it helps to pin down what the system actually needs to do.
Functional requirements:
-
Given a long URL, generate a unique short URL
-
Given a short URL, redirect to the original long URL
-
Optionally allow users to pick a custom alias
-
Optionally support link expiration
Non-functional requirements:
-
Low latency on redirects — this is the hot path and gets hit far more often than URL creation
-
High availability — a broken shortener breaks every link that depends on it
-
The system should scale to handle a very high read-to-write ratio, since most links are created once and clicked many times
That last point is important: URL shorteners are read-heavy systems. It’s common to see ratios like 100 reads for every 1 write, which shapes almost every downstream decision, especially around caching.
Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.
Generating the Short Code
This is the core design decision. A few common approaches:
1. Base62 Encoding of an Auto-Incrementing ID
Assign each new URL a unique numeric ID (from a database auto-increment counter or a distributed ID generator), then encode that number in base62 using the character set [a-zA-Z0-9]. Base62 is chosen because it’s URL-safe and compact — with just 6 characters, you can represent over 56 billion unique values.
Note: Base62 is used for URL shorteners because it maps unique numbers into a short, safe string using 62 case-sensitive alphanumeric characters (a-z, A-Z, 0-9). This avoids special symbols that break web links, keeps IDs very brief, and supports trillions of unique links.
This approach is simple and guarantees no collisions, but it requires a centralized or coordinated ID generator, which can become a bottleneck or single point of failure if not designed carefully. In distributed setups, this is often solved with ID generation services like Twitter’s Snowflake, which produce unique, roughly time-ordered IDs across multiple machines without needing a shared counter.
Using an auto-incrementing integer and converting it via Base62 Encoding Guide is a standard pattern for URL shorteners. It maps a unique sequential ID (0-9, a-z, A-Z) into a compact, URL-safe short code with zero collision risks.
2. Hashing the Long URL
Take the long URL, run it through a hash function like MD5 or SHA-256, and use the first several characters of the resulting hash as the short code. This avoids needing a centralized counter, since any server can compute the hash independently.
The downside is collisions: two different URLs can produce overlapping short hashes, especially once you truncate the hash to something short enough to be usable. This means the system needs a collision-resolution strategy, like checking if the generated code is already taken and appending characters or re-hashing with a salt if it is.
Hashing a long URL in a URL shortener converts a long web address into a deterministic, fixed-length string, which is then truncated or encoded to form a short visual link alias. While intuitive, a pure hashing strategy introduces significant architectural trade-offs compared to alternatives like ID-to-Base62 conversion.
3. Pre-generated Key Pool
A hybrid approach: a separate service pre-generates a large pool of unique, random short codes ahead of time and stores them in a database table, marked as “unused.” When a new URL comes in, the system just grabs one from the pool and marks it “used.” This avoids both the collision problem and the need to compute anything on the fly, at the cost of maintaining that pool and refilling it before it runs out.
Most production systems lean toward a variant of the counter-based or pre-generated approach because it sidesteps collision handling entirely, which matters a lot once you’re operating at scale.
A pre-generated key pool is a system design pattern for URL shorteners where a background service creates random unique short keys in advance and stores them in a database or cache pool. When a user submits a long URL, the system instantly grabs an existing key from the pool rather than computing or hashing it on the fly.
Build Redis, Git, Docker & Claude Code From Scratch
Want to become a better software engineer?
Trusted by engineers at Google, NVIDIA, and Anthropic, CodeCrafters helps you rebuild technologies like Redis, Git, Docker, and Claude Code from scratch so you can deeply understand how real systems work.
We’ve partnered with CodeCrafters to give all readers an exclusive 40% lifetime discount.
💡 Engineers may expense platforms like this through their team’s learning budget.
Start Building & Unlock 40% Off
Data Model
At its simplest, the core table just needs:
Given the read-heavy access pattern, short_code should be the primary lookup key, and it needs to be indexed for fast retrieval. Depending on scale, this table might live in a relational database (fine at moderate scale) or a key-value store like DynamoDB or Cassandra, which are a more natural fit once the system needs to handle very high read throughput with simple lookups by key.
Handling the Redirect
When a user visits short.ly/aZ9kLm, the flow looks like this:
-
Request hits a load balancer, routed to an application server
-
Server looks up aZ9kLm in the cache first
-
On a cache hit, it immediately issues an HTTP redirect to the long URL
-
On a cache miss, it queries the database, returns the redirect, and populates the cache for next time
This is where caching matters most. Because of the heavy read skew, a cache like Redis or Memcached in front of the database can absorb the overwhelming majority of traffic, leaving the database to handle only cold lookups and writes. A least-recently-used (LRU) eviction policy works well here, since a small fraction of links tend to receive a disproportionate share of clicks — this follows a pattern similar to a Zipfian distribution, where a small number of “hot” links account for most of the traffic.
The Zipfian distribution is a discrete probability distribution where the frequency of an item is inversely proportional to its rank. Stated simply, the most common item occurs twice as often as the second most common, three times as often as the third, and so forth, following an inverse power law.
One subtlety: whether to use an HTTP 301 (permanent) or 302 (temporary) redirect. A 301 lets browsers cache the redirect locally, reducing load on your servers for repeat visits, but it also means you lose the ability to track subsequent clicks on that link from that browser, and you can’t change the destination later without users potentially hitting a stale cached redirect. A 302 keeps every click flowing through your servers, which costs more but preserves click tracking and flexibility. Most production shorteners use 302 for exactly this reason.
Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.
Scaling the System
As traffic grows, a few components typically need attention:
-
Database read replicas: Since reads dominate, adding read replicas lets you scale read capacity horizontally without touching the write path.
-
Sharding: At very high scale, the mapping table can be sharded by short_code (e.g., using a consistent hashing scheme), spreading both storage and query load across multiple database nodes.
-
CDN or edge caching: For a globally distributed user base, caching redirects at edge locations closer to users reduces latency further than a single centralized cache can.
-
Rate limiting: To prevent abuse — like someone scripting the creation of millions of short links — the URL creation endpoint typically needs rate limiting, usually per user or per IP.
Extra Features Worth Considering
Beyond the core mechanics, a few features come up often in more complete designs:
-
Custom aliases: Letting users specify their own short code instead of an auto-generated one. This requires checking availability at creation time and handling the inevitable collisions with existing codes.
-
Analytics: Tracking click counts, referrers, geographic origin, and timestamps per link. At high volume, this is usually handled asynchronously — writes get pushed to a message queue and processed by a separate analytics pipeline, rather than blocking the redirect path itself.
-
Expiration and cleanup: Links can be set to expire after a certain time or after a certain number of clicks, with a background job periodically purging expired entries from the active dataset.
-
Malicious URL detection: Since anyone can submit a URL, some services run submitted links through a safe-browsing or phishing-detection check before shortening them, to avoid becoming an open redirect service for scams.
Summary
A URL shortener looks trivial at first glance, but designing one well means reasoning carefully about a heavily read-skewed workload, choosing a short-code generation strategy that avoids collisions and bottlenecks, and layering caching aggressively on the hot path. The core lesson generalizes well beyond this one example: for any system where reads vastly outnumber writes, the caching and read-scaling strategy usually matters more than the write path ever will.
Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.