Part 3 of How Backend Systems Scale →

Unique IDs: Counters, Base62, Hashes, and Key Pools

10 min readUpdated

Part 3 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.

A store saves its first order as number 1. The next order becomes number 2. For a while, an ID is just a number that keeps increasing.

Then we add a second application server. If both start their own counter at 1, they can identify two different orders with the same value.

Making the number shorter won’t fix that. Making it look random won’t necessarily fix it either. We need to separate the representation of an ID from the mechanism that makes it safe to allocate.

On this page

Begin with the simplest correct mapping

An array gives us a small model to reason about:

  1. Append a record.
  2. Use its position as the ID.
  3. Read that position to retrieve the record later.

The model makes lookup straightforward. It also makes its assumptions visible:

  • Restarting an in-memory process loses the records and allocation state.
  • Independent processes can reuse the same positions.
  • Deleting an entry must not shift the identity of every later entry.
  • Concurrent increments need coordination.
  • Decimal IDs grow in display length and expose allocation order.

A database sequence addresses persistence and concurrent allocation differently from an unprotected application integer. Neither needs to generate gap-free numbers to identify records correctly.

Suppose a request receives an ID and then fails before saving its record. Leaving a gap can be harmless. Reassigning that ID while the original request might still complete is much harder to justify.

Convert to Base62 by hand

Our counter may allocate unique values, but we might want a compact public representation. That is a separate problem.

Choose this alphabet:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

It contains 62 symbols, representing digits from zero through 61. Positional notation works as it does in base ten, except each position is worth a power of 62.

Let’s encode decimal 125:

StepDivisionRemainderCharacter
1125 / 62 = 2, remainder 111
22 / 62 = 0, remainder 222

Division gives us the least significant digit first. Reverse the remainders’ characters to get 21. Decoding confirms it: 2 × 62 + 1 = 125.

ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

def encode_id(number):
    if number < 0:
        raise ValueError("ID must be nonnegative")
    if number == 0:
        return ALPHABET[0]
    digits = []
    while number:
        number, remainder = divmod(number, 62)
        digits.append(ALPHABET[remainder])
    return "".join(reversed(digits))

def decode_id(text):
    if not text:
        raise ValueError("ID must not be empty")
    number = 0
    for character in text:
        number = number * 62 + ALPHABET.index(character)
    return number

The encoder takes one iteration per output digit. It produces no leading zeroes, so a public API should decide whether to accept or reject non-canonical inputs with leading zeroes. Invalid characters fail lookup in this example.

Our fixed alphabet matters. Another alphabet order would produce different strings for the same number.

Base64 is a different convention for encoding bytes. Standard Base64 includes + and /; a URL-safe variant changes symbols. Don’t mix its rules with this custom Base62 integer representation.

Derive code length instead of guessing it

Suppose the system must retain about ten billion distinct IDs. We can check the required space:

bits needed = ceil(log2(N))
fixed-length characters needed = ceil(log_base_alphabet_size(N))
  • 2^30 is roughly 10^9.
  • 2^34 is roughly 1.7 × 10^10, enough for 10^10 distinct values.
  • Six Base62 characters provide 62^6 ≈ 5.7 × 10^10 fixed-length combinations.

So six characters have enough sequential capacity under these assumptions:

62^6 ≈ 5.7 × 10^10 possible fixed-length codes

The encoding preserved the counter’s uniqueness. It didn’t create that property. It also didn’t make the allocation order secret; someone who knows the alphabet can decode it.

Choose the guarantees before the generator

An order, a photo, and a public invitation code can need different properties. Write down which ones matter:

  • Global uniqueness or uniqueness within one account.
  • Ordering by creation time.
  • Maximum display length.
  • Whether approximate allocation volume may be exposed.
  • Whether generators can contact shared authority.
  • Lifetime retained record count.

These requirements help compare the mechanisms:

MethodHow it worksMain trade-off
Database sequenceDatabase allocates increasing numbersShared allocation dependency; gaps are normal
Allocated rangesEach generator receives an exclusive blockRange ownership must remain safe across failures
Random IDGenerator chooses from a large spaceCollision probability must be acceptable and handled
Time plus worker plus counterFields divide responsibilityUnique worker assignment, clock behavior, and overflow need rules
Pre-generated poolAllocate unused codes ahead of requestsConsumption must be atomic and the pool must not run dry

A small store can often begin with database-generated IDs. Choosing that starting point doesn’t require exposing the same representation publicly forever.

Let several servers use one counter safely

Contacting the allocator for every ID is one option. Another is to reserve exclusive ranges:

  • A owns 1 through 10,000.
  • B owns 10,001 through 20,000.
  • Each allocates locally until its range runs out.

At 10^3 total IDs per second, ranges of 10^4 reduce average central allocations to about one every ten seconds across the fleet, ignoring partially used ranges.

Reservation must be atomic and durable. If A crashes after using only fifty values, don’t immediately give its apparently unused range to B. A might restart or an outstanding request might still finish. Gaps are usually cheaper than duplicate identities.

Keep three uses of hashing separate

A counter gives us one allocation strategy. Hashing an input gives us another way to propose a code, with different behavior.

For example, hashing the same long URL twice produces the same digest. If each submission must receive a different ID, the URL alone cannot be the complete input.

We might add a unique allocation value or another distinct component. A timestamp alone is insufficient: several requests can share one clock tick. Hashing the result doesn’t remove that ambiguity.

There are also different reasons to use a hash function:

UseWhat is being solvedRequired property
Hash-table lookupFind the bucket for a keySuitable distribution and collision handling
Cryptographic hashingProduce a digest under security requirementsAppropriate modern cryptographic properties
Short public-code generationFit identifiers into a limited namespaceCapacity, predictability requirements, and uniqueness policy

The hash table that stores code-to-record mappings is a different mechanism from a cryptographic digest used to propose codes.

Truncating a digest introduces a smaller output space. Different inputs can collide, even when the full digest has strong cryptographic properties. URL normalization, per-user ownership, custom aliases, and expiration also change what should count as the same record.

MD5 and SHA-1 appear in older explanations. Don’t treat those examples as recommendations for collision-resistant cryptographic security. RFC 6151 discusses MD5’s limitations. The crypto guide explains how hashing differs from encryption and other primitives.

Treat a collision as a write outcome

Random candidates let independent generators avoid consulting a counter for each attempt. The price is that two attempts can choose the same value.

For n independent uniform draws from M possibilities, when the collision probability is small:

probability of at least one collision ≈ n(n - 1) / (2M)

With a million six-character Base62 candidates:

  • n ≈ 10^6.
  • M ≈ 5.7 × 10^10.
  • The expression is about 8.8, so the small-probability approximation is outside its useful range.
  • The chance of at least one collision is already high, even though most codes are unused.

A random generator can still be useful. We need the write path to handle collisions:

  1. Generate a candidate using a random generator suited to the predictability requirement.
  2. Attempt the insert with a uniqueness constraint.
  3. Generate another candidate if that code is already taken.
  4. Bound retries and handle exhaustion or unexpected failures.

The constraint must cover the intended namespace. Independent shard-local uniqueness checks don’t establish a globally unique public code.

A collision doesn’t have to become an incorrect record. It can become a rejected candidate and another attempt, provided occupancy and retry costs remain acceptable.

Pre-generate keys without allocating them twice

If candidate generation or deduplication is expensive, we can do it ahead of requests. Requests then consume unused keys from a pool:

That moves work out of the request path, but introduces allocation state:

  • The generator deduplicates candidates before adding them to the pool.
  • Claiming a key is atomic, so two requests can’t consume it.
  • Claiming and associating the record can share a transaction when they share a database.
  • Separate allocation and association need a policy for abandoned claims.
  • Refilling must begin before the pool runs dry.
  • A key can’t return to the unused pool while an older request may still use it.

At 10^3 allocations per second, a reserve of 10^6 keys lasts 10^3 seconds—about seventeen minutes. That gives us a way to discuss the refill outage we can tolerate.

Size the pool separately from the lifetime namespace

Suppose we retain 10^10 identifiers but only need a thirty-minute refill buffer. At 10^3 peak allocations per second and roughly 2 × 10^3 seconds, the buffer needs about 2 × 10^6 unused keys.

Six bytes per code makes the characters alone about 12 MB. Actual storage adds entry metadata, allocation state, indexes, and possibly replicas.

The two-million-key reserve isn’t the lifetime namespace. Conversely, pre-generating every possible lifetime code can waste storage and complicate management.

Check what the ID does not promise

Before choosing a generator, finish these sentences precisely:

  • A unique ID doesn’t establish permission to access its record.
  • A time-ordered format doesn’t establish agreement between clocks.
  • A random-looking format isn’t necessarily unpredictable.
  • A truncated digest doesn’t retain the full digest’s collision resistance.
  • A sequence with gaps can still provide correct identities.

The first counter had a clear model: one allocator, one increasing value. Every alternative changes some part of that model. Keeping those changes explicit makes the trade-offs easier to choose.


Previous: Estimate Capacity, Find Bottlenecks, and Set Useful SLOs. Next: Storage from First Principles: Logs, Indexes, and Transactions.