Interview: orders go to 16 shards in 2 regions, what should the order id be?

Central counter, shard bits, random UUID and time+shard+sequence ids. Clock skew and rewind guards, Lamport and hybrid clocks, and how the id picks the…

More on Ticket interviews

Keep learning

Overview

One auto-increment DB becomes 16 shards in 2 regions. Pick an order id: unique, no central call, newest-first, clock-safe. Why can’t every shard just run its own auto-increment? explain simply Every shard starts at 1, so ids collide as soon as data meets. Fix A: odd/even or shard bits. Unique and small, but order is lost. Fix B: each shard takes a block (1–1,000, 1,001–2,000). Still no order. Fix C: one central counter. Ordered, but slow, a bottleneck, and fragile. names the collision each fix loses something central counter has a price Shard bits Unique · small · no order Few central calls · no order Central counter Ordered · single point of failure A time-based id generator’s clock jumps back 2 seconds. What breaks? what breaks if New ids sort before old ones, and some ids can repeat. Clocks jump back from NTP resets, leap seconds, or paused VMs. Monotonic clocks are for durations only. Monitor clock offsets. duplicates, not just disorder remembers last time monotonic is for durations How many ids can a 64-bit time-based id make? Do the maths. Layout: 41 bits ms (~69 years), 10 bits shard (1,024), 12 bits sequence. A random UUID is 128 bits, so every index on the id doubles. does the arithmetic compares to need mentions key size Product wants “if order A happened before order B, then id A < id B”, even across services. Is a time-ordered id enough? what would you do instead No. Clock skew means time-based ids are only roughly ordered. Lamport clock (counter + node id) keeps cause before effect, not real time. Hybrid logical clock: real time that never goes backwards (CockroachDB). Strict real-time order needs one oracle (TiDB) or waiting out uncertainty (Spanner). skew breaks time ids Lamport and hybrid clocks linearizable needs one point or waiting We use time-ordered ids and shard by range of id. What happens? All new orders hit the last range: one hot shard, the rest idle. Cost: a time-range scan must ask every shard. spots the hot shard hash the id names the scan cost Shard by id range Every new id is the biggest → last shard takes 100%. Shard by hash of id Staff: a shard is restored from last night’s backup. Its counter went backwards. How do you avoid duplicate ids? Persist a high-water mark before handing out ids, and restart above it. Write “may issue up to N”, hand out ids to N, then reserve the next batch. Ids are names, not counts. Say so before anyone reports on gaps. skip is safe, reuse is not ids are names Save “up to 2,000” Issue 1,001…2,000 Crash / restore Restart at 2,001 gap, no repeat The need Unique, no central call, roughly ordered, clock-safe. The choice 64-bit time + shard + sequence. Not random UUID. The guard The sharding The honest limit Roughly ordered. Strict order needs a logical clock or oracle. A timestamp alone as the id Skew can reorder. Not for money or permissions. Range-sharding a time id All new rows hit one shard. Hash it. Ignoring clocks Drift fails silently. Monitor offsets. Random vs time vs central: size, order, coordination Time ids are only roughly ordered Guard against clock going backwards Lamport, hybrid clock or oracle for strict order A clock shows 100, 101, 102 ms and is then reset back to 99. The next id gets time 99, which sorts before ids already issued, and may repeat one. sync resets the clock New ids sort before old ones, and the second 100 can repeat an id. The guard keeps “last time used” and refuses to go below it. Illustrative millisecond values. 41 bits · time in ms 10 bits 12 bits A 64-bit id split into 1 spare bit, 41 bits of time, 10 bits of shard and 12 bits of sequence. A 128-bit random UUID is twice as long. 64-bit time-ordered id (classic layout, illustrative) 128-bit random UUID 128 bits · random, so no order 41 bits of milliseconds ≈ 69 years (1, Aaliyah) (1, Caleb) (2, Bryce) A Lamport stamp is (counter, node). Compare the counter first, then the node name. Bryce saw both messages, so his stamp is bigger. One central counter Shard number + local counter Random UUID Time + shard + sequence Perfect order: one node numbers everything. But every insert must reach it, and it can fail. Yes, every insert 8 bytes Unique and small, no central call. But shards count at different speeds, so order is wrong. Unique with no coordination, but no order at all. Also twice as big. 16 bytes Mostly in order. Move the slider: if B’s clock is off by more than the gap between orders, they swap. 12 orders arrive from 3 shards. Each gets an id. Then we sort by id. Id scheme Clock error of shard B in milliseconds what really happened, oldest first ORDER BY id, as “oldest first” would show it ✓ right place ✕ wrong place Orders in the wrong place Central call per insert Id size What to notice. No scheme is best on all three rows. Only the central counter orders perfectly, and it is the only one that must be called every time. Even across shards, but scattered across each index. See the index-cost chapter. Every new id is the biggest, so all go to the last range. One shard is hot. Where do today’s new rows land? Kind of id random id How rows are sharded shard by id range shard by hash of id SHARE OF NEW ROWS PER SHARD INDEX PAGES TOUCHED IN ONE SHARD the newest pages only: easy to keep in memory pages all over: many cold pages to load normal share of writes hot shard index page touched What to notice. The id decides two things at once: which shard gets the write, and how the index inside that shard grows. One roll in order, but everyone queues at one booth A roll per booth booths clash on the same number Pull from a hat no clash, but no order Time + booth + count unique, and roughly in order Four kinds of raffle ticket: one shared roll, a roll per booth that clashes, numbers from a hat with no order, and time plus booth plus count that is unique and roughly in order.

Orders now go to 16 shards in 2 regions. What should the order id be?

Auto-increment breaks across shards. Every id choice trades order, size, coordination and clock trust. UUID v4 vs v7 clock skew Lamport and hybrid clocks Auto-increment ids collide once orders span 16 shards. Time + shard + sequence id, clock guard, hash-sharded.

Raffle tickets at a busy fair

Many booths, one rule: every ticket number must be unique. Four ways to do it.

Choose the order id before we shard the orders table.

Today: one database, auto-increment ids. Next: 16 shards across two regions. Id must be unique, need no central call, page newest-first, survive bad clocks.

Four ways to make an id

No central call Time order Small (64-bit) Central counter Shard + local counter Random UUID v4 Time + shard + seq One region, moderate rate, strict order. Shard + counter UUID v4 Client-made ids, small tables. Most big tables. 16 shards, 2 regions, newest-first paging. Which order id do you pick? A central auto-increment service Perfect order, small ids. But the far region pays a trip per insert, and it can fail. Good order Safe if a clock is wrong Easiest to make. No newest-first paging, double size, scattered index writes. Time + shard + sequence, with a clock guard, sharded by hash of id

Say these out loud first

Related chapters: index cost (the random UUID point), shard split, page hotspot.

A model answer

We are sharding orders. What do you use for the id?

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.