BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / LLM inference and serving32 of 36 in topic

797. Build a key-value cache with expiry and LRU eviction

MediumLLM inference and serving Pro

Serving stacks cache things like embeddings, tokenized prompts and auth lookups. Entries must expire after a time to live, and the cache must stay under a fixed size.

Write run_ttl_cache(capacity, ops) that runs a list of operations on an empty cache and returns the list of outputs, one per operation. Times in ops never go down.

Operations: ('set', t, key, value, ttl) stores the value and returns None; the entry is live at times strictly less than t + ttl. Setting an existing key replaces its value and expiry. ('get', t, key) returns the value if the key is live, else None. ('delete', t, key) returns True if a live key was removed, else False. ('count', t) returns the number of live keys.

Eviction: a successful get and any set make that key the most recently used. When a set adds a new key and the cache already holds capacity live keys, first drop expired keys, then evict the least recently used live key.

Functiondef run_ttl_cache(capacity, ops)

Example 1

Input: capacity = 2, ops = [('set', 0, 'a', 1, 10), ('set', 1, 'b', 2, 10), ('get', 2, 'a'), ('set', 3, 'c', 3, 10), ('get', 4, 'b'), ('count', 4)]

Output: [None, None, 1, None, None, 2]

Example 2

Input: capacity = 5, ops = [('set', 0, 'k', 'v', 5), ('get', 4, 'k'), ('get', 5, 'k'), ('count', 5)]

Output: [None, 'v', None, 0]

Constraints

  • At most 10,000 operations.
  • Times are non-decreasing integers.
  • capacity >= 1.
Hint 1

Keep (value, expires_at) per key.

Hint 2

A key is live only when expires_at > t.

Hint 3

Purge expired keys before deciding a live key must be evicted.

Common mistakes
  • Using >= in the live check, so an entry lives one tick too long.
  • Evicting a live key while expired keys still use slots.
  • Forgetting that a get also refreshes recency.
Understand the idea

A cache with a time to live answers 'is this still fresh?', and LRU eviction answers 'what goes when we are full?'. Store absolute expiry times (t + ttl) rather than remaining time, so checking freshness is one comparison. Lazy expiry means you only check a key when you touch it, which is cheap; the cost is that dead keys can sit around, so sweep them before you evict a live key. With capacity 2: set a, set b, get a, then set c evicts b because a was used more recently. The same pattern guards prompt caches and embedding caches in model serving.

Topics
LLM inference and serving
Similar questions
  • Generate one token at a time with a KV cacheMedium
  • Allocate KV cache memory in pages, like vLLMMedium
  • Verify a draft model's guesses in speculative decodingMedium
  • Is decoding memory-bound? A roofline estimateMedium
All LLM inference and serving problems
Report
797 / 903
Python 3solution.pyPython idle
1
2
3
4
def run_ttl_cache(capacity, ops):
# return one output per operation
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS