Designing Multilevel Cache - Hierarchical Caching System

Difficulty: Medium-Hard Patterns: Strategy, Composition, Facade Asked at: PhonePe, Flipkart, Amazon, Walmart


Functional Requirements

  1. Multiple cache levels - L1 (fast, small capacity) and L2 (slower, larger capacity), extensible to N levels
  2. Configurable eviction - each level can use a different eviction strategy (least recently used, LRU, or least frequently used, LFU)
    💡 Eviction = choosing which entry to throw out when a full level needs room. LRU throws out whatever has gone untouched the longest; LFU throws out whatever has been asked for the fewest times.
  3. Read-through - on cache miss at L1, check L2, then origin; populate upper levels on hit
    💡 Read-through = the cache itself fetches a missing value from the next level down and stores it on the way back, so the caller only ever talks to the cache and never to the origin.
  4. Write-through - writes propagate to all cache levels (top-down)
    💡 Write-through = a write lands in every level immediately. The alternative, write-back, would only touch L1 and flush downward later — faster, but a crash loses the un-flushed writes.
  5. TTL support - entries expire after a configurable time to live (TTL)
    💡 Time to live (TTL) = how long an entry is allowed to be served after it was created. It is the simplest answer to “my cache is showing stale data”.
  6. Get/Put/Delete - standard cache operations with O(1) average time complexity
    💡 O(1) means the cost does not grow with the number of entries — a cache holding ten million keys answers as fast as one holding ten. That is the whole reason a cache is worth having.

Non-Functional Requirements

  1. O(1) operations - get, put, delete must be constant time (HashMap + DoublyLinkedList for LRU, HashMap + frequency lists for LFU)
  2. Thread-safety - concurrent reads and writes must not corrupt cache state
    💡 Thread-safety = the structure stays correct when several threads touch it at once. Two threads mid-eviction on the same linked list can otherwise leave a node pointing at a removed node.
  3. Extensibility - add new eviction policies (first in first out, FIFO, or Random) without modifying existing code
    💡 That “without modifying existing code” is the open/closed principle: new behaviour arrives as a new class, and the classes that already work are left untouched. Learn more →
  4. Correctness - eviction removes the correct entry per policy, TTL expiry is honored

Core Entities

Entity Description
Cache Interface - get, put, delete operations
CacheEntry Key, value, creation time, TTL
EvictionPolicy Strategy interface - tracks access, evicts entries
LRUEviction Least Recently Used - doubly linked list + HashMap
LFUEviction Least Frequently Used - frequency map + min-frequency tracking
CacheLevel Single cache level with capacity, eviction policy, and TTL
MultilevelCache Composes multiple CacheLevels with read-through and write-through
CacheManager Facade - provides simple get/put/delete to clients

💡 A doubly linked list is a chain where every node holds a pointer to both its neighbours. That second pointer is what lets you unhook a node from the middle without walking the list to find what came before it — the single trick the whole LRU implementation rests on.


Class Diagram

classDiagram
    class EvictionPolicy {
        <<interface>>
        +onAccess(key String)
        +onInsert(key String)
        +evict() String
        +remove(key String)
    }
    class LRUEviction
    class LFUEviction
    class CacheEntry {
        -String key
        -Object value
        -long createdAt
        -long ttlMs
        +isExpired() boolean
    }
    class CacheLevel {
        -int capacity
        -Map~String-CacheEntry~ store
        -EvictionPolicy policy
        -long defaultTtlMs
        +get(key) Object
        +put(key, value)
        +delete(key)
    }
    class MultilevelCache {
        -List~CacheLevel~ levels
        +get(key) Object
        +put(key, value)
        +delete(key)
    }
    class CacheManager {
        -MultilevelCache cache
        +get(key) Object
        +put(key, value)
        +delete(key)
        +stats() CacheStats
    }
    EvictionPolicy <|.. LRUEviction
    EvictionPolicy <|.. LFUEviction
    CacheLevel --> EvictionPolicy
    CacheLevel --> CacheEntry
    MultilevelCache --> CacheLevel
    CacheManager --> MultilevelCache

💡 Reading the arrows: a dashed arrow with a hollow head (<|..) means “implements this interface”, so LRU and LFU are two drop-in eviction policies. A plain arrow (-->) means “holds a reference to”, which is how the levels stack up. Learn more →

Key classes:

  • EvictionPolicy — the four-method interface (onAccess, onInsert, evict, remove) that every eviction algorithm implements. Note it tracks only keys, never values; the entries themselves live in the level.
  • LRUEviction / LFUEviction — the two supplied policies. Each keeps its own bookkeeping structure so that picking a victim is O(1) rather than a scan.
  • CacheEntry — one stored key/value pair plus its creation time and TTL. It answers isExpired() itself, so no caller does clock arithmetic.
  • CacheLevel — one tier of the hierarchy. Owns a capacity, a map of entries, one eviction policy and a default TTL, plus its own hit/miss counters. It is the only class that decides when to evict.
  • MultilevelCache — holds the ordered list of levels and implements the hierarchy rules: search top-down on read, promote upward on a lower-level hit, write to every level on a put.
  • CacheManager — the public face. Takes the lock, forwards to MultilevelCache, and exposes stats. Clients import this and nothing else.

Design Patterns

Pattern Where Why
Strategy EvictionPolicy with LRU/LFU Swap eviction algorithm per cache level, no if/else chain
Composition MultilevelCache composes CacheLevel objects Add/remove levels without changing core logic
Facade CacheManager Single entry point hides multilevel complexity from clients