Quick revision
The short answer
We hash the customer id with a stable, well-distributed function such as Murmur3, take Math.floorMod(hash, 1024) to get a bucket that is never negative, and look the bucket up in an immutable int[1024] that maps buckets to shards. The map sits behind an AtomicReference, so a reload builds a complete new array and swaps it in one step, and readers never see a half-updated map. The chosen shard goes into a request-scoped context that an AbstractRoutingDataSource reads for the whole transaction, and a map version lets moving buckets be blocked.
What to remember
In this answer, we wrote the core of a two-level shard router. The customer id is hashed with Murmur3 (Guava's murmur3_32_fixed) because it is stable and spreads similar ids, and Math.floorMod maps the signed hash into [0, 1024) where % and Math.abs fail. The bucket-to-shard map is an immutable array behind an AtomicReference, replaced as a whole snapshot with a version check. The chosen shard goes into a context read by AbstractRoutingDataSource, set before the transaction begins and cleared afterwards, and a MOVING marker with map versions keeps bucket moves safe.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We hash the customer id with a stable, well-distributed function such as Murmur3, take Math.floorMod(hash, 1024) to get a bucket that is never negative, and look the bucket up in an immutable int[1024] that maps buckets to shards. The map sits behind an AtomicReference, so a reload builds a complete new array and swaps it in one step, and readers never see a half-updated map. The chosen shard goes into a request-scoped context that an AbstractRoutingDataSource reads for the whole transaction, and a map version lets moving buckets be blocked.
Why this question is asked
Application-level sharding puts a small piece of code on the path of every database call, so that piece must be correct, fast and safe under concurrency. The two-level design here, keys to 1,024 fixed buckets and buckets to 8 shards, is popular because it lets data move later without rehashing every key. Interviewers ask for the code because each line hides a decision: which hash, how to deal with negative numbers, how to swap the map while requests are running and how to make Spring use the right DataSource. In this answer, we will recap the design, write the bucket function and see the negative-number bug, write the router with a safe swap, connect it to Spring, and add versioning for moves.
1A Quick Recap of the Two-Level Design
With plain hash(id) mod 8, adding a ninth shard changes the result for almost every key, so almost all data would have to move. The two-level design avoids that. First, every customer id is hashed into one of 1,024 logical buckets, and that number never changes for the life of the system. Second, a small table maps each bucket to one of the 8 physical PostgreSQL shards. To add a shard, we move some buckets to it and update the table; keys stay in the same buckets, and only the moved buckets' data is copied.
- Customer id"cust-48213"
- Stable hashMurmur3 32-bit over the UTF-8 bytes
- Bucket
floorMod(hash, 1024), fixed forever - Bucket mapint[1024] -> shard number, can change
- DataSource
AbstractRoutingDataSourcepicks the shard pool
5 layers, from the top down. Step through them one at a time.
2Choosing the Hash Function
The hash must give the same number for the same id in every process, every JVM version and every language that might route requests, now and in ten years, because a change would send every key to a different bucket. It must also spread similar ids evenly. String.hashCode() is specified by Java and therefore stable, but it is a simple polynomial: ids like cust-00001 and cust-00002 produce hash codes that differ by 1, and their low bits follow a pattern, so buckets fill unevenly. Object.hashCode() of other types can differ between runs and must never be used.
Murmur3 is a good choice: fast, well distributed and implemented identically in many languages. In Guava, Hashing.murmur3_32_fixed() is the correct variant; the older murmur3_32() had a bug with some non-BMP characters, which is exactly the kind of difference that would split routing between two services.
3Handling Negative Hashes: % Versus floorMod
A 32-bit hash is a signed int, so about half of all hashes are negative. Java's % operator keeps the sign of the left operand, so a negative hash gives a negative bucket, and indexing the array with it throws. A common half-fix, Math.abs(hash) % 1024, still fails for one value: Math.abs(Integer.MIN_VALUE) is Integer.MIN_VALUE, which is still negative.
Math.floorMod always returns a value with the sign of the divisor, so with a positive bucket count the result is always in [0, 1024). Because 1,024 is a power of two, hash & 1023 gives the same result, but floorMod states the intent clearly and works for any bucket count.
4The Router: An Immutable Map Behind an AtomicReference
The bucket map is read on every request and replaced rarely, when an operator or a rebalancer moves buckets. The safe pattern for that is copy-on-write: the map is an immutable snapshot, and a reload builds a complete new snapshot and swaps the reference in one atomic step. A reader takes the reference once at the start of a lookup and uses that snapshot throughout, so it can never see half of an old map and half of a new one, and reads need no locks.
Notice the defensive clone(): if we stored the caller's array, the caller could change it after the swap and break immutability. The version check in replace() stops an older map that arrives late from a slow config poll from replacing a newer one.
5Connecting the Router to Spring
Spring's AbstractRoutingDataSource is a DataSource that holds a map of target DataSources, one connection pool per shard, and asks determineCurrentLookupKey() which one to use each time a connection is requested. We store the chosen shard in a request-scoped context and return it from that method.
But there is a catch: the transaction manager takes a connection when the transaction begins and keeps it until commit. So the shard must be set before the @Transactional method is entered and must not change inside it; switching the context halfway does nothing, or worse, mixes shards in one logical operation. Clearing it in finally matters because servlet threads are reused, and a leftover value would send the next request to the wrong shard. Logging the bucket, shard and map version on errors makes routing problems visible instead of mysterious.
6Versioning the Map for Bucket Moves
When a bucket is moved from shard 3 to shard 7, there is a short window where writes must not go to either: the old shard is being fenced and the new one is catching up. The map marks such a bucket as MOVING, and route() throws a retryable BucketMovingException, which the API layer turns into a short retry or a 503 with Retry-After. After the move, a new map with a higher version points the bucket at shard 7. The shards can also store which buckets they own with the version that granted them, so a router holding an old map gets an error from the shard instead of writing to the wrong place.
7Follow-up questions
Why 1,024 buckets rather than 8 or one million?
The bucket count is fixed forever, so it caps how finely we can spread data: with 1,024 buckets we can grow to hundreds of shards and still move small pieces. With 8, every shard is one bucket and there is nothing to move. With a million, the map becomes a 4 MB array per process, metadata and monitoring per bucket become heavy, and buckets get so small that moving them one by one is slow. A few thousand is a common middle ground: buckets are small enough to move in minutes and the map stays tiny.
Why not use a ConcurrentHashMap and update entries in place?
Because a move or rebalance changes several buckets together, and readers could see some updated and some not. Swapping a whole immutable snapshot makes every change atomic and keeps reads lock-free.
Would a ScopedValue work instead of a ThreadLocal?
Yes. ScopedValue, final in Java 25, binds a value for the duration of a call and cannot leak, which suits a per-request shard. It requires the routing code to run the call inside ScopedValue.where(...).run(...), and the value is visible to the DataSource on the same thread, which is what we need.
8Conclusion
In this answer, we wrote the core of a two-level shard router. The customer id is hashed with Murmur3 (Guava's murmur3_32_fixed) because it is stable and spreads similar ids, and Math.floorMod maps the signed hash into [0, 1024) where % and Math.abs fail. The bucket-to-shard map is an immutable array behind an AtomicReference, replaced as a whole snapshot with a version check. The chosen shard goes into a context read by AbstractRoutingDataSource, set before the transaction begins and cleared afterwards, and a MOVING marker with map versions keeps bucket moves safe.
Open with
I would route in two steps. First, a bucket: I hash the customer id with Murmur3, Guava's murmur3_32_fixed over the UTF-8 bytes, because it is stable across processes and languages and spreads similar ids well, whereas String.hashCode clusters for ids like cust-00001 and cust-00002.
Then, if they want more
The hash is a signed int, so I use Math.floorMod(hash, 1024), which always returns 0 to 1023; the % operator returns negatives, and Math.abs fails for Integer.MIN_VALUE. The bucket count is fixed forever, so a key never changes bucket when shards are added.
Second, the shard: an immutable int array of 1,024 entries, held in an AtomicReference together with a version. A reload builds a whole new array, copies it defensively, and swaps the reference, so readers take one snapshot and never see a half-updated map, without locks.
Then I put the shard into a request-scoped context before the transaction starts, and an AbstractRoutingDataSource returns it from determineCurrentLookupKey, so the whole transaction uses that shard's pool; I clear it in finally because threads are pooled.
Finally, the map carries a version and can mark a bucket as moving, so requests for it get a retryable error during a move, and I log bucket, shard and version on errors.
About this answer
- Last updated
- 13 November 2026
- Versions it names
- Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write the core Java routing code that maps a customer id to a shard, and explain the...": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/fb56fa6016/