Blog/Guides
How to Design a URL Shortening Service
Design a URL shortener that survives production: Base62 codes, collision-free IDs, 301 vs 302, caching, failure modes, abuse controls, and SMS links.
Nov 11, 2026 · 24 min read

A URL shortener looks like a weekend project: take a long link, return a short one, redirect when someone clicks it. Then traffic arrives and the design questions pile up. How long should the code be, and how do you stop two requests from claiming the same one? Can the redirect stay fast when it is read 100 times for every link created? What happens when a short link has to be killed because it points somewhere harmful?
This guide walks through a design that holds up in production: requirements, a capacity estimate you can adapt, code generation that avoids both collisions and guessable sequences, a redirect path built around a cache, and the abuse and privacy controls most tutorials leave for last. The running example is a service that puts short links inside booking and reminder texts, because that case adds constraints the standard interview answer ignores.
The short version: generate 7-character Base62 codes from a counter passed through a keyed permutation, serve redirects from a cache in front of a key-value store, answer with a 302 unless a link will never change and never needs counting, and send click events to a queue instead of the database.
Start with requirements, not boxes
Write down what the service promises before drawing any architecture, because three later decisions (redirect status, code length, expiry) follow directly from those promises.
Functional requirements
Create a short link from a long URL, with an optional custom alias.
Redirect a short link to its destination.
Edit the destination, expire a link, or disable it on demand.
Report clicks per link.
Non-functional requirements
Fast redirects. Pick a latency target you can measure, such as a p99 under 100 ms at your edge.
Availability. The redirect path is the product. Link creation can degrade; redirects cannot.
Uniqueness. No two links share a code, and a code is never reissued to a different destination.
Abuse resistance. The service must not become a free way to hide phishing links.
Some interview write-ups assume links can never be deleted or edited, as ByteByteGo’s chapter on designing a URL shortener does to keep the exercise simple. Drop that assumption first. Abuse takedowns and corrected destinations both depend on it.
The running example for the rest of this guide is a booking platform that texts a client an offer for a freed-up slot. A marketing link is created once and shared for years. A link in a booking text is created for one person, opened once, and meaningless soon after, so it needs a short expiry and a way to carry context without exposing it. The section on appointment messages returns to this.
Estimate the load before choosing storage
At 5 million new links a day and a 100:1 read-to-write ratio, the service handles about 58 writes and 5,800 redirects per second, which a modest cluster can serve. The design effort goes into read latency, not write throughput.
Quantity | Assumption or formula | Result |
|---|---|---|
New links per day | Assumed | 5,000,000 |
Redirects per day | 5,000,000 × 100 | 500,000,000 |
Writes per second | 5,000,000 ÷ 86,400 | about 58 |
Redirects per second (average) | 500,000,000 ÷ 86,400 | about 5,800 |
Redirects per second (peak) | 3 × average, assumed | about 17,400 |
Record size | Code, URL, and metadata, assumed | 300 bytes |
Storage per day | 5,000,000 × 300 bytes | 1.5 GB |
Storage per year | 1.5 GB × 365 | about 548 GB |
Links after 5 years | 5,000,000 × 365 × 5 | 9.125 billion |
Storage after 5 years | 1.5 GB × 365 × 5 | about 2.7 TB |
Two things stand out. Storage is not the constraint: 2.7 TB over five years fits on one modern disk, so sharding is about availability and read throughput, not capacity. And the read side dominates, which is why the redirect path gets its own cache.
The inputs are yours to change. GeeksforGeeks’ walkthrough assumes 10 million new links and 1 billion redirects a day, and ByteByteGo assumes 100 million new links a day. The method is the same: start from writes per day, apply a read ratio, divide by 86,400, multiply by record size.
One more estimate sizes the cache. If 20 million distinct links account for most daily redirects (an assumption to replace with your own access logs), caching them at 300 bytes each takes about 6 GB, which fits in memory on a single cache node.
The same method gives a very different answer for the running example. A booking platform that sends 20,000 texts a day (a hypothetical volume) creates about 0.23 links per second and 7.3 million a year. At that scale a private shortener needs one small database and one cache node. Most of the scaling machinery below becomes optional, and the parts that still matter are expiry, token length, and message size.
Define the API and choose the redirect status
The API is two core operations plus link management, and the one decision with lasting consequences is the HTTP status you return on a redirect.
Method | Path | Purpose |
|---|---|---|
POST | /api/v1/links | Create a link from a long URL, optional alias, optional expiry |
GET | /{code} | Redirect to the destination |
GET | /api/v1/links/{code} | Read link details |
PATCH | /api/v1/links/{code} | Change destination or expiry, or disable |
DELETE | /api/v1/links/{code} | Disable permanently |
GET | /api/v1/links/{code}/stats | Read click counts |
Two details save trouble later. Accept an Idempotency-Key header on creation so a retried request returns the same code instead of minting a second one. In the booking case, a retried send job would otherwise create two live links for one offer. And keep the redirect route (/{code}) on a different deployment from the management API, so a spike in link creation never slows a redirect.
301, 302, 307, or 308
Four redirect statuses are in play. For a GET request the method-preservation difference between 301 and 308, or between 302 and 307, does not matter, so the real choice is permanent or temporary.
Status | Meaning | Browser caches it by default | Use it when |
|---|---|---|---|
301 | Permanent | Yes | The destination will never change and you do not need every click |
308 | Permanent, method preserved | Yes | Same as 301, for non-GET methods |
302 | Temporary | No | You count clicks, or may edit or disable the link |
307 | Temporary, method preserved | No | Same as 302, for non-GET methods |
A cached 301 means a returning visitor’s browser skips your server entirely. You cannot count that click, change the destination, or disable the link for that person. ByteByteGo describes the same trade-off: a 301 lowers server load while a 302 makes click tracking easier. For a public service, the takedown requirement settles it. Default to 302, and choose 301 only for links you have decided are permanent and uncounted.
Generate short codes that never collide
Seven Base62 characters give 3.5 trillion codes, far more than this service will use in a decade, so the real question is how to hand them out without collisions or a guessable order.
How long should the code be?
Base62 uses 0-9, a-z, and A-Z, so each character carries one of 62 values. The table compares code length against the 9.125 billion links the estimate predicts after five years.
Length | Distinct codes | Share used after 5 years |
|---|---|---|
5 | 916,132,832 | Exhausted in about 6 months |
6 | 56,800,235,584 | 16.1% |
7 | 3,521,614,606,208 | 0.26% |
8 | 218,340,105,584,896 | under 0.01% |
Six characters would last five years, but density matters. A randomly generated code collides with an existing one with probability roughly equal to the share of the space already used: 0.26% at seven characters after five years, 16% at six. Seven is the length both reference designs settle on, and it leaves room to skip bad codes, as described below.
Three ways to produce the code
Approach | How it works | Collisions | Order visible to outsiders |
|---|---|---|---|
Hash and truncate | Hash the long URL, keep the first 7 characters | Possible, so check the database and retry | No |
Random code | Generate 7 random Base62 characters, rely on a unique constraint | Rare, retry on conflict | No |
Counter to Base62 | Take the next integer ID, encode it | None | Yes, the next code is predictable |
Hashing has one trap beyond collisions. The same long URL always yields the same code, so two customers who shorten the same page share one link, and one customer’s delete or analytics changes the other’s. Create one code per request.
A counter never collides, but sequential codes let anyone walk the whole link space. The fix is to keep the counter and scramble its output with a keyed permutation: a one-to-one mapping from counter values to code values, so uniqueness is preserved and the order disappears. The Python below uses a four-round Feistel network over 42 bits, then walks the result back into range, which takes about 1.25 rounds on average because 2^42 is only 25% larger than 62^7.
import hashlib, hmac
ALPH = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
M = 62 ** 7 # 3,521,614,606,208 possible 7-character codes
HALF = 21 # 2 x 21 = 42 bits; 2**42 is larger than M
MASK = (1 << HALF) - 1
KEY = b"load-from-a-secret-store"
ROUNDS = 4
def _f(half, rnd):
d = hmac.new(KEY, f"{rnd}:{half}".encode(), hashlib.sha256).digest()
return int.from_bytes(d[:4], "big") & MASK
def _enc(x):
l, r = x >> HALF, x & MASK
for rnd in range(ROUNDS):
l, r = r, l ^ _f(r, rnd)
return (l << HALF) | r
def permute(counter):
"""Map 0 <= counter < M to a unique value below M."""
x = _enc(counter)
while x >= M: # cycle-walk until the value lands inside the code space
x = _enc(x)
return x
def to_base62(n, width=7):
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPH[r])
return "".join(reversed(out)).rjust(width, "0")
code = to_base62(permute(2009215674938)) # unique, with no visible orderA Feistel network is one-to-one by construction, so different counters always give different codes. Running this code over 200,000 consecutive counter values confirmed it: 200,000 distinct codes. Three operating notes:
Hand out counter blocks. Each app server leases a block of IDs from a central counter, say 100,000, and issues them locally, so creation never waits on a shared lock. A crashed server loses its unused block, which costs almost nothing against 3.5 trillion codes. Block size also sets how long creation survives a counter outage, as the failure table below shows.
Never rotate the key. A new key maps counter values you have already issued to different codes, and some of those would collide with live links. If the key leaks, ordering becomes predictable but existing links keep working.
Skip codes you do not want. Check each code against a blocklist of offensive strings and against reserved words, and take the next counter value on a hit. If people type codes by hand, drop look-alike characters (0/O, 1/l/I) and encode in base 58, which still gives about 2.2 trillion seven-character codes.
Custom aliases share the same namespace. Keep one unique index over generated codes and aliases, and if the generator ever lands on a code a customer has already claimed, skip to the next ID.
Links that open a booking hold are the exception. They should use a random 22-character token instead of this 7-character code, for the reasons given in the section on appointment messages.
Snowflake IDs and Bloom filters: what each costs
Two other techniques come up in almost every system-design discussion of this problem. Both work, and each costs something the design above avoids.
Snowflake IDs. A Snowflake ID is a 64-bit integer made of a 41-bit millisecond timestamp, a 10-bit machine ID, and a 12-bit sequence, as the Snowflake ID format is usually described. Each machine can issue 4,096 IDs per millisecond with no coordination, which removes the central counter that block leasing needs. The price is length. The 63 usable bits need 11 Base62 characters, because 62^10 is about 8.4 × 10^17 and 2^63 is about 9.2 × 10^18. That is four characters longer than the 7-character codes here, and the timestamp makes codes roughly sortable. Snowflake IDs suit internal row keys better than public codes.
Bloom filters. A Bloom filter answers “definitely not present” or “possibly present” in very little memory. ByteByteGo suggests one to avoid a database lookup on every collision check when codes come from hashing. A filter holding every live code could also reject random-probe 404s before they reach Redis. The catch is size and deletion. The standard sizing formula gives about 9.6 bits per entry for a 1% false-positive rate, so 9.125 billion codes would need roughly 11 GB, and a plain Bloom filter cannot remove an entry when a link expires. Caching the “not found” result, described below, is simpler and usually enough.
What happens when a link is created
Every rejection happens before the counter hands out an ID. The only loop is the clash check: if a code is on the blocklist or already claimed as an alias, the service takes the next ID, which costs one code out of 3.5 trillion.
Pick storage for a read-heavy key lookup
The redirect path is a single lookup by code, so almost any store works. Choose the one your team can already operate, and protect it with a cache.
Column | Type | Notes |
|---|---|---|
code | varchar(16), primary key | Case-sensitive match |
long_url | text | Validated at creation, with a maximum length you enforce |
owner_id | uuid | Who may edit or disable the link |
status | enum | active, disabled, or blocked |
expires_at | timestamp, nullable | Null means no expiry |
created_at | timestamp | For audits and cleanup |
One gotcha catches teams that move from numeric IDs to Base62. Codes use both upper and lower case, so aB3 and Ab3 are different links. A case-insensitive database collation treats them as the same key and rejects the second one as a duplicate. Use a binary or case-sensitive collation on the code column and verify it with a test that inserts both.
For private links, add a subject_ref column holding an opaque booking or message ID, never a name or phone number. Disabling a cancelled booking then disables all of its links with one query.
On SQL versus NoSQL, GeeksforGeeks lists both as options, while ByteByteGo uses a relational table. At about 58 writes per second a single primary handles the load, so decide on operations and read scaling. A relational database with read replicas covers this estimate comfortably. A managed key-value store such as DynamoDB removes the replication work if you prefer that trade.
Keep click events out of this table. They are append-only, high-volume, and queried by time range, which suits a separate analytics store.
Keep the redirect path short and cached
Serve redirects from a cache and let the database see only the misses. At a 100:1 read ratio, a 95% cache hit rate (an assumption to replace with a measured one) cuts database reads from about 5,800 per second to about 290.
A redirect request should pass through as few layers as possible:
Edge cache. A CDN or edge proxy holds the code-to-URL mapping for a short TTL, such as 60 seconds, and answers without touching your origin. Because those requests never reach your servers, the edge must report each click itself (see the analytics section).
Redirect service. On an edge miss, a stateless service checks Redis for the code.
Database read replica. On a Redis miss, read the row from a replica, then write it back to Redis with a TTL.
Click event. Whichever layer answered, publish the click to a queue after the response is on its way, never before.
Four refinements matter more than the box diagram suggests:
Cache the “not found” result. Anything probing for valid codes produces a stream of misses. Caching a miss for 30 to 60 seconds stops repeated probes from reaching the database.
Protect hot keys. One viral link means one cache key takes a large share of traffic. A small in-process cache on each app server, with a TTL of a few seconds, absorbs it.
Bound how long a disabled link keeps working. When you disable a link, delete its Redis key and purge the edge. The edge TTL is the worst-case delay for anyone whose request was served from there, so keep it short. For a 10-minute booking hold, a lapsed hold can still redirect for up to that long, so the landing page must check the hold itself.
Shard by hashed code. Hashing the code spreads links evenly across shards. The permuted codes also mean that range-based sharding on the code would not pile new writes onto the newest shard, which range-sharding on a raw counter would.
A hit at the edge or in Redis ends the request there. Only a miss in both reaches the read replica, and the click event goes to the queue after the response is on its way.
Count clicks without slowing the redirect
Write each click to a queue and return the redirect immediately. Counting synchronously puts a database write on the one path that is read 100 times more often than links are created.
Count at every layer that answers. A redirect served from the edge cache never reaches your servers, so the edge has to emit the click itself: stream its request logs into the same queue, or run the redirect logic at the edge. Otherwise your most popular links, the ones the edge answers most often, are the ones you undercount.
A click event needs only a few fields: code, timestamp, an event ID, the user agent, the referrer, and a country taken from the edge. A consumer reads the queue and rolls events up into per-link counters by minute or hour. Delivery from most queues is at-least-once, so deduplicate on the event ID before counting. Pick a retention window for raw events and keep the aggregates longer. IP addresses can count as personal data, so truncate or drop them early.
Expect non-human clicks. Link-preview generators and security scanners can request a short link before the recipient does, so tag known bot user agents and do not count a first click as proof that a person read the message. This matters most for transactional links, where a click might trigger a state change such as confirming a hold. Make the landing page, not the redirect, perform that action.
For automated messaging, the click log is the last link in an audit trail. Reading the trigger, tool calls and result of each run shows what was sent and why. The click event shows whether the link did anything afterwards.
Plan for failure and watch the right signals
Every dependency in this design can fail, and the redirect path should degrade in a defined order instead of failing all at once. The table uses the numbers from the capacity estimate.
Dependency | What breaks | Degraded behavior |
|---|---|---|
Edge cache | Every request reaches your origin | Origin and Redis must absorb the full read load: about 5,800 redirects per second on average and 17,400 at peak |
Redis | Reads fall through to replicas | At a 0% hit rate replicas see about 5,800 reads per second instead of 290. A short in-process cache and a concurrency limit per instance stop a restart from becoming a stampede |
Read replica | Cache misses cannot resolve | Serve expired cache entries for a bounded time, then return 503 with |
Counter service | New ID blocks cannot be leased | Servers keep issuing from blocks already leased. With 4 servers sharing 58 creations per second, a 1,000-ID block lasts about 69 seconds and a 100,000-ID block about 1.9 hours, so lease large blocks |
Click queue | Events cannot be published | Buffer a bounded number in memory and drop the rest. Redirects never wait on the queue, and you accept an undercount |
Primary database | Link creation fails | Return 503 on creation. Redirects continue from cache and replicas |
The 503 row matters because of the negative caching described earlier. If a replica outage returned 404 and that answer were cached, a healthy link would look dead for the length of the TTL. Losing a 100,000-ID block when a server crashes costs about 0.000003% of the 3.5 trillion codes, so large blocks are cheap.
Multi-region reads
Run the redirect service, Redis, and a read replica in each region, with all writes going to one primary region. Replication lag then creates one new failure: a link created in the primary region may not exist yet in another region’s replica, so a fast recipient gets a 404. On a replica miss, make one read from the primary before caching a not-found result. Disabled links need an explicit purge in every regional cache, with the TTL as the upper bound.
Signals to alert on
Signal | Alert when | What it tells you |
|---|---|---|
Cache hit rate, edge and Redis | It drops below the rate your capacity plan assumed (95% in the estimate) | Replicas are about to take load meant for the cache |
p99 redirect latency | It exceeds the target you set | Cache or replica degradation |
404 rate by source | One IP or range spikes | Code probing or a broken integration |
Replica lag | It grows long enough for new links to 404 in other regions | Replication is falling behind creation |
Queue lag | Consumers fall behind your reporting delay | Click counts are going stale |
Counter block headroom | Remaining IDs would run out before the next lease | Creation is about to stall |
Test every row of the failure table by switching the dependency off in staging and confirming that redirects still succeed. A degraded mode you have never exercised is a guess.
Plan for abuse, expiry, and privacy from day one
A public shortener is a free way to hide a phishing destination, so abuse controls belong in the first release, not the backlog.
Validate every destination. Allow only
httpandhttps. Rejectjavascript:anddata:URLs, enforce a maximum length, and refuse destinations on your own short domain to prevent redirect loops.Check reputation, and check again. Screen each URL at creation, then re-screen links on a schedule, because a clean page can turn malicious later. Google’s Safe Browsing APIs are for non-commercial use only, and Google points commercial services to its Web Risk API instead.
Rate-limit creation per account and per IP, and require authentication for bulk creation.
Reserve aliases. Block words such as
api,admin,login, andstatic, plus offensive strings.Return the right status. Use 404 for a code that never existed and 410 Gone for one that expired or was disabled, so crawlers and monitoring can tell them apart.
Never reissue a code. Keep expired and blocked codes reserved. A recycled code can send old messages and bookmarks to a stranger’s destination.
Expiry needs one extra rule in a cached system: set the cache TTL to the shorter of your default TTL and the time remaining until expires_at. Otherwise the cache keeps serving a link after it should have stopped.
Finally, be honest about enumeration. After five years the service holds 9.125 billion links in a space of 3.5 trillion, so a random guess lands on a live link about once in 390 attempts. Scrambled codes make links unlisted, not private. Rate-limit repeated 404s from one source, and give anything personal a much longer token, as the next section explains.
Short links in appointment messages change four design choices
A link in a booking or reminder text is created once, opened by one person, and useless soon after, so the generic design needs an expiry driven by the business event, a longer token for anything personal, a message-length budget, and a domain of its own.
Consider what an appointment business actually sends. A no-show recovery text offers a freed slot with a hold that lasts minutes. A review request goes out once, after the visit, in the language the client already used. Each carries a personal link, and each link should stop working when its moment passes.
Tie expiry to the business event
Set expires_at to the end of the hold, say 10 minutes after the offer, instead of leaving it null. When the hold lapses, return 410 and let the landing page offer the next opening rather than a dead end.
Use a longer token for personal links
A 7-character public code suits a campaign. A link that opens a booking hold should carry a random 22-character Base62 token, which holds about 131 bits and cannot be guessed in practice. Keep the long URL free of personal data: it should contain an opaque booking ID, never a name or phone number. The landing page must still confirm the hold is valid for that visitor.
Budget message length for each language
The table compares two illustrative texts written for this guide (they are examples, not production copy). The long link is 153 characters and the short link is 27.
Message | Encoding | Characters | SMS segments |
|---|---|---|---|
English, long link | GSM-7 | 224 | 2 |
English, short link | GSM-7 | 98 | 1 |
Vietnamese, long link | UCS-2 | 219 | 4 |
Vietnamese, short link | UCS-2 | 93 | 2 |
Any character outside the GSM-7 set, such as a Vietnamese diacritic, an Arabic letter, or even a smart quote pasted from a word processor, switches the whole message to UCS-2 and cuts a single segment from 160 characters to 70. Once a message spans several parts, Twilio documents 153 characters per part in GSM-7 and 67 in UCS-2, and it bills per segment. A short link cut the Vietnamese example from four segments to two.
Businesses that text in more than one language feel this first. If voice, SMS and web share one customer thread, a link created for a call-back text can also appear in the web chat and in the agent’s log, so it has to be short, stable, and safe to display in all three places.
Give each location its own link domain
Bitly’s support documentation warns that many mobile carriers block texts containing links from public shorteners and recommends a custom domain. A domain you control also keeps your sending reputation separate from strangers’ on a shared hostname. A group with several locations already keeps a separate book, hours and menu for each door. The link domain can follow the same boundary, so a complaint about one location’s texts does not lower the reputation of the others. Rules differ by country and carrier, and this guidance comes mostly from US sources, so check the requirements for every country you send to.
Build it, or put a branded domain on an existing service?
Build a shortener only when links are part of your product or tied to your own state. If you just need clean, trackable links in your own messages, a custom domain on an existing link service costs less to run than everything above.
Situation | Better choice |
|---|---|
Links appear in your own marketing and reminder messages, at modest volume | Custom domain on an existing link service |
Links must expire with your own business events, such as a booking hold, or carry per-tenant retention and privacy rules | A small private service you build |
Third parties can create links on your domain | Build only if you can staff abuse handling |
The middle row has a useful property. If only your own backend can call the create endpoint, there is no public input, nobody can use the domain to host a phishing link, and most of the abuse section above falls away. You still need the code generator, the cache, expiry, and the queue, but not the scanning pipeline or the public rate limits. A private shortener is a table, a cache, a counter, and a 302.
The last row is where teams underestimate the work. The redirect path is the easy part. Keeping a public domain off blocklists is the permanent part.
Questions
Frequently asked questions
Seven Base62 characters is the usual answer. It gives 3.5 trillion codes, which is 0.26% used after 9.125 billion links. Six characters (56.8 billion codes) lasts five years at 5 million links a day, but random generation then collides 16% of the time at the end, so retries become routine.
Use 302 by default. Browsers cache 301 responses, so returning visitors skip your server, and you cannot count their clicks or disable the link for them. Choose 301 only for links that will never change and do not need counting.
A counter passed through a keyed permutation avoids collision checks and hides the order. Hashing the long URL is simpler but needs collision handling, and it gives two customers the same code when they shorten the same page.
You cannot stop guessing in a 62-character space, only make it expensive. Scramble the order of codes, rate-limit repeated 404s, and use a random token of 22 characters (about 131 bits) for any link that is personal or sensitive.
Either. The workload is a single key lookup at about 58 writes per second in the estimate above, so choose on what your team can operate. Use a case-sensitive collation for the code column, and put a cache in front of whichever you pick.
Return 410 Gone, shorten the cache TTL so it never outlives expires_at, and keep the code reserved so it is never reissued to a different destination.
Text messages are billed and limited per segment, and non-GSM characters cut a segment from 160 characters to 70. A 27-character short link instead of a 153-character one cut an English example from 2 segments to 1 and a Vietnamese example from 4 to 2.
Conclusion
A URL shortener is easy to build and hard to run well, and the difficulty sits in a handful of decisions rather than in the architecture diagram. Generate codes from a counter passed through a keyed permutation, so they are unique and unordered. Answer redirects with a 302 unless a link is permanent and uncounted, and count clicks at every layer that answers. Serve reads from a cache, keep click counting off the redirect path, and decide in advance how each dependency degrades. Treat abuse, expiry, and privacy as part of the first release.
To start, build the thin version: one table keyed by code, a Redis cache, a counter that leases ID blocks, a 302, and a queue for click events. Add reputation screening before you open public link creation. If the links will land in messages people read on their phones, add three more checks: an expiry driven by the business event, a longer token for anything personal, and a link short enough to keep the text within one segment in the recipient’s language.
The running example in this guide comes from the kind of messaging LLDTEK works with: AI voice and chat agents for appointment businesses that answer calls, book visits, and follow up by text. When a message carries a link, the details above decide whether it arrives, fits in one segment, and stops working when it should. If you are weighing how an agent should text your clients, bring a real booking to a 30-minute demo.
Updated Dec 5, 2026.
