Skip to content
Urlzee

How URL Shorteners Work Under the Hood

By Urlzee Team · Published · 6 min read

A URL shortener is a lookup table with a web server in front of it. Creating a link stores a row that maps a short code to a long URL. Opening the link reads that row and answers with an HTTP redirect. Everything else, from safety checks to analytics, is built around those two operations.

What are the moving parts of a URL shortener?

There are two paths through the system, and they have very different requirements.

Write path (create a link)Read path (follow a link)
Triggered byA form or API callEvery click
VolumeLowHigh; a single link may be opened many thousands of times
Work doneValidate, check safety, generate code, insertLook up code, check status, redirect, log
PriorityCorrectness and abuse preventionSpeed

The data model is small: a short code, a destination, an owner, an active flag, an optional expiry time and a click counter. The short code column has a unique index, so lookups are fast and the database itself refuses duplicates.

The rest of this article follows both paths, using Urlzee's implementation as the example.

The order of the steps matters, because cheap checks should reject bad input before expensive ones run.

  1. Normalise and parse the URL. If the input has no scheme, https:// is assumed. The result is parsed with a real URL parser, not a regular expression. Anything longer than 2,048 characters, or containing whitespace or control characters, is rejected.
  2. Apply structural rules. Only http and https are accepted. URLs with an embedded username or password are refused, as are raw IP addresses, single-label hosts such as localhost, and internal suffixes like .local and .internal.
  3. Refuse loops and chains. A destination on the shortener's own domain would create a redirect loop. Destinations on other known shorteners are refused too, because chaining redirects is the most common way to hide where a link ends up.
  4. Check blocklists. The host is compared with a list of domains already blocked for abuse, and the URL is sent to Google Safe Browsing when that check is configured.
  5. Validate the alias, if one was given. On Urlzee an alias is 3 to 50 characters, starts with a letter or number, and uses letters, numbers, hyphens and underscores. Words that are also site paths, such as pricing, blog and api, are reserved.
  6. Generate a code if there is no alias, then insert the row.

The same pipeline runs for the homepage, the bulk URL shortener and the API. The safety steps are covered in how URL shorteners prevent abuse.

How is the short code generated?

There are two mainstream designs.

Counter plus encoding. Give each link the next number from a sequence and write that number in Base62, using digits and both cases of letters. Codes are guaranteed unique and start very short. The drawback is that they are predictable: anyone can count upward and visit every link in order.

Random selection. Pick each character at random and rely on the database to catch the rare duplicate. Codes are a fixed length from the start and cannot be guessed in sequence.

Urlzee uses the random design. The alphabet is 56 characters: lowercase and uppercase letters and digits with the lookalikes 0, O, o, 1, l and I removed, so a code read from a printed page is hard to mistype. Each code is 7 characters, which gives 56^7, or about 1.7 trillion, possible values.

The random bytes come from the platform's cryptographic generator, crypto.getRandomValues. Each byte is mapped to a character, and bytes that would skew the distribution are thrown away. That technique is called rejection sampling, and Base62 encoding: how short IDs are generated explains why it is needed.

How are collisions handled?

By letting the database decide. The application does not ask "is this code free?" and then insert, because two requests could both see "free" and both try to write. Instead it attempts the insert and reads the result.

  • If the insert succeeds, the code was unique.
  • If the database reports a unique-constraint violation and the code was random, generate a new code and try again. Urlzee allows up to five attempts, which in a space of 1.7 trillion is far more than it should ever need.
  • If the violation was on a custom alias, there is nothing to retry. The API returns 409 with the code alias_taken.

This pattern, insert first and handle the conflict, is the standard way to avoid race conditions when uniqueness matters.

The read path is a short sequence that has to finish quickly. On Urlzee it goes like this:

  1. Shape check. Before touching the database, the path is tested against the pattern a valid code must match, and against the reserved words. Requests for things like /favicon.ico or random junk never cost a query.
  2. Rate limit. Requests are counted per client address, using a one-way hash of the address rather than the address itself. This slows down anyone trying to enumerate codes to harvest destinations. Over the limit, the response is 429 with a Retry-After header.
  3. Lookup. One indexed query fetches the destination, active flag and expiry for the code.
  4. Status checks. No row means 404 Not Found. A link that has been switched off, or has passed its expiry date, returns 410 Gone with a short explanation page.
  5. Redirect. Otherwise the response is a 302 with the destination in the Location header.

The redirect response carries a few deliberate headers:

HTTP/1.1 302 Found
Location: https://example.com/a/very/long/page
Cache-Control: private, no-store
X-Robots-Tag: noindex, nofollow

Cache-Control: private, no-store stops browsers and proxies from remembering the answer. X-Robots-Tag tells search engines not to index the short URL itself.

Why a 302 and not a 301?

Because a 301 is cached. A browser that has stored a permanent redirect can skip the shortener on the next visit, so the click is never counted and an edited link still leads to the old address.

A 302 with no-store guarantees every visit reaches the server. That keeps click counts trustworthy and lets the link editor change a destination with immediate effect. The wider trade-offs are in 301 vs 302 redirects.

How are clicks recorded without slowing the redirect?

By doing the logging after the response has been sent. The visitor is waiting for the redirect, not for a database write, so the write should not stand in the way.

Urlzee gathers what it needs from the request while handling it:

  • the country, from a header set by the hosting platform's edge network
  • the referrer host, meaning only the domain of the page the click came from, not the full URL
  • the device type, browser and operating system, parsed from the User-Agent header
  • a bot flag, set when the user agent matches known crawlers, link-preview fetchers and command-line clients

It then returns the 302 and writes the click record once the response is on its way. The visitor's IP address is not stored with the click. Clicks flagged as bots are kept separate, so they do not inflate the totals shown in link analytics. Why those numbers differ between tools is explained in bot traffic in link analytics.

What makes this hard at scale?

The logic is simple. The difficulty is in volume and in abuse.

  • Read-heavy load. Popular links are requested far more often than new links are created. Large services put a cache in front of the database so hot codes are answered from memory. The cache must be invalidated when a link is edited or disabled.
  • Counting. Incrementing a counter on every click creates write contention on busy rows, so services append click events and aggregate them later.
  • Abuse. A free shortener attracts people who want to hide phishing pages. Validation at creation time is not sufficient, because a destination can turn malicious later. Reports and the ability to disable a link instantly matter as much as the first check.
  • Permanence. People print short links. A shortener that loses its database, or its domain, breaks every one of them at once, which is one cause of link rot.

Frequently asked questions

How does a URL shortener generate the short code?
There are two common methods: encode a database counter in Base62, or pick random characters and retry if the result already exists. Urlzee uses the random method, drawing 7 characters from a 56-character alphabet with a cryptographically secure generator.
What happens when you click a short link?
Your browser requests the short URL, the shortener looks up the code in its database, and it replies with an HTTP redirect whose Location header holds the long URL. The browser then loads that address. The lookup typically takes milliseconds.
Can two different long URLs end up with the same short link?
No. The short code is stored under a uniqueness rule in the database, so a second insert of the same code is rejected. Random generators simply try again with a new code, and a custom alias that is taken returns an error.
Do URL shorteners store the IP addresses of people who click?
It depends on the service. Urlzee does not store visitor IP addresses with clicks; it records the country, referring site, device type, browser and operating system for each click.