Skip to content
Commitwise
Menu
System Design

Consistent hashing and unique IDs

Spread keys across servers so that adding or removing one moves only a small share of them, with a hash ring and virtual nodes, and generate unique, sortable IDs without a central database, comparing auto-increment, UUIDv4, UUIDv7 and Snowflake-style IDs, with code in Kotlin, Java, TypeScript and Swift.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A cache cluster has ten servers, and the app picks one with hash(key) % 10. Traffic grows, the team adds an eleventh server, and the database falls over: almost every key now maps to a different server, so nearly every cache lookup misses at the same moment. On another team, two services that each generated “unique” order numbers from the current time in milliseconds produced the same number twice in one busy second.

Both problems come up in almost every distributed system, and in many system design interviews: where does this key live? and how do I create an ID that nobody else will create? This lesson covers the standard answers: consistent hashing, and ID schemes that need no central coordinator.

New to some of these? Open what you need, or skip ahead.

Basics:What is a hash function?

A hash function turns any input (a user id, a URL) into a number, always the same number for the same input, and spread evenly for different inputs. hash("user-42") might be 2891336453. Hash maps use it to decide where to store a key; distributed systems use it to decide which server stores a key. See hash mapHash mapA key-value collection that finds a value by its key in constant time on average.Open in glossary →.

Basics:What is sharding?

Sharding splits data across several servers (shards), each holding part of it, because one server can’t hold or serve everything. A rule decides which shard owns each key. See shardingShardingSplitting one big database into several smaller ones, each holding part of the data.Open in glossary →.

Part Not started

Consistent hashing

With hash(key) % N, every key’s server depends on N, the number of servers. Change N from 10 to 11 and almost every key gets a new server: about 91% of them. For a cache, that means 91% misses at once; for a database, moving 91% of the data.

Consistent hashingConsistent hashingA way to assign keys to servers so that adding or removing a server moves only about 1/N of the keys.Open in glossary → fixes this with a circle, the hash ring:

  1. Hash every server to a point on the ring.
  2. Hash every key to a point on the ring.
  3. A key belongs to the first server clockwise from its point.

Add a new server, and it only takes the keys between itself and the previous server: about 1/N of the keys. Everything else stays where it was. Remove a server, and only its keys move, to the next server clockwise.

With few servers, their points can land unevenly, so one server gets a huge arc. The fix is virtual nodes: each server gets many points on the ring (say 100), which spreads load evenly. When a server fails, its keys are spread over many servers instead of all landing on one neighbor.

With modulo placement, going from N to N+1 servers keeps only the keys whose hash mod N equals their hash mod (N+1), about 1/(N+1) of them, so ~N/(N+1) move. Consistent hashing maps servers and keys onto the same hash space (a ring); ownership is the successor of the key’s position; membership changes move ~K/N keys. Virtual nodes (tens to hundreds per server) bound load imbalance and let heterogeneous servers take proportional numbers of points; lookups are O(log V) with a sorted structure. Replication stores a key on the next R distinct physical servers clockwise (Dynamo, Cassandra), which pairs naturally with quorums. Alternatives: rendezvous (HRW) hashing (each key picks the server with the highest hash(key, server): no ring, minimal movement, O(N) per lookup), jump consistent hash (tiny and perfectly balanced, but only for numbered buckets that grow or shrink at the end), and slot-based schemes like Redis Cluster’s 16,384 hash slots assigned to nodes, which make rebalancing explicit. None of them fix hot keys: a single very popular key still lands on one server and needs replication of that key, request coalescing or local caching.

class HashRing(nodes: Collection<String>, private val virtualNodes: Int = 100) {
    private val ring = TreeMap<Long, String>()                 // position on the ring → server

    init { nodes.forEach(::add) }

    fun add(node: String) = repeat(virtualNodes) { i -> ring[hash("$node#$i")] = node }
    fun remove(node: String) = repeat(virtualNodes) { i -> ring.remove(hash("$node#$i")) }

    fun nodeFor(key: String): String {
        val entry = ring.ceilingEntry(hash(key)) ?: ring.firstEntry()   // past the end: wrap around
        return entry.value
    }

    private fun hash(s: String): Long =
        ByteBuffer.wrap(MessageDigest.getInstance("SHA-256").digest(s.toByteArray())).long
}
class HashRing {
    private final TreeMap<Long, String> ring = new TreeMap<>();   // position on the ring → server
    private final int virtualNodes;

    HashRing(Collection<String> nodes, int virtualNodes) {
        this.virtualNodes = virtualNodes;
        nodes.forEach(this::add);
    }

    void add(String node) { for (int i = 0; i < virtualNodes; i++) ring.put(hash(node + "#" + i), node); }
    void remove(String node) { for (int i = 0; i < virtualNodes; i++) ring.remove(hash(node + "#" + i)); }

    String nodeFor(String key) {
        Map.Entry<Long, String> entry = ring.ceilingEntry(hash(key));
        return (entry != null ? entry : ring.firstEntry()).getValue();  // past the end: wrap around
    }

    private static long hash(String s) {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8));
            return ByteBuffer.wrap(digest).getLong();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }
}
function fnv1a(s: string): number {                            // a fast 32-bit hash
  let h = 0x811c9dc5;
  for (let i = 0; i < s.length; i++) {
    h ^= s.charCodeAt(i);
    h = Math.imul(h, 0x01000193) >>> 0;
  }
  return h;
}

class HashRing {
  private points: { hash: number; node: string }[] = [];       // sorted by hash

  constructor(nodes: string[], private readonly virtualNodes = 100) {
    nodes.forEach((n) => this.add(n));
  }

  add(node: string): void {
    for (let i = 0; i < this.virtualNodes; i++) this.points.push({ hash: fnv1a(`${node}#${i}`), node });
    this.points.sort((a, b) => a.hash - b.hash);
  }

  remove(node: string): void {
    this.points = this.points.filter((p) => p.node !== node);
  }

  nodeFor(key: string): string {
    const h = fnv1a(key);
    let lo = 0, hi = this.points.length;
    while (lo < hi) {                                          // first point with hash >= h
      const mid = (lo + hi) >> 1;
      if (this.points[mid].hash < h) lo = mid + 1; else hi = mid;
    }
    return this.points[lo % this.points.length].node;          // past the end: wrap around
  }
}
  • Each server is added 100 times, as cache-1#0, cache-1#1… , so its points are scattered around the ring.
  • nodeFor finds the first point at or after the key’s position (ceilingEntry, or a binary search); if there is none, it wraps around to the first point.
  • Adding a server only inserts its points: keys that now fall just before them move to it, and nothing else changes.

Predict the output

A cache cluster grows from 10 to 11 servers. Roughly what share of keys changes server with hash % N, and with a consistent hash ring?

Spot the bugPicking a server

Tap the line with the bug.

fun serverFor(key: String, servers: List<String>): String {
    val index = abs(key.hashCode()) % servers.size
    return servers[index]
}
String serverFor(String key, List<String> servers) {
    int index = Math.abs(key.hashCode()) % servers.size();
    return servers.get(index);
}
function serverFor(key: string, servers: string[]): string {
  const index = Math.abs(hashCode(key)) % servers.length;   // a Java-style 32-bit hash
  return servers[index];
}

Choosing a placement scheme

SchemeMovement on changeBalanceLookupTypical use
hash % N~N/(N+1) of keysEvenO(1)Fixed clusters that never change size
Ring + virtual nodes~1/NGood with 100+ vnodesO(log V)Memcached/Redis clients, Dynamo-style stores
Rendezvous (HRW)~1/NEvenO(N)Small clusters, CDN node selection
Jump hash~1/NPerfectO(log N)Numbered shards that grow at the end
Fixed slots (e.g. 16,384)Explicit slot movesOperator-controlledO(1)Redis Cluster, many databases

Membership must be agreed on (all clients must see the same ring), usually via a coordination service or gossip; clients with different views send the same key to different servers during changes, so caches tolerate it and databases use explicit rebalancing with ownership handoff.

  • Modulo remaps ~N/(N+1) keys on resize; a ring moves ~1/N. Ownership = successor on the ring.
  • Virtual nodes for balance, proportional capacity, and spreading a failed node’s load; O(log V) lookup.
  • Replicas on the next R distinct physical nodes; quorums.
  • Alternatives: rendezvous hashing, jump hash, fixed slots (Redis Cluster 16,384). Consistent membership views matter.
  • Hot keys remain hot: replicate the key, coalesce requests, cache locally. Beware abs(Int.MIN_VALUE).

Check this part

  1. On a hash ring, which server owns a key?

  2. Why give each server many virtual nodes?

  3. What does consistent hashing not solve?

  4. What is Math.abs(Integer.MIN_VALUE) in Java?

hash(key) % N remaps almost every key when N changes. Consistent hashing places servers and keys on a ring; a key belongs to the next server clockwise, so adding or removing a server moves only about 1/N of the keys. Virtual nodes (many points per server) even out the load and spread a failed server's keys over many others. Hot keys still need separate handling.

Part Not started

Unique IDs without a central database

In a single database, AUTO_INCREMENT (or a sequence) gives 1, 2, 3… and never repeats. With many servers, or apps creating records offline, one counter becomes a bottleneck and a single point of failure. So distributed systems use IDs that each machine can create on its own.

The common options:

  • UUIDv4: 128 random bits, like 7f3c9a2e-…. Any device can create one, collisions are practically impossible, and they’re unguessable. But they’re random, so new rows land all over a database index, which slows inserts on big tables.
  • UUIDv7: also 128 bits, but the first part is the current time. Still created anywhere, and new IDs sort after older ones, so they’re friendly to database indexes.
  • Snowflake IDsSnowflake IDA 64-bit, time-sortable ID built from a timestamp, a worker number and a per-millisecond sequence.Open in glossary →: 64-bit numbers made of a timestamp, a machine number and a counter. Compact, sortable by time, and each machine can make thousands per millisecond. Twitter invented them; Discord and Instagram use variants.

Ask two questions before choosing: must IDs be sortable by time? and is it OK to expose them (a sequential id like /orders/1042 tells competitors how many orders you have, and invites guessing other users’ ids)?

Requirements decide: global uniqueness without coordination, time ordering (feeds, logs, index locality), size (64-bit keys are cheaper in every index and join), generation on clients (offline mobile), and exposure (enumeration and business-volume leaks). Sequences are simple and compact but centralized (partition with ranges or step offsets) and enumerable. UUIDv4 is coordination-free and unguessable but random inserts fragment B-tree indexes and hurt cache locality at scale. UUIDv7 (RFC 9562) puts a 48-bit Unix millisecond timestamp first, giving near-sequential inserts and global uniqueness; it reveals creation time. Snowflake-style IDs (41-bit ms timestamp from a custom epoch ≈ 69 years, 10-bit worker id, 12-bit sequence ≈ 4,096 IDs/ms/worker) are 64-bit and k-sorted, but require unique worker ids (assigned via configuration, a lease table or a coordinator, not hostname hashes) and protection against clock rollback (refuse or wait, never reuse timestamps). For public URLs, consider a separate opaque identifier (random or encoded) even if internal keys are sequential.

class SnowflakeIds(
    private val workerId: Long,                                 // 0..1023, unique per running instance
    private val clock: () -> Long = System::currentTimeMillis,
) {
    init { require(workerId in 0..1023) { "workerId must fit in 10 bits" } }

    private var lastMillis = -1L
    private var sequence = 0L

    @Synchronized
    fun next(): Long {
        var now = clock() - EPOCH
        check(now >= lastMillis) { "Clock moved backwards by ${lastMillis - now} ms; refusing to create IDs" }
        if (now == lastMillis) {
            sequence = (sequence + 1) and 0xFFF                 // 12 bits: 4,096 IDs per millisecond
            if (sequence == 0L) {
                while (now <= lastMillis) now = clock() - EPOCH  // used them all: wait for the next ms
            }
        } else {
            sequence = 0
        }
        lastMillis = now
        return (now shl 22) or (workerId shl 12) or sequence    // 41 bits time | 10 bits worker | 12 bits seq
    }

    companion object {
        const val EPOCH = 1_735_689_600_000L                    // 2025-01-01T00:00:00Z: ~69 years of IDs
    }
}
final class SnowflakeIds {
    private static final long EPOCH = 1_735_689_600_000L;      // 2025-01-01T00:00:00Z: ~69 years of IDs
    private final long workerId;                               // 0..1023, unique per running instance
    private long lastMillis = -1L;
    private long sequence = 0L;

    SnowflakeIds(long workerId) {
        if (workerId < 0 || workerId > 1023) throw new IllegalArgumentException("workerId must fit in 10 bits");
        this.workerId = workerId;
    }

    synchronized long next() {
        long now = System.currentTimeMillis() - EPOCH;
        if (now < lastMillis) {
            throw new IllegalStateException("Clock moved backwards by " + (lastMillis - now) + " ms");
        }
        if (now == lastMillis) {
            sequence = (sequence + 1) & 0xFFF;                 // 12 bits: 4,096 IDs per millisecond
            if (sequence == 0) {
                while (now <= lastMillis) now = System.currentTimeMillis() - EPOCH;   // wait for the next ms
            }
        } else {
            sequence = 0;
        }
        lastMillis = now;
        return (now << 22) | (workerId << 12) | sequence;      // 41 bits time | 10 bits worker | 12 bits seq
    }
}
  • An ID is built from three parts packed into one 64-bit number: milliseconds since 2025, the worker id of this server, and a sequence that counts IDs within the same millisecond.
  • Two servers can never produce the same ID, because their worker ids differ; one server can’t either, because within a millisecond the sequence counts up.
  • If a server asks for more than 4,096 IDs in one millisecond, it waits for the next millisecond.
  • If the clock goes backwards (a time sync correction), it refuses instead of risking a duplicate.
  • Sorting IDs sorts them by creation time, so “newest first” is just order by id desc.

TypeScript note

JavaScript numbers are exact only up to 2⁵³, so a 64-bit Snowflake ID must be a bigint in TypeScript and a string in JSON: JSON.parse would silently round 1987654321098765432 to a different number. APIs that serve web or JavaScript clients usually send 64-bit IDs as strings for exactly this reason.

Swift note

Swift’s UUID() creates a random UUIDv4. For time-ordered IDs created on the device (offline-first apps), use a small UUIDv7 implementation or let the server assign IDs and keep a local temporary id until sync.

Predict the output

A team uses UUIDv4 as the primary key of a PostgreSQL table receiving 5,000 inserts per second, with 2 billion rows. Inserts get slower over months and the index uses far more memory than expected. Switching to UUIDv7 helps. Why?

Production puzzles

Spot the bugWorker ids from host names

Tap the line with the bug.

val workerId = (InetAddress.getLocalHost().hostName.hashCode() and 0x3FF).toLong()
val ids = SnowflakeIds(workerId)
long workerId = InetAddress.getLocalHost().getHostName().hashCode() & 0x3FF;
SnowflakeIds ids = new SnowflakeIds(workerId);

Exercisehard

IDs for an offline-first notes app

A notes app creates notes offline on phones and syncs later. Notes must be referenced by id across devices immediately (links between notes), sort by creation time, and appear in shareable URLs. Choose the ID scheme and explain the trade-offs.

›

Who creates the ID, and can a central counter be reached at that moment?

SolutionTry it yourself first
  • Client-generated UUIDv7: created on the device with no network, globally unique without coordination, sortable by creation time, and index-friendly on the server. Links between notes work offline because the id is final from the start.
  • Trade-offs: 128 bits instead of 64 (acceptable); the id reveals creation time (usually fine for notes); device clocks can be wrong, so “sort by creation” should use a server-confirmed timestamp for display when it matters, while the id only needs to be unique.
  • Sharing: use a separate random share token in URLs (revocable, not tied to the note’s id), so sharing can be turned off without changing ids.
  • Not Snowflake: devices can’t be assigned unique worker ids reliably, and 64-bit precision is awkward in JavaScript clients.
SizeCoordinationTime-orderedExposure
Sequence64-bitCentral (ranges/steps to scale)YesEnumerable, leaks volume
UUIDv4128-bitNoneNo (index fragmentation)Unguessable
UUIDv7128-bitNoneYes (48-bit ms prefix)Reveals creation time
Snowflake64-bitUnique worker idsYes (k-sorted)Reveals time, roughly volume
  • Snowflake: 41-bit ms (custom epoch, ~69 years), 10-bit worker, 12-bit sequence; refuse on clock rollback; lease worker ids, never hash host names.
  • 64-bit IDs as strings for JavaScript clients; separate opaque tokens for public URLs.

Check this part

  1. Why are random UUIDv4 primary keys slow on very large tables?

  2. What makes two servers' Snowflake IDs different?

  3. What should a Snowflake generator do when the clock moves backwards?

  4. Why send 64-bit IDs as strings in JSON APIs?

Choose IDs by requirements: unique without coordination, sortable by time, compact, safe to expose. Auto-increment is simple but centralized and guessable; UUIDv4 is random and fragments indexes; UUIDv7 is time-ordered and index-friendly; Snowflake-style 64-bit IDs (timestamp, worker id, sequence) are compact and sortable but need unique worker ids and a clock that never goes backwards.

Key takeaways

  • hash % N reshuffles almost every key when servers change; a hash ring moves only about 1/N.
  • Virtual nodes spread keys evenly and share a failed server’s load.
  • Pick IDs by need: UUIDv4 for unguessable, UUIDv7 or Snowflake for time-ordered.
  • Don’t expose sequential IDs in public URLs.
  • Know the placement schemes (ring, rendezvous, jump hash, slots) and their trade-offs; hot keys need their own fix.
  • Membership views must agree; databases rebalance explicitly.
  • Time-ordered IDs keep indexes healthy; Snowflake needs leased worker ids and clock-rollback protection.
  • Mind client precision (2^53) and use opaque public identifiers.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.