KatInterview

Concurrent In-Memory Cache with Sharded Locking

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadinglocking

Last updated

Build a thread-safe in-memory cache supporting concurrent reads and writes, choosing data structures and synchronization primitives to minimize contention.

You're building an in-memory cache for a multi-threaded application. Multiple threads will simultaneously insert, retrieve, and remove entries from this cache, all within a single process.

Your task is to design a thread-safe cache class that supports these operations:

  • put(key, value): store or update the value associated with a key
  • get(key): retrieve the value for a key, returning null/None if not found
  • delete(key): remove a key and its value if present

Requirements:

  • Thread safety: Operations must be safe under concurrent access with no data corruption or lost updates
  • Atomicity: Each operation should behave as if it executes instantaneously from the caller's perspective
  • Performance: Minimize blocking between threads; avoid unnecessary serialization
  • Scope: Single-process only (no distributed system concerns)
  • Types: Keys are strings; values can be any object type

Answer these questions:

  1. What underlying data structure would you choose to hold the key-value mappings? Justify your choice.

  2. What synchronization approach would you use? Compare at least three options (such as: global mutex, reader-writer locks, sharded locks, lock-free structures, or language-provided concurrent collections). Explain the benefits and drawbacks of each.

  3. Pick one synchronization strategy and implement it in a language that lacks a built-in concurrent map (like Python with a standard dict). Show or describe how you'd implement put, get, and delete.

  4. How would you verify correctness and detect race conditions? Describe your testing approach, including any concurrency-specific techniques or tools.

  5. What production considerations would matter if this cache were deployed in a real system? Think about monitoring, resource limits, input validation, and performance tuning.

Hints

Hint 1

A hash table gives O(1) operations for point lookups—do you need ordering or range queries?

Hint 2

Dividing the cache into independent segments, each with its own lock, reduces contention proportionally to the segment count.

Hint 3

When acquiring multiple locks (for operations like size()), always take them in a consistent order to prevent deadlock.