KatInterview

Building a High-Performance In-Memory Cache

System DesignModel answer
HardModel answerSystem Designcachingconcurrencydistributed-systems

Last updated

Design a fast, thread-safe in-memory cache with automatic expiration and crash recovery capabilities.

Problem

You need to build a high-performance, in-memory caching system that stores key-value pairs. The cache must support basic operations with extremely low latency while handling concurrent access from multiple clients.

Core Operations

Your cache must implement:

  • SET(key, value): Store or update a key-value pair
  • GET(key): Retrieve the value for a given key (return null if absent)
  • DELETE(key): Remove a key and its value
  • EXPIRE(key, ttl): Mark a key for automatic removal after a specified duration

System Constraints

  • Performance goal: Operations should complete in under 1 millisecond
  • Concurrency: Support thousands of simultaneous client connections
  • Crash recovery: Minimize data loss when the system restarts unexpectedly

Scale Parameters

  • Expected dataset: 10 million keys
  • Typical value size: 1 KB per entry
  • Traffic pattern: 90% read operations, 10% writes

What to Cover

  1. Choose and justify the core data structures for storing entries
  2. Design a concurrency control approach that avoids bottlenecks
  3. Implement efficient automatic expiration without scanning all keys
  4. Create a persistence strategy that doesn't compromise performance

Explain your reasoning for each decision and discuss the trade-offs involved.

Hints

Hint 1

Start by calculating total memory requirements—this tells you whether a single machine suffices

Hint 2

For concurrency, consider how to reduce lock contention: sharding the data across multiple independent structures is often better than one global lock

Hint 3

Expiration needs both correctness (never return expired data) and efficiency (reclaim memory without constant scanning)