Multi-Level Key-Value Store with Expiration and Time Travel
System DesignModel answerLast updated
Build an in-memory key-value store supporting CRUD, filtered queries, automatic expiration, and historical lookups across four progressive levels.
You are building an in-memory key-value store that will be extended across four progressive stages. Each stage adds new capabilities while maintaining compatibility with earlier features.
Stage 1: Core Operations
Implement fundamental operations for managing records and their fields:
- Create and remove records
- Add, update, and remove fields within a record
- Retrieve entire records or individual field values
Define clear behavior for missing records or fields, and ensure all operations are idempotent.
Stage 2: Field Filtering
Add the ability to query which fields in a record satisfy given conditions. Support predicates including:
- Equality and inequality checks
- Numeric comparisons (less than, greater than, etc.)
- String operations (substring matching, prefix checks, pattern matching)
Design a filter expression format and implement an API that returns matching field names.
Stage 3: Automatic Expiration
Support time-based expiration by allowing each record to have a time-to-live (TTL). Records should automatically become inaccessible once their TTL elapses. Address:
- How expiration is detected and enforced
- Behavior when reading or writing expired records
- Efficient expiry tracking (aim for logarithmic or better complexity per operation)
Stage 4: Historical Queries
Enable querying past states of the database. Support reading field values or entire records as they existed at any previous timestamp. Consider:
- How creates, updates, deletes, and expiration interact with historical reads
- Storage strategy for maintaining version history
- Trade-offs between query performance and memory usage
For each stage, specify:
- API method signatures and return values
- Core data structures and their rationale
- Time and space complexity
- Key edge cases and how they are handled
- A brief test strategy
Make reasonable assumptions about scale (records, fields, operations), concurrency model, and time representation. State your assumptions clearly.
Hints
Hint 1
Choose data structures in Stage 1 that can accommodate versioning later without major refactoring
Hint 2
For expiration, consider a priority queue with lazy deletion rather than active polling
Hint 3
Historical queries need to distinguish 'record didn't exist' from 'field wasn't set' — track record lifetime separately from field versions
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests API design, data structure selection under evolving requirements, and handling time semantics correctly. The key challenge is choosing structures early that won't require fundamental redesign when historical queries are added.
Assumptions and Scope
Scale: Approximately 100,000 records, 100 fields per record, 1 million total operations. Everything stays in memory with no disk persistence.
Concurrency: Single-threaded execution. Locking can be discussed as an extension.
Time model: Operations accept an explicit timestamp parameter rather than reading system time. Timestamps are monotonically non-decreasing. This makes testing deterministic and lets us control time precisely.
Data types: Field values are strings. Numeric predicates attempt to parse values as numbers and fail gracefully for non-numeric values.
Error handling: Methods return success/failure booleans or None for missing data. No exceptions for normal "not found" cases. All operations are idempotent.
API Design
# Stage 1: Core CRUD
create_record(timestamp, record_id) -> bool
delete_record(timestamp, record_id) -> bool
set_field(timestamp, record_id, field_name, value) -> bool
delete_field(timestamp, record_id, field_name) -> bool
get_record(timestamp, record_id) -> dict | None
get_field(timestamp, record_id, field_name) -> str | None
# Stage 2: Filtering
list_fields(timestamp, record_id, filters) -> list[str] | None
# Stage 3: Expiration
set_ttl(timestamp, record_id, ttl_seconds) -> bool
# Stage 4: Time Travel
get_field_at(timestamp, record_id, field_name, query_time) -> str | None
get_record_at(timestamp, record_id, query_time) -> dict | None
Filter format: List of (operator, operand) tuples combined with AND logic.
- Operators:
"eq","ne","lt","le","gt","ge","contains","prefix","regex" - Empty list matches all fields
- Example:
[("gt", "100"), ("contains", "active")]
Data Structures
current_state: dict[record_id, dict[field_name, value]]
expiry_times: dict[record_id, expiration_timestamp]
expiry_heap: list[(expiration_timestamp, record_id)]
lifecycles: dict[record_id, list[[creation_time, deletion_time]]]
field_history: dict[(record_id, field_name), list[(timestamp, value_or_tombstone)]]
Rationale:
current_state provides O(1) access for Stages 1-3. For Stage 4, we can't simply version this entire structure—we need per-field granularity.
lifecycles tracks when records existed as intervals. Each create appends a new [start, infinity] interval. Delete or expiration closes the current interval. This separates "does the record exist?" from "what are its field values?" which is crucial when a record is deleted, expires, then recreated.
field_history is an append-only list per field. Each write appends (timestamp, value). Deletes append a tombstone marker. Because timestamps are monotonic, these lists stay sorted, enabling binary search.
The expiry heap supports efficient TTL without iterating all records on every call.
Stage 3: Expiration Details
Expiry semantics: A record with TTL of 10 seconds set at time 100 is visible through time 109 and expires at time 110. Formally: alive if current_time < expiration_timestamp.
Implementation: Every operation first calls _check_expirations(timestamp) which pops heap entries where expiration_timestamp <= timestamp and removes those records from current_state.
Lazy deletion in heap: When set_ttl is called multiple times on the same record, we push a new heap entry rather than updating in-place (which is O(n)). When popping, verify that expiry_times[record_id] == expiration_timestamp from the heap. If not, the entry is stale and we discard it.
Complexity: Each TTL write pushes once, each expiration pops once. Amortized O(log n) per TTL operation. Reads stay O(1) after the expiration check.
Behavior after expiration: An expired record behaves identically to a deleted one:
- Reads return
None - Writes return
False(record doesn't exist) create_recordsucceeds, starting a fresh record with no TTL
Design choice: Field writes do NOT refresh the TTL. The TTL countdown continues independently of field modifications. This prevents unexpected lifetime extensions and keeps semantics simple.
Stage 4: Historical Queries Deep Dive
The critical insight: separate record existence from field values.
Record existence at time T:
Binary search lifecycles[record_id] for the interval containing T. If start <= T < end for some interval, the record existed.
Field value at time T:
Binary search field_history[(record_id, field_name)] for the last entry with timestamp <= T.
Combining them:
- Check if record existed at query time
- If yes, find the field's value
- If the value is a tombstone, return
None - If the value's timestamp predates the current record incarnation's start time, return
None(it belonged to a previous incarnation)
This last check prevents values from "leaking" across incarnations when a record is deleted, recreated, and queried historically.
Handling TTL in history:
When set_ttl is called, update the current lifecycle interval's end time to timestamp + ttl. If TTL is cleared (ttl=None), set end back to infinity. When the expiration actually occurs, the interval already has the correct end time—no additional history write needed.
Complexity:
- Write operations: O(1) amortized (append to version list)
get_field_at: O(log V + log L) where V = versions of that field, L = lifecycle intervalsget_record_at: O(F · log V) where F = number of fields ever written to this record- Space: O(total write operations)
Trade-offs:
Per-field versioning vs. global log: We chose per-field lists because point queries (most common) are faster. A global append-only log would require replay for each query, making reads O(log W + R) where W is total writes and R is writes to replay.
Snapshots: Periodic record-level snapshots could speed up get_record_at to O(F + log S) but increase memory by a constant factor. Reasonable for read-heavy workloads.
Retention windows: Limit history to the most recent N hours or M versions to bound memory growth. Queries beyond the window return None or raise an error.
Compaction: Merge old versions when the version list grows large, keeping only periodic checkpoints. Adds write overhead but improves query latency.
Edge Cases
Same-timestamp writes: When multiple operations share a timestamp, use bisect_right to get the most recent write in that batch.
Delete then immediate recreate: Creates a new lifecycle interval. Historical queries before the recreation correctly return None.
Expire, then recreate with same ID: Same as delete/recreate. Old field values don't resurface.
Setting TTL to zero or negative: Record expires immediately on the next operation.
Querying future times: Undefined behavior. Either reject (timestamp validation) or treat as current time.
Non-numeric values in numeric predicates: Predicate evaluates to false for that field.
Test Strategy
Stage 1: Create/delete idempotency, field upsert, reads on missing records, reads on missing fields.
Stage 2: Empty filters (match all), single predicate, multiple predicates (AND logic), regex with special characters, numeric comparison on non-numeric values.
Stage 3: Basic expiration, stale heap entries (multiple TTL updates), read/write on expired record, recreate after expiration, clear TTL, zero TTL.
Stage 4: Query before creation, query after deletion, query during a lifecycle, recreate and query old incarnation, field deleted in past, TTL interacting with historical reads, same-timestamp batch writes.
Complexity Summary
| Operation | Time | Space |
|---|---|---|
| create_record, delete_record | O(1) | O(1) |
| set_field, delete_field | O(1) amortized | O(1) |
| get_record, get_field | O(1) + expiry check | - |
| list_fields | O(F · P) where F=fields, P=predicate cost | - |
| set_ttl | O(log n) amortized | O(1) |
| get_field_at | O(log V + log L) | - |
| get_record_at | O(F · log V) | - |
| Total space | - | O(total writes) |
Extensions
Concurrency: Add per-record read-write locks. Historical reads are read-only except for the expiry heap. Use a separate lock for the heap or make expiry checks lock-free with atomic operations.
Persistence: Append writes to a WAL (write-ahead log). Rebuild state on restart by replaying the log. Periodic snapshots reduce replay time.
Distributed version: Partition records across nodes by hashing record ID. Historical queries stay local. TTL requires distributed time coordination or per-node cleanup with eventual consistency.