# Unique ID generator - 64 bits, and two facts nobody can check

> How 64 bits buy sortable ids with no central counter, and what happens when the clock goes backwards. The id is unique only because worker 17 exists exactly…

Source: https://tierslate.com/templates/unique-id-generator

Infrastructure primitives · System design · starter · 8 step walkthrough · 4 tables

How 64 bits buy sortable ids with no central counter, and what happens when the clock goes backwards.

**Own this board: 200 credits.** The first act plays on the page. Owned once with credits, never a subscription.

## What this board gets wrong on purpose

The tension: The id is unique only because worker 17 exists exactly once and its clock never moves backwards, and the generator can verify neither. The lease makes the first true only while the registry is reachable, so a worker that keeps generating through a lease expiry - exactly what a network partition produces - mints duplicate primary keys that nothing detects until a UNIQUE constraint fails weeks later on a row nobody is looking at. The clock guard makes the second true by REFUSING TO GENERATE, so a 200 ms NTP correction becomes 200 ms in which every write on the service fails. And because the ids are sortable they are also readable: two ids taken an hour apart tell a competitor exactly how many rows were created in between.

## Practise this as an interview

Take Unique ID generator - 64 bits, and two facts nobody can check as a timed system design interview on a blank board - on your own, with the requirements to check yourself against, or with a candidate you invite.

## Start here

### Why this design

Every sharded database needs primary keys that are unique without a central counter, and Twitter, Discord and Instagram each answered it with a 64-bit, time-ordered id (Snowflake and its descendants). Interviewers ask it because it looks like a throughput question and is not: one worker covers peak demand twenty-three times over. What it probes is bit budgeting, how clocks really behave under NTP, how a fleet guarantees a worker number exists exactly once, and why a sortable key matters to a B-tree.

### What you will learn

- How 64 bits are spent: 1 sign bit, 41 bits of milliseconds (69.7 years from a custom epoch), 5 + 5 bits of datacenter and worker (1,024 generators), 12 bits of sequence (4,096 ids per ms per worker).
- Why demand of 174,000 ids/s against a supply of 4.2 billion makes the design coordination bound, and why the real ceiling is 1,024 worker ids - and that the sequence bits are the ones to spend when it runs out.
- Why the worker id is a 30 s lease renewed every 10 s rather than a config value, and why a worker past its lease must stop generating instead of carrying on.
- What the clock guard does when NTP steps the clock backwards - wait out a few milliseconds, refuse beyond that - and what that costs in failed writes.
- Why a sortable bigint beats UUIDv4 at 5 billion ids a day: right-edge B-tree appends against ~97% random reads, and 365 TB against 1.6 PB of index over five years.
- When UUIDv4 or auto-increment is the better answer, and why a sortable id needs a separate opaque public token.

### How to read this board

1. Diagram, left to right: THE CALLER, then THE GENERATOR (the in-process library, the worker id registry and the custom epoch), then SIXTY-FOUR BITS, LAID OUT TO SCALE across the top - the box widths are the bit counts.
2. Below the bits: WHERE IT GOES WRONG · THE CLOCK, then WHAT IT IS FOR, then THE ALTERNATIVES along the bottom. Press play for the eight-step walkthrough.
3. Page 1 · Requirements - the questions that decide whether you need any of this, starting with "must the id sort by time?".
4. Pages 2 and 3 · Capacity and Storage estimation - demand against supply (0.004% utilised), and what an 8-byte sequential key saves in every index.
5. Page 4 · Availability - five nines because it is a library and not a service, and what degrades when the registry or the clock misbehaves.
6. Page 5 · How it works - the whole path in prose - then Page 6 · Deployment plan, including why the bit layout is a row and why there is no rollback for a duplicate.
7. The DATA MODEL at the bottom: bit layouts, worker leases, clock incidents and public tokens - under a megabyte, and the only part that can fail.
8. Then the conversation to have: the id is unique only while worker 17 exists once and its clock never runs backwards, and the generator can verify neither. A partitioned worker that keeps generating past its lease mints duplicates nothing detects.

## 1 · Requirements

### Ask these before drawing anything

- Must the id be sortable by creation time? This is the question that decides everything. If not, UUIDv4 is a better answer than anything on this board and the interview is over in one minute - which is a good answer, not a failure.
- Is the id ever shown to a user or put in a URL? Sortable ids are enumerable and they leak volume: two ids an hour apart tell anybody how many rows were created in between. If it is public, it needs a separate opaque external id.
- How many bits are available? 64 fits in a bigint and in a JavaScript BigInt but NOT in a JavaScript Number, which silently loses precision above 2^53 and is the most common production bug in this design.
- How many generating processes will there ever be? The worker id space is a hard ceiling. 1,024 sounds infinite until a fleet autoscales.
- Is the clock trustworthy, and who owns NTP? If nobody can answer this, the design has an unowned dependency at its centre.
- What should happen when an id cannot safely be generated - fail the write, or block? There is no third option, and the answer is an availability number.

### Functional

- Generate a 64-bit id that is unique across the entire fleet, forever.
- Ids increase monotonically with time, so that ordering by id orders by creation.
- Generation is in process: no network call, no service to be unavailable.
- A worker acquires its worker id automatically on start and releases it on stop.
- An id can be decoded back into its timestamp, datacenter and worker, for debugging.

### Non-functional

- p99 under 1 microsecond per id. This is arithmetic and a lock, not a request.
- Zero duplicates. Not "rare" duplicates - a duplicate here is a primary key collision discovered weeks later in a table nobody was watching.
- Survive the id registry being unavailable for the length of a lease without producing a duplicate. Note what this does NOT say: it does not say keep generating.
- Ids remain unique across a datacenter failover, a process restart within the same millisecond, and a clock correction.
- The scheme must last 69 years from its epoch, and the expiry date must be written down somewhere a human will find it.

### Out of scope

- Global ordering. Two ids generated in the same millisecond on two workers have no meaningful order between them, and any code that assumes one is wrong.
- Cryptographic unpredictability. These ids are guessable by construction. Anything needing unguessability needs a random token instead, alongside.
- Ids for entities that already have a natural key. The best id generator is the one you did not need.

## The rest of this board

This page publishes the question. The answer - 5 more written pages, an 8-step narrated walkthrough and a 4-table schema - is the board itself, and it opens in Tierslate.

- 5 written pages
- 8 walkthrough steps
- 4 tables (28 columns)

5 pages behind this one:

- Capacity estimation
- Storage estimation
- Availability
- How it works
- Deployment plan

## Related system design templates

- [URL shortener system design](https://tierslate.com/templates/url-shortener) - Why one tiny write and a hundred cacheable reads make two systems sharing a single table.
- [Distributed cache system design](https://tierslate.com/templates/distributed-cache) - Why a hash ring moves a sliver of keys when a node leaves, and why the hot key and the miss storm remain.
- [Key-value store system design](https://tierslate.com/templates/key-value-store) - How a key finds its replicas, and why choosing how many to wait for buys overlap rather than order.
- [Rate limiter system design](https://tierslate.com/templates/rate-limiter) - Why the hard part of limiting requests is where the shared counter lives, not the algorithm.
- [Web crawler system design](https://tierslate.com/templates/web-crawler) - Why a crawler that feeds on its own output needs politeness, deduplication and loop brakes more than speed.
- [Pastebin system design](https://tierslate.com/templates/pastebin) - Why storing text is the easy part and expiry, abuse and the read path are the design.
- [Load balancer system design](https://tierslate.com/templates/load-balancer) - How requests are spread across servers, and why the health check matters more than the algorithm.
- [API gateway system design](https://tierslate.com/templates/api-gateway) - Why auth, routing and limits move to one front door, and what that door costs when it falls over.
- [Login and sessions system design](https://tierslate.com/templates/login-sessions) - How a password becomes a session, and what changes when the session is a signed token nobody can revoke.
- [Feature flags system design](https://tierslate.com/templates/feature-flags) - Why a flag is evaluated locally from a pushed ruleset, and what a stale ruleset does during an incident.
- [Secrets manager system design](https://tierslate.com/templates/secrets-manager) - How secrets are encrypted under a key nobody holds directly, and why rotation is the feature, not storage.
- [DNS system design](https://tierslate.com/templates/dns-resolver) - How a name becomes an address through layers of caches, and why the TTL decides how fast a mistake spreads.
- [Distributed cron system design](https://tierslate.com/templates/cron-scheduler) - Why a scheduled job needs a lease so it runs once, not once per server, and what a missed tick should do.
- [Background job queue system design](https://tierslate.com/templates/job-queue) - Why a job queue delivers at least once, and how idempotent workers and dead letters keep retries honest.
- [Code execution sandbox system design](https://tierslate.com/templates/code-execution-sandbox) - How untrusted code is run in isolated, time-limited sandboxes, and why the queue in front of them is the real system.
- [Distributed log system design](https://tierslate.com/templates/message-queue) - Why an append-only partitioned log gives ordering and replay, and what replication and consumer offsets cost.
- [Consensus system design](https://tierslate.com/templates/raft-consensus) - How Raft keeps replicas agreeing through elections and a replicated log, and what a network partition really does.
- [Object storage system design](https://tierslate.com/templates/object-storage) - How objects are split, erasure-coded and placed across failure domains so losing disks never loses data.

All 100 system design templates: https://tierslate.com/templates (Markdown: https://tierslate.com/templates.md)
