Tiered Cache Manager with Expiry and Weighted Retrieval
Data Structure DesignModel answerLast updated
Implement a multi-level cache that evicts expired entries, checks tier utilization, and retrieves the highest-weight item from any eligible tier.
Background
Distributed systems often organize in-memory data across multiple storage tiers — hot, warm, and cold — each with a fixed capacity. A controller periodically pulls the most valuable item from any tier that has enough headroom, while ignoring tiers that are too full to be considered active consumers.
Your job is to implement TieredCache, a storage manager that spans several independent tiers and supports timed expiry and weighted retrieval.
What to Implement
__init__(tiers: list[tuple[int, int]])
Initializes the cache with an ordered list of (tier_id, capacity) pairs.
- The position in the list defines priority: index
0is the highest-priority tier, index1is next, and so on. - All
tier_idvalues are unique. - Every
capacityis at least1.
insert(tier_id: int, item_id: str, weight: int, expiry: int) -> bool
Stores a new item in the specified tier.
item_idis a unique string identifier.weightis a positive integer representing the item's value.expiryis a non-negative integer timestamp. The item is considered expired at any momenttwheret >= expiry.- Returns
Falseiftier_iddoes not exist, or if the tier is currently holding as many items as its capacity allows (even if some of those items are already past their expiry). - Returns
Trueon success.
retrieve(current_time: int) -> str | None
Fetches the most valuable available item by executing the following steps in order:
- Expire: Remove every item across all tiers whose
expiry <= current_time. This happens before anything else. - Screen tiers: A tier is eligible only if its remaining live item count satisfies
live_count <= capacity / 2(integer or float division; a tier more than half full is skipped). - Pick the winner: Among all items in eligible tiers, select the one with the highest
weight. Break ties as follows:- Prefer the item in the higher-priority tier (earlier index in the original list).
- If still tied, prefer the item that was inserted first (lower insertion order).
- Deliver: Remove the winning item from its tier and return its
item_id. If no eligible tier contains any live item, returnNone.
current_time values passed to retrieve are non-decreasing across calls.
Example
cache = TieredCache([(1, 4), (2, 2)])
# Tier 1: capacity 4, higher priority (index 0)
# Tier 2: capacity 2, lower priority (index 1)
cache.insert(1, "A", weight=10, expiry=100) # Tier 1 count=1
cache.insert(1, "B", weight=30, expiry=50) # Tier 1 count=2
cache.insert(1, "C", weight=20, expiry=100) # Tier 1 count=3
cache.insert(2, "D", weight=25, expiry=100) # Tier 2 count=1
# t=40: no expirations yet.
# Tier 1: 3 live items. 3 > 4/2=2 → ineligible.
# Tier 2: 1 live item. 1 <= 2/2=1 → eligible.
# Only "D" is reachable → returned.
assert cache.retrieve(40) == "D"
# t=60: item "B" (expiry=50) is purged first.
# Tier 1: now 2 live items. 2 <= 4/2=2 → eligible.
# Tier 2: 0 live items → eligible but empty.
# Heaviest item in Tier 1 is "C" (weight=20). "A" has weight=10.
assert cache.retrieve(60) == "C"
Constraints
- Number of tiers
L ≤ 100. 1 ≤ capacity ≤ 1,000per tier.1 ≤ weight ≤ 10^9.- All timestamps are non-negative integers up to
10^9. current_timeacross successiveretrievecalls is non-decreasing.- Total combined calls to
insertandretrieve≤ 50,000.
What is expected
Provide the full implementation of TieredCache with correct handling of all edge cases, and explain your data structure choices and their time complexity.
Hints
Hint 1
Each tier needs to answer two questions independently: which items have expired, and what is the heaviest live item? A min-heap keyed by expiry and a max-heap keyed by weight (negated for Python's min-heap) can answer each question in log time. Since one item lives in both heaps, you need a way to mark items as dead without removing them from both heaps at once — lazy deletion via a live-item set …
Hint 2
The eligibility check (`live_count <= capacity / 2`) needs to be accurate after purging but before retrieval. Keep an explicit per-tier counter of live items and decrement it whenever an item is purged or retrieved. Avoid floating-point by rewriting the condition as `2 * live_count <= capacity`.
Hint 3
The global winner is always the local winner of some tier. So you only need to peek at the top of each eligible tier's weight heap and compare those candidates. Encode the full tie-breaking rule into a single comparison key: `(-weight, tier_index, insertion_seq)` — the smallest such tuple wins.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is that retrieve has to do three things at once: expire stale entries, check per-tier utilization, and surface the globally best item — all while keeping each individual operation fast.
Data structures per tier
Each tier maintains two heaps and a live-item counter:
- Expiry heap: a min-heap of
(expiry, seq). Popping items from the front in order of their expiry timestamp handles the purge step efficiently. - Weight heap: a min-heap of
(-weight, seq, item_id). Negating weight turns Python's min-heap into a max-heap by weight, withseqas the tie-breaker (lower seq = inserted earlier = preferred). count: an integer tracking the number of live items in this tier right now.
One item lives in both heaps at the same time. Rather than remove it from both heaps when it expires or gets retrieved, we use lazy deletion: a global set alive holds the seq of every live item. When a heap entry surfaces, check seq in alive before acting on it. If it is not there, discard and move on.
insert
Push one entry onto each heap, add seq to alive, increment count, and bump the global sequence counter. No purge happens here — insert has no time argument, and a full tier is full regardless of whether some items are past their expiry. Return False immediately if the tier is unknown or already at capacity.
Cost: O(log n) for two heap pushes.
retrieve
Step 1 — Purge. For every tier, pop entries off the expiry heap while expiry <= current_time. For each popped entry, if seq in alive, remove it from alive and decrement count. Because current_time never decreases, anything popped now will never be needed again.
Step 2-3 — Find the winner. For each tier, skip it if count == 0 or if 2 * count > capacity (the half-full threshold, written without floats). For eligible tiers, clean stale entries off the top of the weight heap, then form the candidate key (-weight, tier_index, seq). The smallest key across all eligible tiers wins: it encodes maximum weight, then highest priority, then earliest insertion — exactly the spec's tie-breaking order.
Step 4 — Deliver. Pop the winning entry, remove its seq from alive, decrement its tier's count, and return item_id.
Cost: O(L + k log n) amortized per call, where k is the number of stale or expired entries processed. Every heap entry is pushed and popped at most once across all calls, so the total across all operations is O(n log n + R·L) with R retrieve calls. With L ≤ 100 and 50,000 total calls, this is well within budget.
Edge cases worth calling out
expiry == current_timeis expired. The purge condition is strict<=.- Odd capacity (e.g., 3): eligible threshold is
count ≤ 1. The2 * count <= capacityformulation handles this without floats. - Full tier with expired items:
insertstill returnsFalse. Capacity is checked against stored count, not live count, becauseinserthas no time context. Say this explicitly in an interview — it is the first thing interviewers probe. - No eligible items: return
None. - Reused
item_id: safe, because internal identity isseq, notitem_id.
Common mistakes
- Purging after the eligibility check instead of before — the spec is unambiguous about order.
- Using
count < capacity / 2instead ofcount <= capacity / 2— off by one at the boundary. - Forgetting to decrement
countwhen an item is retrieved (not just when it expires). - Using floating-point division for the eligibility test, which can misfire on odd capacities.
import heapq
class TieredCache:
def __init__(self, tiers: list[tuple[int, int]]):
self._index: dict[int, int] = {} # tier_id -> position index
self._cap: list[int] = []
self._count: list[int] = [] # live items per tier
self._exp_heap: list[list] = [] # per-tier min-heap by (expiry, seq)
self._wt_heap: list[list] = [] # per-tier min-heap by (-weight, seq, item_id)
for i, (tier_id, capacity) in enumerate(tiers):
self._index[tier_id] = i
self._cap.append(capacity)
self._count.append(0)
self._exp_heap.append([])
self._wt_heap.append([])
self._alive: set[int] = set() # seqs of items still live
self._seq: int = 0
def insert(self, tier_id: int, item_id: str, weight: int, expiry: int) -> bool:
i = self._index.get(tier_id)
if i is None or self._count[i] >= self._cap[i]:
return False
seq = self._seq
self._seq += 1
heapq.heappush(self._exp_heap[i], (expiry, seq))
heapq.heappush(self._wt_heap[i], (-weight, seq, item_id))
self._alive.add(seq)
self._count[i] += 1
return True
def retrieve(self, current_time: int) -> str | None:
# Step 1: purge expired items across all tiers.
for i, heap in enumerate(self._exp_heap):
while heap and heap[0][0] <= current_time:
_, seq = heapq.heappop(heap)
if seq in self._alive:
self._alive.discard(seq)
self._count[i] -= 1
# Steps 2-3: find the best candidate among eligible tiers.
# Key encodes: (max weight desc, tier priority asc, insertion order asc)
best_key: tuple | None = None
best_tier: int = -1
for i in range(len(self._cap)):
# Eligibility: tier must be at most half full after purging.
if self._count[i] == 0 or 2 * self._count[i] > self._cap[i]:
continue
# Clean stale entries off the top of this tier's weight heap.
wh = self._wt_heap[i]
while wh and wh[0][1] not in self._alive:
heapq.heappop(wh)
if not wh:
continue
neg_w, seq, _ = wh[0]
candidate = (neg_w, i, seq) # smallest = best under all tie-breakers
if best_key is None or candidate < best_key:
best_key = candidate
best_tier = i
if best_key is None:
return None
# Step 4: remove winner and return its id.
_, seq, item_id = heapq.heappop(self._wt_heap[best_tier])
self._alive.discard(seq)
self._count[best_tier] -= 1
return item_id
Follow-up: scaling to millions of tiers
The O(L) scan over all tiers becomes the bottleneck at scale. Two improvements help:
- Global expiry heap: replace per-tier expiry heaps with one heap of
(expiry, seq, tier_index). Purge cost then depends on the number of expired items, not L. - Eligible-tier index: maintain a sorted structure (e.g., a heap or balanced BST) holding only the tiers currently eligible, keyed by their local best-item key. On insert, expiry, or retrieval, update the affected tier's entry.
retrievethen reads the global winner in O(log L) instead of O(L).