System Design Lab / Simulation

Simulate a tiny LRU cache

Send a request sequence through a least-recently-used cache and compare hits, misses and memory limits.

You will learn to

  • Explain eviction
  • Calculate a hit rate
  • Identify the limits of a cache model

Before you start

Arrays and key-value lookup

Trace the path

A request reaches the cache first. On a hit, return its value and mark the key most recently used. On a miss, fetch from the simulated origin, insert the value and evict the least recently used key if capacity is exceeded. The diagram is an original representation of this flow.

A model is not a benchmark

Objects here have equal size and never expire. The latency estimate uses values you choose, not measured network performance. Real systems need invalidation, TTLs, synchronization and memory accounting. A high hit rate does not prove correctness: stale data can be fast and wrong.

Compare workloads

Try A B A C A B with capacities two and three. Compare a hot repeated key with unique keys. Ask whether caching helps with no reuse and which personalized responses must never be shared.

Work through six requests

Set capacity to 2 and enter A B A C A B. Read cache order from least to most recently used. A misses and leaves [A]. B misses and leaves [A, B]. A hits and moves to the end, leaving [B, A]. C misses, evicts B and leaves [A, C]. A hits and leaves [C, A]. B misses, evicts C and leaves [A, B].

There are two hits and four misses, so the hit rate is 2 / 6, approximately 33.3%. With capacity 3, the same sequence has three compulsory misses followed by three hits: 50%. These are deterministic simulation results, not measurements of a real service.

Why recency changes the answer

A correct LRU implementation updates recency on both insertion and a hit. If a hit leaves the order unchanged, the fourth request above evicts A instead of B: that behavior resembles insertion-order eviction, not LRU. Trace one repeated key before comparing larger workloads.

This model caches keys, not actual response bodies. It omits expiration, concurrent requests, invalidation, memory sizes and network costs. A high hit rate does not alone establish faster end-to-end responses. A cache with expensive lookup or stale data can hurt users even when many requests hit.

As a follow-up, compare A A A A with A B C D at capacity 2. The first sequence has one miss and three hits; the second has four misses. Increasing capacity cannot create reuse when every request is unique. For user-specific data, include the correct identity in the key and enforce authorization before returning a cached result.

Try it yourself

Enable JavaScript for this interactive activity. You can read all lesson explanations above without it.

Continue exploring