System design interview: design a unique ID generator

A distributed unique ID generator hands out identifiers that never repeat, from many machines at once, without asking a central server for each one. The standard interview answer packs a timestamp, a worker number and a per-millisecond counter into a 64-bit integer, so IDs are unique, roughly sorted by time and fit in a database BIGINT; the follow-ups are about clocks that jump backwards and how workers get their numbers.

By Published 9 min read

1. Clarify the requirements

This prompt is short, so the requirements carry more weight than usual. Each property you agree on rules options in or out.

  • Functional: every call returns an ID that has never been returned before, anywhere in the system; IDs are numeric and fit in 64 bits; IDs created later are usually larger, so sorting by ID roughly sorts by creation time.
  • Non-functional: generate at least 1 million IDs a second across the fleet at peak (assumed); each call takes microseconds, so no network round trip per ID; keep working when any single machine or the coordination service is down.
  • Out of scope unless asked: strictly gap-free sequences (invoice numbers), IDs that must hide creation time or volume from outsiders.

2. Estimate the scale

Checking the bit budget against the requirements (assumed figures)
QuantityAssumptionResult
Peak demand1 million IDs a second across the fleetabout 1,000 per millisecond
Sequence bits12 bits per worker per millisecond4,096 IDs per ms, about 4 million a second per worker
Worker bits10 bits1,024 workers at once
Timestamp bits41 bits of milliseconds from a custom epoch2^41 ms is about 69.7 years
Total41 + 10 + 12 = 63 bits used, top bit stays 0always a positive signed 64-bit integer
Checking the bit budget against the requirements (assumed figures). Scroll sideways on a small screen.

One worker could meet the whole peak on paper, so throughput is not the constraint. Workers exist for availability and locality: each app server or each region generates its own IDs with no network hop. The bit budget is a negotiation; a fleet with more machines can move bits from the sequence to the worker field.

3. Define the API

next_id()            -> 64-bit integer, e.g. 122041606520975360
next_ids(count)      -> list of integers (batching for bulk inserts)
parse(id)            -> { timestamp_ms, worker_id, sequence }   for debugging
Usually a library inside each service; a network service is the fallback for languages without one.

4. The options, side by side

Five ways to produce unique IDs
ApproachHow it worksStrengthsWeaknesses
Database auto-incrementOne database's sequenceSimple, dense, orderedA single write bottleneck and failure point; does not scale across shards
Multiple databases with stepServer k of n hands out k, k+n, k+2n...No single pointAdding servers changes the step; IDs only loosely ordered across servers
Ticket server with rangesA central counter hands each app server a block (say 10,000 IDs)One call per block; dense IDsThe block service must be highly available; IDs are ordered within a server, not globally
UUID (random, 128-bit)122 random bits per IDNo coordination at allTwice the size; random values scatter inserts across a B-tree index; not sortable
Timestamp + worker + sequence (64-bit)Bits packed as in the table aboveLocal, fast, roughly time-ordered, fits BIGINTDepends on clocks; needs worker IDs assigned without duplicates
Five ways to produce unique IDs. Scroll sideways on a small screen.

Time-ordered 128-bit UUIDs (version 7, standardized in RFC 9562) are a reasonable modern middle ground when 128 bits are acceptable: they start with a millisecond timestamp and fill the rest with random bits, so they sort by time and need no worker IDs. Mention them if storage size is not a concern.

5. The core decision: the 64-bit layout and its edge cases

This layout is often called Snowflake-style after the generator Twitter described publicly. The interview is not about the bit diagram, which most candidates can draw; it is about what the generator does when the assumptions behind it break.

import threading, time

EPOCH_MS = 1_767_225_600_000  # 2026-01-01T00:00:00Z, chosen by us
WORKER_BITS, SEQ_BITS = 10, 12
MAX_SEQ = (1 << SEQ_BITS) - 1

class IdGenerator:
    def __init__(self, worker_id, now_ms=lambda: time.time_ns() // 1_000_000):
        if not 0 <= worker_id < (1 << WORKER_BITS):
            raise ValueError("worker_id out of range")
        self.worker_id, self.now_ms = worker_id, now_ms
        self.last_ms, self.seq = -1, 0
        self.lock = threading.Lock()

    def next_id(self):
        with self.lock:
            ms = self.now_ms()
            if ms < self.last_ms:
                if self.last_ms - ms > 5:
                    raise RuntimeError("clock moved back too far")
                ms = self._wait_until(self.last_ms)  # small step back: wait it out
            if ms == self.last_ms:
                self.seq = (self.seq + 1) & MAX_SEQ
                if self.seq == 0:  # 4,096 IDs used this millisecond
                    ms = self._wait_until(self.last_ms + 1)
            else:
                self.seq = 0
            self.last_ms = ms
            return ((ms - EPOCH_MS) << (WORKER_BITS + SEQ_BITS)) | (self.worker_id << SEQ_BITS) | self.seq

    def _wait_until(self, target):
        ms = self.now_ms()
        while ms < target:
            ms = self.now_ms()
        return ms
A thread-safe generator (tested: rollover within one millisecond, clock steps back, 200 random jittery clocks)
const EPOCH_MS = 1767225600000n; // 2026-01-01T00:00:00Z, chosen by us
const WORKER_BITS = 10n, SEQ_BITS = 12n;
const MAX_SEQ = (1n << SEQ_BITS) - 1n;

class IdGenerator {
  constructor(workerId, nowMs = () => BigInt(Date.now())) {
    if (workerId < 0 || workerId >= 1 << Number(WORKER_BITS)) throw new RangeError("workerId out of range");
    this.workerId = BigInt(workerId);
    this.nowMs = nowMs;
    this.lastMs = -1n;
    this.seq = 0n;
  }

  nextId() {
    let ms = this.nowMs();
    if (ms < this.lastMs) {
      if (this.lastMs - ms > 5n) throw new Error("clock moved back too far");
      ms = this.waitUntil(this.lastMs); // small step back: wait it out
    }
    if (ms === this.lastMs) {
      this.seq = (this.seq + 1n) & MAX_SEQ;
      if (this.seq === 0n) ms = this.waitUntil(this.lastMs + 1n); // 4,096 used this ms
    } else {
      this.seq = 0n;
    }
    this.lastMs = ms;
    return ((ms - EPOCH_MS) << (WORKER_BITS + SEQ_BITS)) | (this.workerId << SEQ_BITS) | this.seq;
  }

  waitUntil(target) {
    let ms = this.nowMs();
    while (ms < target) ms = this.nowMs();
    return ms;
  }
}
The same generator in JavaScript. IDs are BigInt because a Number loses precision above 2^53 (tested with node).
  • Sequence overflow. When a worker hands out 4,096 IDs inside one millisecond, it waits for the next millisecond instead of wrapping into a duplicate.
  • Clock rollback. NTP corrections and VM migrations can move the clock back. A step of a few milliseconds is waited out; a larger one makes the generator refuse (and alert) rather than risk duplicates. Persisting the last timestamp lets a restarted process detect a rollback across restarts too.
  • JavaScript and JSON. A 63-bit ID does not survive a round trip through a double. Send IDs to browsers as strings.
  • Custom epoch. Counting from a recent date instead of 1970 spends the 41 bits on the future; choose it once and never change it.

6. The architecture

  1. Callers
    • Services with the generator library
    • Fallback ID service for other languages
  2. Local
    • Generator: timestamp + worker + sequence
    • Local clock (NTP-disciplined)
  3. Coordination
    • Worker ID lease service
    • Consensus store
  4. Ops
    • Clock offset monitoring
    • Alert on refusals and lease conflicts
Worker IDs leased from a coordination service; IDs generated locally. Each application process embeds the ID generator library. At startup it asks a coordination service backed by a consensus store for a worker ID lease, renews the lease while running and gives it up on shutdown. The generator reads the local clock, which is disciplined by NTP, and returns IDs without any network call. Monitoring watches clock offset and the rate of refusals. Services without the library call a small ID service that runs the same generator.
  1. Get a worker IDOn startup, take a free number from 0 to 1023 with a lease (say 30 seconds) in the coordination service, and renew it every few seconds.
  2. GenerateEvery next_id call is local: read the clock, bump the sequence, pack the bits.
  3. Lose the leaseStop generating before the lease could expire, for example once a third of the lease has passed without a successful renewal. After expiry another process may hold that number, and two holders would produce duplicates.
  4. Shut downRelease the lease so the number can be reused. The service hands a released or expired number out again only after a quiet period longer than the clock skew you tolerate, so a new holder whose clock runs slightly behind cannot repeat a timestamp the old holder already used.

7. Scale it

  • Split the worker field. With several regions, use a few bits for the region and the rest for the machine, so each region leases numbers independently and a region outage does not block others.
  • Batch when needed. A bulk import can ask for thousands of IDs at once; the generator fills them from consecutive sequence values and milliseconds.
  • Watch the time budget. At the assumed peak of about 1,000 IDs per millisecond spread over many workers, each worker uses a tiny part of its 4,096. If one worker gets hot, it will wait for the next millisecond, which caps its rate without errors.
  • Mind the index. Time-ordered IDs append to the right edge of a B-tree, which is efficient for inserts. In stores that range-partition by key, that same property sends every new row to one partition, so hash the ID for placement there (see sharding).

8. What breaks, and what you do about it

Failure modes worth naming
FailureEffectMitigation
Clock jumps back by secondsPossible duplicate IDsRefuse to generate until the clock passes the last timestamp; alert; take the host out of rotation
Two processes with the same worker IDDuplicates in the same millisecondLeases with fencing: stop generating when the lease cannot be renewed
Coordination service downNew processes cannot get a worker IDRunning processes keep their leases until expiry; long leases and a spare pool of numbers buy time
Clock skew between machinesIDs from different machines out of order by a few msAccept: ordering is approximate across workers; never use IDs for exact event order
Running out of timestamp bitsOverflow decades from nowChoose a recent epoch; document the date; 41 timestamp bits buy about 69 years
Failure modes worth naming. Scroll sideways on a small screen.

9. Trade-offs to discuss

  • 64-bit or 128-bit. 64-bit IDs are smaller in every index and foreign key; 128-bit time-ordered UUIDs remove worker coordination entirely.
  • Leaking information. Time-based IDs reveal when something was created and, with the sequence, a rough rate. If that matters, expose a separate random public ID or encrypt the internal one.
  • Central ranges or local generation. Ticket servers give dense, nearly sequential numbers and need a highly available central component; local generation needs good clocks and worker leases.
  • Strict or approximate order. No scheme here gives a strict global order across machines without a central sequencer. If the product truly needs that, it pays for a single ordered log.

10. How to talk through it in the interview

Fictional example

When the interviewer attacks the clock
Interviewer
NTP just moved this host's clock back two seconds. What does your generator do?
Candidate
It remembers the last millisecond it used. Two seconds back is beyond the small window I wait out, so it refuses to issue IDs and raises an alert, and the load balancer drains the host. Issuing IDs with an old timestamp could repeat a value this worker already produced.
Interviewer
Isn't refusing worse than a duplicate?
Candidate
For primary keys, a duplicate is a correctness bug that might surface weeks later; a refusal is a visible, short outage on one host that the fleet absorbs.

Because the design is small, 45 minutes leaves room for depth: about 5 minutes on requirements and why ordering matters, 5 on the bit budget arithmetic, 10 comparing the five approaches, 15 on the 64-bit generator's edge cases (overflow, rollback, leases), and 10 on deployment, failures and trade-offs. Many interviewers fold this into a larger prompt, such as the post IDs in a news feed or codes in a URL shortener.

  • Show the bit arithmetic: 2^41 milliseconds is about 69 years.
  • Raise clock rollback before you are asked.
  • Explain how a worker ID is assigned and what stops two processes sharing it.

Practicing this design with Natively

A short prompt like this is good for repeated drills. Run it a few times on a call with a friend acting as interviewer: Natively records the conversation as text and can suggest talking points as each question is asked, so you can see afterwards whether you covered leases and clock rollback or stopped at the bit diagram. If you write the generator in an editor during practice, a screenshot of the code can be captured and explained. Notes and the transcript are kept to compare one attempt with the next.

Questions people ask

How do you generate unique IDs in a distributed system?

The common interview answer packs a millisecond timestamp, a worker ID and a per-millisecond sequence into a 64-bit integer, generated locally on each machine. Alternatives are database sequences, ticket servers that hand out ranges, and UUIDs. Pick based on whether IDs must be 64-bit and sortable by time.

How long does a 41-bit millisecond timestamp last?

2^41 milliseconds is about 69.7 years. Counting from a recent custom epoch instead of 1970 spends those years on the future. With 10 worker bits and 12 sequence bits, the whole ID fits in 63 bits, so it is a positive signed 64-bit integer.

What happens if the clock moves backwards in an ID generator?

The generator remembers the last millisecond it used. For a step of a few milliseconds it can wait until the clock catches up; for a larger step it should refuse to issue IDs and alert, because an old timestamp could repeat an ID already produced.

Why not just use UUIDs as IDs?

Random UUIDs need no coordination but take 128 bits, and their randomness scatters inserts across a B-tree index and makes them unsortable by time. Time-ordered UUIDs (version 7) fix the ordering. If 128 bits are acceptable, they are a simple choice.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP