> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# URL Shortener Two Ways to Make a Code

> Explains hashing versus counter methods to generate unique short codes for URL shorteners, comparing trade offs in uniqueness, statelessness, scalability, and latency

Step four: start with a high-level design for a URL shortener.

When a user requests a short URL:

* The request goes to an application server.
* The server creates a short code and stores the `(short_code, long_url)` pair in the database.
* The server returns the short URL to the user; the user can then share it publicly.
* When anyone later accesses the short link, their request goes to the application server, which looks up the short code in the database and redirects the client to the long URL.

This simple design works, but the hard part is: how do we create the short code?

We have two primary constraints:

* The code must be short (to keep URLs concise).
* The code must never repeat (no two different long URLs should map to the same short code).

If two different long URLs map to the same short code, the mapping becomes ambiguous and the service breaks. Before reading further, pause and think: how would you generate a short code that is both short and unique?

Below are two common approaches.

<Callout icon="lightbulb" color="#1CB2FE">
  This article compares two common short-code generation strategies — hashing and counting — and highlights trade-offs for scalability, uniqueness, and latency. Use the approach that fits your constraints (statelessness vs guaranteed uniqueness).
</Callout>

## Option 1 — Hashing

Idea: take the long URL, pass it through a hash function, and use a fixed-length prefix of the hash as the short code (for example, the first 7 characters). A hash function deterministically converts any input into a fixed jumble of characters.

Example:

```text theme={null}
[Linux System Administration for Beginners](https://learn.kodekloud.com/user/courses/linux-system-administration-for-beginners)
aX9dQ2zK7pLm3nR8vT1sW5yB4cF6h
shortlink.io/aX9dQ2z
```

Key properties:

* Deterministic: the same input always produces the same output.
* Not random: identical long URLs always map to the same short code.

Determinism example:

```text theme={null}
[Linux System Administration for Beginners](https://learn.kodekloud.com/user/courses/linux-system-administration-for-beginners)
[Linux System Administration for Beginners](https://learn.kodekloud.com/user/courses/linux-system-administration-for-beginners)
aX9dQ2z
aX9dQ2z
```

Collision risk and handling:

* Two different inputs can produce hashes whose first N characters are identical — a collision.
* To avoid collisions, you must check the database when generating a new code. If the code is already taken by a different long URL, modify the input (for example, append a character, use a suffix/salt, or increase the prefix length) and re-hash until you get an unused code.

Example collision flow:

```text theme={null}
OPTION 1 - HASHING

urls
short_code    long_url
aX9dQ2z       kodekloud.com/cour...
b7Kp1Rz       kodekloud.com/blog...
Qm4xT8w       kodekloud.com/pric...

Try to write one new code:
Qm4xT8w  TAKEN
--> append/change input and re-hash --> new code
```

Pros and cons (hashing):

| Aspect | Details |
| - | - |
| Pros | Simple to compute; stateless generation; deterministic mapping (same long URL -> same code). |
| Cons | Collisions grow more likely as you add entries; need a DB check on every generation and possibly multiple retries; latency increases with retries. |

When to use hashing:

* When you prefer stateless generation and deterministic behavior (same long URL yields same short code).
* When occasional rehash retries are acceptable and traffic/growth is moderate.

## Option 2 — Counting (Global Counter)

Idea: maintain a global counter that increments for each new long URL. Convert that integer into a compact alphabet (commonly Base62: 0–9, a–z, A–Z) to produce a short code.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/FNsK4qjOEH3p_rqy/images/System-Design-for-Interview-Prep/Warm-Ups-The-Read-Heavy-Classics/URL-Shortener-Two-Ways-to-Make-a-Code/url-shortener-counting-global-counter-base62.jpg?fit=max&auto=format&n=FNsK4qjOEH3p_rqy&q=85&s=39ac5d817239e735737364de8257d528" alt="An infographic showing a URL-shortening design labeled &#x22;Option 2 — Counting,&#x22; with a single global counter that hands out incremental numbers which are converted to a Base62 code (example output &#x22;4c92&#x22;) for short links. Three example URLs are shown feeding the counter." width="1920" height="1080" data-path="images/System-Design-for-Interview-Prep/Warm-Ups-The-Read-Heavy-Classics/URL-Shortener-Two-Ways-to-Make-a-Code/url-shortener-counting-global-counter-base62.jpg" />
</Frame>

Base62 encoding uses 62 symbols per position (10 digits + 26 lowercase + 26 uppercase). For example, the number of possible codes for a 7-character Base62 string is approximately `62^7 ≈ 3.5 trillion` — large enough for very high-scale needs.

Why counting avoids collisions:

* Each new link gets a unique integer (the counter value). Encoding that integer in Base62 produces a unique short code. No per-generation collision checks are required.

Pros and cons (counting):

| Aspect | Details |
| - | - |
| Pros | Guaranteed uniqueness; compact codes with Base62; no retries or collision handling. |
| Cons | Requires a stateful, central allocation mechanism that can become a bottleneck without careful design. |

Scaling strategies for the global counter:

* Use a database sequence or an atomic counter service that guarantees monotonic increments.
* Pre-allocate ID ranges to application servers (each server gets a block of IDs to use locally), reducing contention.
* Use distributed ID generators (e.g., Snowflake-style IDs) and encode the generated IDs in Base62 for shortness.

When to use counting:

* When you need strict uniqueness without retries and can provision a scalable ID allocation mechanism.
* When shortest possible codes are a priority and you can tolerate a small amount of state management.

## Comparison: Hashing vs Counting

| Metric | Hashing | Counting |
| - | - | - |
| Uniqueness | Probabilistic — collisions possible, requires checks | Deterministic — guaranteed by design |
| Statelessness | Yes (can be stateless) | No (requires a stateful counter or allocator) |
| Latency on write | Low normally, but can spike on collisions | Consistent (except for counter contention) |
| Complexity to scale | Simpler to scale app servers; must handle collision resolution | Needs design for distributed ID allocation (pre-allocation or sequences) |
| Determinism | Same URL => same code | Same URL can get different codes if submitted multiple times (unless deduplicated) |

<Callout icon="lightbulb" color="#1CB2FE">
  Choosing between hashing and counting depends on trade-offs: hashing is stateless but must handle collisions; counting guarantees uniqueness but requires a consistent, scalable way to allocate increasing IDs.
</Callout>

## Practical tips

* If you want deterministic short URLs for the same long URL, prefer hashing plus de-duplication logic (dedupe on read/write).
* If you need absolute uniqueness and minimal write-time logic, use a counter-based approach with ID pre-allocation or a distributed ID system.
* Use Base62 (or a larger alphabet) to keep codes compact; increase length only when capacity requires it.

## Links and references

* [Base62 encoding concepts](https://en.wikipedia.org/wiki/Base62)
* [Distributed ID generation (Snowflake)](https://en.wikipedia.org/wiki/Snowflake_ID)
* [Kubernetes – sequences and database techniques for distributed counters](https://kubernetes.io/docs/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/system-design-for-interview-prep/module/bf4e82c2-1292-42c6-b85f-8b6a0dad559f/lesson/ea62f033-b3d0-4fc8-9b02-92b8f67753c8" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.