KatInterview

Thread-Safe Maps, Cache Sharding and Batch Processing Models

System DesignModel answer
MediumModel answerSystem Designconcurrencyconsistent-hashingjava

Last updated

Explain how Java's concurrent hash map stays safe under contention, how to shard a session cache without mass reshuffling, and when batch map-reduce beats SQL joins.

This is a three-part conceptual question. Answer each part with mechanisms and concrete numbers, not slogans.

Part 1: Thread-safe maps in Java

  1. Describe how Java's ConcurrentHashMap stays correct under many simultaneous readers and writers without putting one lock around the whole structure. Cover how reads, inserts, and resizes work.
  2. You want to use your own class as a key in this map. What must hold for its equals() and hashCode() implementations, and what goes wrong if those rules are broken?

Part 2: Sharding a session cache

You are building a distributed cache for user session data on 10 nodes.

  1. Keys are assigned with node = hash(user_id) % num_nodes. What is the main problem when a node is added or removed? Quantify it if you can.
  2. Propose a placement scheme that moves far less data when the cluster changes. Explain how it works and which parameters affect how evenly load is spread.

Part 3: Processing models

Compare the MapReduce programming model with relational SQL joins. Describe a situation where you would choose a MapReduce-style batch job over a complicated SQL query running on a sharded database.

Hints

Hint 1

Think about the granularity of synchronization: what is the smallest unit that must be locked for a write, and which operations need no lock at all?

Hint 2

A key's hash picks the bucket and equality is checked inside it. Ask what happens to a lookup if two equal keys land in different buckets, or if a key's fields change after insertion.

Hint 3

For modulo placement, compute the fraction of keys for which h mod 10 equals h mod 11. For the alternative, picture nodes and keys on a circle and ask which keys are affected when one node appears.

Hint 4

For Part 3, compare who decides the execution plan, how data is moved between machines, and what happens to a job when a worker dies halfway.