KatInterview

Tiered Cache Manager with Expiry and Weighted Retrieval

Data Structure DesignModel answer
HardModel answerData Structure Designheaplazy-deletionmulti-level

Last 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 0 is the highest-priority tier, index 1 is next, and so on.
  • All tier_id values are unique.
  • Every capacity is at least 1.

insert(tier_id: int, item_id: str, weight: int, expiry: int) -> bool

Stores a new item in the specified tier.

  • item_id is a unique string identifier.
  • weight is a positive integer representing the item's value.
  • expiry is a non-negative integer timestamp. The item is considered expired at any moment t where t >= expiry.
  • Returns False if tier_id does 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 True on success.

retrieve(current_time: int) -> str | None

Fetches the most valuable available item by executing the following steps in order:

  1. Expire: Remove every item across all tiers whose expiry <= current_time. This happens before anything else.
  2. 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).
  3. 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).
  4. Deliver: Remove the winning item from its tier and return its item_id. If no eligible tier contains any live item, return None.

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,000 per tier.
  • 1 ≤ weight ≤ 10^9.
  • All timestamps are non-negative integers up to 10^9.
  • current_time across successive retrieve calls is non-decreasing.
  • Total combined calls to insert and retrieve ≤ 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.