# Design a URL Shortener Like bit.ly: System Design Guide

> How to design a URL shortener like bit.ly: capacity arithmetic, base62 key generation, a Postgres schema, 301 versus 302, Redis caching, analytics and abuse control.

URL: https://www.matthewswong.com/en/blog/design-url-shortener-system-design/

- Author: Matthews Wong (https://www.matthewswong.com/en/about/)
- Published: 2026-10-10
- Updated: 2026-10-10
- Category: Backend

> **Key takeaway:** To design a URL shortener like bit.ly, give every long URL a unique counter value and encode it in base62, so seven characters cover 3.5 trillion links. Store the code and URL in Postgres, cache hot redirects in Redis, answer with a 302 when you need click analytics, and write click events asynchronously in batches.

A URL shortener looks like a toy: one table, one redirect. Then you write down the traffic and it turns out to be a textbook read-heavy key-value problem, where the redirect path must stay fast while the write path, the analytics and the abuse handling all want a share of the same database.

This is a worked design, not a war story. I have not operated a shortener at this scale, so every number below is derived from stated assumptions with the arithmetic shown, and the protocol and database behaviour comes from RFC 9110, the PostgreSQL and Redis documentation. The stack is the one I reach for on a single VPS: Postgres, Redis and a Node service.

## What are the requirements and how big is the system?

Start with what the service promises, because it decides every later trade-off. Four requirements carry almost all of the design:

- Create: turn a long URL into a short code, optionally with a custom alias and an expiry date.
- Redirect: resolve a code to its long URL with very low latency, because a slow redirect is a slow page for every visitor.
- Analytics: count clicks per link over time, without slowing the redirect.
- Safety: do not become the cheapest way to hide phishing links, and be able to switch a bad link off in seconds.

Now the capacity arithmetic. These inputs are assumptions chosen to make the maths concrete, not measurements of any real service. Change them and the conclusions scale linearly.

Two results shape everything else. Reads outnumber writes 100 to 1, so the redirect path deserves a cache and the create path does not. And a year of links is 600 GB at the assumed row size, which a single Postgres node can hold, but five years at 3 TB is where you would start planning partitioning or sharding rather than hoping.

## How long should the short code be?

Base62 uses digits, uppercase and lowercase letters: 62 symbols, so a code of length n can name 62 to the power n links. The arithmetic below, using the 6 billion links from the capacity block, gives the answer.

Six characters would fit 6 billion links, but only by running at 10.6 percent full, and I would still pick seven. If codes are sequential, length decides only the cosmetics. If codes are scrambled or random, a sparse space is what makes guessing a valid code expensive. Base62 is also safe in a URL path: RFC 3986 lists letters and digits among the unreserved characters, so no percent-encoding is ever needed. Avoid base64, whose plus and slash characters are not.

## How do you generate unique short keys?

There are three realistic strategies. The question that separates them is where uniqueness comes from: a counter, a hash, or an allocator that hands out ranges.

| Approach | How uniqueness is achieved | Collisions | Main drawback |
| --- | --- | --- | --- |
| Base62 of a counter | A database sequence gives each link the next integer, encoded in base62 | None by construction | The counter is a single point of coordination, and raw codes are enumerable |
| Hash of the long URL | Hash the URL and keep the first 6 to 7 characters | Grow with the table; each one needs a check and a retry | Collision handling on the write path, and the same URL always maps to the same code |
| Pre-generated ranges | Each app instance reserves a block of ids and hands them out from memory | None, because blocks never overlap | A crash forfeits the unused part of a block, which leaves gaps |

The hash option sounds attractive because it needs no coordination, but the birthday problem makes it quietly expensive. Truncating to six characters leaves 56.8 billion possible codes, and the collision rate is simply how full that space already is.

I prefer a counter with block allocation: a sequence or a key_blocks row is touched once per block, not once per link, and the code is computed in the app. Here is the encoder and decoder in TypeScript, using BigInt because ids beyond 2 to the power 53 lose precision as a normal number.

> Raw counter codes reveal how many links you have created and let anyone walk the space one code at a time. Multiplying the id by a constant modulo 62 to the power 7 is a cheap bijection that scatters consecutive ids, but it is obfuscation, not security. If links must be unguessable, use random codes with a unique constraint instead.

## What does the database schema look like?

One table is the source of truth for redirects, keyed by the code itself so the hot lookup is a single primary-key probe. Click data lives in separate tables so it can never bloat the one the redirect reads.

The sequence is the simplest id source. PostgreSQL documents that a sequence value is not reclaimed when its transaction aborts and that crashes can leave gaps, which is harmless for a code space this large. To avoid a database round trip per link, reserve ids in blocks instead.

The block reservation is one UPDATE with RETURNING, and the row lock serialises concurrent reservers, so two instances can never receive the same range. The cost of that safety is that the key_blocks row becomes a very small hot spot, which is why the block is large.

## Should the redirect be a 301 or a 302?

This is the question interviewers like, and the answer is a trade between speed and visibility. RFC 9110 says a 301 means the target has a new permanent URI and a 302 means it resides temporarily elsewhere, so the client should keep using the original URL. The practical difference is caching.

| Property | 301 Moved Permanently | 302 Found |
| --- | --- | --- |
| Cache default | Heuristically cacheable per RFC 9110, so browsers may reuse it with no explicit headers | Not in the heuristically cacheable list, so reused only with explicit freshness headers |
| Click analytics | Repeat clicks may never reach your server, so counts are undercounted | Every click reaches you unless you set a short max-age |
| Changing the destination | Hard, because cached copies keep the old target | Easy, because the next request asks you again |
| Server load | Lowest, because the browser skips you after the first visit | Highest, which is why a Redis cache sits in front of it |

My default is a 302 with a short private max-age, which gives analytics a chance to count nearly every click while still sparing the server from rapid repeats in the same browser. A 301 is right only when the link is truly permanent and you do not need per-click counts, such as redirecting a retired domain.

> A 301 is hard to undo. Once a browser has cached it, you cannot recall it: disabling a link for abuse will not stop clients that never ask again, and your analytics will silently undercount. Default to 302 and choose 301 deliberately.

## How do you cache redirects?

With 100 times more reads than writes, use cache-aside in front of Postgres: check Redis, fall back to the database on a miss, then populate the cache. Cache misses too, briefly, so a burst of requests for a code that does not exist cannot hammer the database.

Size the cache from the working set, not the total. Redis lets you cap memory with maxmemory and choose an eviction policy; allkeys-lfu keeps the codes that are requested often and drops the long tail. The hit ratio then decides how much traffic reaches Postgres.

The arithmetic shows why a few points of hit ratio matter more than they look: going from 90 to 99 percent cuts database reads tenfold. When a link is disabled or edited, delete its cache key at the same time, or a takedown will not take effect until the TTL expires.

## How do you record clicks without slowing the redirect?

The redirect path must never wait for an analytics write. Push each click into an in-memory buffer, answer the redirect, and flush the buffer in batches. One multi-row INSERT of thousands of clicks costs far less than thousands of single-row inserts.

Raw clicks go into a partitioned table, and a periodic job rolls them up into one row per code per hour. Dashboards read the small rollup table; the raw partitions can be dropped by day when you no longer need them. The ON CONFLICT clause in the INSERT statement documentation is what makes the additive rollup work.

Be honest about the trade: a crash loses whatever sat in the buffer, up to one second of clicks. For analytics that is an acceptable loss and for billing it would not be. If you need exactness, put a durable queue between the redirect and the database and accept the extra moving part.

## How do you stop abuse?

A shortener hides the destination by design, which phishing and malware campaigns love. Abuse handling is part of the design, not a later patch, and these five controls cover the common cases:

Validate on create: allow only http and https schemes, cap the URL length, and refuse javascript and data URLs.

Rate limit creation per account and per IP, and require an account for custom aliases or bulk creation.

Check destinations against a threat list such as the Google Safe Browsing lists at creation time, and re-check periodically because a clean page can turn malicious later.

Keep a disabled_at switch and delete the cache key when you flip it, so a takedown works in seconds.

If you ever fetch the destination to read its title, block private and loopback addresses first, or you have built a server-side request forgery tool.

Also reserve words such as admin, api and login so that a custom alias can never shadow a route of your own service. None of these is exotic; skipping any one of them is what turns a small service into somebody's phishing infrastructure.

A URL shortener is a read-heavy key-value store with three jobs bolted on. Derive the numbers first, generate codes from a counter or reserved ranges instead of hashes, default to a 302 so you can count clicks, cache the redirect, and keep every non-essential write off the request path.

## Sources and further reading

- IETF: RFC 9110, HTTP Semantics (301, 302 and cacheability)
- IETF: RFC 3986, URI Generic Syntax (unreserved characters)
- PostgreSQL docs: sequence manipulation functions
- Redis docs: key eviction and maxmemory policies
- Wikipedia: Birthday problem
- Google: Safe Browsing

## Source links

- https://www.rfc-editor.org/rfc/rfc9110.html
- https://www.rfc-editor.org/rfc/rfc3986.html
- https://www.postgresql.org/docs/current/functions-sequence.html
- https://redis.io/docs/latest/develop/reference/eviction/
- https://en.wikipedia.org/wiki/Birthday_problem
- https://developers.google.com/safe-browsing

## FAQ

### How do you design a URL shortener like bit.ly?

Accept a long URL, assign it a unique id from a counter or a reserved block of ids, and encode that id in base62 to get the short code. Store code and URL in a database keyed by the code, serve redirects through a cache such as Redis, and record clicks asynchronously so analytics never slows the redirect.

### How many characters does a short URL need?

Base62 gives 62 to the power n codes for n characters, so six characters allow 56.8 billion and seven allow 3.5 trillion. At 100 million new links a month for five years you reach 6 billion links, which fits in six characters but leaves a dense space. Seven characters are a safer choice, especially if codes are scrambled.

### Should a URL shortener use a 301 or a 302 redirect?

Use a 302 by default. A 301 is heuristically cacheable under RFC 9110, so browsers can skip your server on repeat visits, which undercounts clicks and makes the destination hard to change. Choose a 301 only for genuinely permanent links where per-click analytics do not matter.

### Is it better to hash the URL or use a counter to generate short codes?

A counter encoded in base62 never collides, while a truncated hash does. With six characters and 6 billion stored links, about 10.6 percent of new hash inserts would land on a used code and need a retry. A counter or block allocation avoids that, at the cost of coordinating the id source.

### How do you prevent a URL shortener from being used for phishing?

Validate schemes and URL length at creation, rate limit link creation, and check destinations against a threat list such as Google Safe Browsing, then re-check them periodically. Keep a disabled flag and delete the cached redirect when you set it so a takedown works within seconds. Reserve route-like aliases so they cannot shadow your own pages.

---

- HTML version: https://www.matthewswong.com/en/blog/design-url-shortener-system-design/
- Bahasa Indonesia: https://www.matthewswong.com/id/blog/design-url-shortener-system-design/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
