KatInterview

Thread-Safe In-Memory Store and Sliding-Window Counter

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencyrace-conditionslocking

Last updated

Find the concurrency bugs in an in-memory key-value store with expiry and a 300-second hit counter, then fix them with appropriate locking and describe how to test.

You have built two single-process, in-memory components and now need to make them safe for many threads.

Component 1: key-value store

  • put(key, value, ttl=None), get(key), delete(key).
  • Entries with a TTL expire lazily on read and may also be removed by a background sweeper.

Component 2: sliding-window hit counter

  • hit(ts) records one event at second ts.
  • getHits(ts) returns the number of events in the last 300 seconds.
  • The implementation uses a circular array of 300 buckets, each holding a (timestamp, count) pair.

Assume a workload such as 16 to 64 threads, a read-heavy store (about 90% reads), and a write-heavy counter (hits far outnumber queries).

What to cover in your answer

  1. List the concrete race conditions in each component. Describe specific thread interleavings, not just "there may be races."
  2. Propose fixes and compare them: a single global lock, lock striping, read/write locks, atomics/CAS, striped counters, and lock-free or copy-on-write designs. Discuss correctness and performance for each.
  3. Explain what consistency guarantee your getHits gives, and whether that is acceptable.
  4. Describe how you would test and validate concurrent behavior.

Include code for the core of your fix.

Hints

Hint 1

For the store, look at every place where code does check-then-act or read-modify-write, especially the gap between noticing that an entry is expired and deleting it.

Hint 2

For the counter, a bucket's timestamp and count form one logical unit. Ask what happens if two threads at the same second both decide the bucket is stale, or if a reader sees half of an update.

Hint 3

Make the expiry delete conditional: only remove the entry if it is still the same version that was observed as expired. For testing, think about stress tests with invariant checks, many thread counts, and tools such as thread sanitizers.