Query Recent Time-Series Metrics by Name and Tag Subset
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory telemetry store that ingests timestamped numeric observations with string metadata labels and answers top-k recency queries filtered by metric name and label subsets.
Every observation has four fields:
name(str): identifier of the series being measured (such as"db_latency").value(float): numeric reading captured for that event.tags(dict[str, str]): key-value string attributes describing the source (such as{"tier": "primary", "az": "usw1"}).timestamp(int): millisecond timestamp of the event. Events may arrive out of time order.
Design a MetricStore supporting two operations, exposed to the test harness through metric_store(operations, arguments):
def metric_store(operations: List[str], arguments: List[List]) -> List[Optional[List[Dict]]]:
Each index i pairs operations[i] with arguments[i] on one shared store instance:
"record"with[name, value, tags, timestamp]:- Appends the observation to the store and produces
Nonein the output list. - Identical observations—even sharing the exact same
name,value,tags, andtimestamp—are kept as distinct entries rather than deduplicated.
- Appends the observation to the store and produces
"query"with[name, tags, limit]:- Finds stored observations whose
nameequals the requestednameand whosetagsmap contains every(key, value)pair present in the query'stagsfilter. Extra keys on a stored observation are allowed, and an empty filter{}matches every tag map undername. - Orders matching observations by
timestampfrom largest to smallest (newest first). Whenever two matching observations have the sametimestamp, the one ingested by a later"record"call comes first. - Returns at most
limitmatching observations (or all matches if fewer thanlimitexist), each formatted as{"name": str, "value": float, "tags": dict[str, str], "timestamp": int}.
- Finds stored observations whose
Examples
Example 1
Input:
operations = ["record", "record", "record", "record", "query"]
arguments = [
["db_latency", 14.2, {"tier": "primary", "az": "usw1"}, 500],
["db_latency", 28.5, {"tier": "primary", "az": "use1"}, 540],
["db_latency", 9.0, {"tier": "replica", "az": "usw1"}, 590],
["db_latency", 31.0, {"tier": "primary", "az": "usw1"}, 540],
["db_latency", {"tier": "primary"}, 2]
]
Output:
[
None,
None,
None,
None,
[
{"name": "db_latency", "value": 31.0, "tags": {"tier": "primary", "az": "usw1"}, "timestamp": 540},
{"name": "db_latency", "value": 28.5, "tags": {"tier": "primary", "az": "use1"}, "timestamp": 540}
]
]
Walk-through: Three "db_latency" entries carry "tier": "primary" (at timestamps 500, 540, and 540), while the 590 entry is skipped because its "tier" is "replica". The two entries at timestamp 540 tie on time, so the fourth "record" (value = 31.0) precedes the second "record" (value = 28.5). Because limit = 2, the older entry at 500 is omitted.
Example 2
Input:
operations = ["record", "record", "record", "query", "query", "query"]
arguments = [
["cache_hits", 120.0, {"node": "n1", "pool": "auth"}, 200],
["cache_hits", 85.0, {}, 200],
["disk_io", 4.5, {"node": "n1"}, 250],
["cache_hits", {}, 10],
["cache_hits", {"pool": "billing"}, 5],
["net_rx", {}, 5]
]
Output:
[
None,
None,
None,
[
{"name": "cache_hits", "value": 85.0, "tags": {}, "timestamp": 200},
{"name": "cache_hits", "value": 120.0, "tags": {"node": "n1", "pool": "auth"}, "timestamp": 200}
],
[],
[]
]
Walk-through: The first query uses an empty tag filter {} with limit = 10, matching both "cache_hits" entries at timestamp 200 and returning the later-inserted 85.0 entry ahead of 120.0 (ignoring "disk_io"). The second query requests "pool": "billing", which no entry has ([]), and the third queries an unseen metric name "net_rx" ([]).
Constraints
0 <= len(operations) == len(arguments) <= 50,000- Every
namehas length1 <= len(name) <= 100and contains only ASCII letters, digits, and underscores (_). - Every
tagsdictionary has0 <= len(tags) <= 20string keys and string values. 1 <= timestamp <= 2^63 - 1, with no guarantee of chronological arrival order.1 <= limit <= 1000for every"query"operation.
Step-by-step walkthrough
Understand the operations and ordering rules
We need an in-memory
MetricStorethat ingests timestamped observations and retrieves the most recent matching entries:record(name, value, tags, timestamp): Stores one observation. Even when two calls share the exact samename,value,tags, andtimestamp, both are retained as separate entries.query(name, tags, limit): Returns up tolimitstored entries undernamewhosetagsinclude every(key, value)pair requested by the query'stagsfilter:- Additional keys on the stored entry are allowed (
{"tier": "primary", "az": "usw1"}matches query{"tier": "primary"}). - An empty filter
{}matches every entry stored undername.
- Additional keys on the stored entry are allowed (
- Sorting and tie-breaking:
- Primary order:
timestampdescending (largest timestamp first). - Tie-breaker: insertion order descending (when two entries share the same
timestamp, the one ingested later comes first).
- Primary order:
Timestamps can arrive out of chronological order, and
metric_store(operations, arguments)replays a sequence of"record"and"query"commands against one sharedMetricStore.Why filtering and sorting everything per query is too slow
A naive implementation appends every observation into one flat list, and on each
queryscans the whole list, checksnameandtags, sorts all matches from scratch, and slices[:limit].With up to
50,000operations, consider25,000"db_latency"writes followed by25,000queries withlimit = 2. Scanning unrelated metric names and sorting25,000entries25,000times performs hundreds of millions of comparisons — even though previously stored entries never change relative order andlimit = 2only needs the two newest matches!Key idea: bucket by name and keep tuples sorted on insert
We avoid both wasted scans and repeated sorting by organizing entries at write time:
- Bucket by
namein a dictionary (by_name): A query for"db_latency"looks upby_name["db_latency"]directly and skips every other metric name. - Keep each bucket sorted ascending as
(timestamp, seq, value, tags_copy): Assign eachrecordcall an increasing integerseq = 0, 1, 2, ..., and insert into the list withbisect.insort(which binary-searches for the sorted index and inserts there). - Walk backwards with
reversed(...)and stop atlimit: See what happens when an ascending(timestamp, seq)list is read from right to left:
Stored ascending (left -> right): idx 0: (ts=500, seq=0, ...) idx 1: (ts=540, seq=1, ...) <-- ingested earlier at ts=540 idx 2: (ts=540, seq=3, ...) <-- ingested later at ts=540 idx 3: (ts=590, seq=2, ...) <-- newest timestamp Read backwards with reversed() (right -> left): (590, 2) -> (540, 3) -> (540, 1) -> (500, 0) newest ts=540, ts=540, oldest later seq earlier seqReading from right to left yields exact
(timestamp DESC, seq DESC)order with zero sorting duringquery, allowing us tobreakas soon as we collectlimitmatches!Placing
seqat tuple index1also prevents a subtle Python crash: tuple comparison proceeds left to right and stops at the first differing element. Because every entry gets a uniqueseq, Python never attemptsdict < dictontags(which would raiseTypeError).- Bucket by
Write the subset tag-matching helper
A stored entry satisfies
wanted_tagswhen every(key, value)pair inwanted_tagsappears inmetric_tagswith the identical value. Ifwanted_tagshas more keys thanmetric_tags, we can returnFalseimmediately; ifwanted_tagsis{}, the loop completes immediately and returnsTrue.def has_all_tags(metric_tags: Dict[str, str], wanted_tags: Dict[str, str]) -> bool: # A metric with fewer keys than the query filter cannot possibly contain every wanted key. if len(wanted_tags) > len(metric_tags): return False for key, value in wanted_tags.items(): if key not in metric_tags or metric_tags[key] != value: return False return TrueImplement `MetricStore.record`
Each
recordcall copiesdict(tags)defensively (so caller mutations afterwards cannot alter stored history), packs(timestamp, self.next_seq, value, dict(tags)), incrementsself.next_seq, and inserts intoself.by_name[name]usingbisect.insort.Whenever timestamps arrive roughly in order,
bisect.insortplaces the new tuple right at the tail of the list with minimal element shifting.class MetricStore: def __init__(self) -> None: # by_name: metric_name -> ascending list of (timestamp, seq, value, tags_copy), # e.g., {"db_latency": [(500, 0, 14.2, {"tier": "primary"}), (540, 1, 28.5, {"tier": "primary"})]}. self.by_name: Dict[str, List[Tuple[int, int, float, Dict[str, str]]]] = {} # next_seq: strictly increasing insertion ID (0, 1, 2, ...) used to break timestamp ties. self.next_seq = 0 def record(self, name: str, value: float, tags: Dict[str, str], timestamp: int) -> None: # Copy tags so later caller edits cannot mutate stored history. # Unique seq at index 1 orders equal timestamps and prevents Python from comparing dicts with '<'. entry = (timestamp, self.next_seq, value, dict(tags)) self.next_seq += 1 if name not in self.by_name: self.by_name[name] = [] # Keep each metric's list sorted ascending by (timestamp, seq) as events arrive. bisect.insort(self.by_name[name], entry)Implement `MetricStore.query` and the judge wrapper
queryreturns[]immediately ifnamehas never been recorded, otherwise iteratesreversed(self.by_name[name])(creating anO(1)reverse iterator without copying the list). Each matching entry is emitted with a fresh copy ofmetric_tags, and iteration stops oncelen(results) == limit.def query(self, name: str, tags: Dict[str, str], limit: int) -> List[Dict]: if limit <= 0 or name not in self.by_name: return [] results = [] entries = self.by_name[name] # Walk backwards from the right end: newest timestamp first, and latest insertion first on ties. for timestamp, seq, value, metric_tags in reversed(entries): if has_all_tags(metric_tags, tags): results.append({ "name": name, "value": value, "tags": dict(metric_tags), "timestamp": timestamp, }) # Stop as soon as we have collected `limit` matches instead of scanning older history. if len(results) == limit: break return resultsTrace Example 1 step by step
Let's trace the four
"record"calls from Example 1 (seq = 0, 1, 2, 3), whereseq = 3arrives withtimestamp = 540afterseq = 2attimestamp = 590:by_name["db_latency"] after all 4 inserts (sorted ascending): [0] (ts=500, seq=0, val=14.2, tags={"tier": "primary", "az": "usw1"}) [1] (ts=540, seq=1, val=28.5, tags={"tier": "primary", "az": "use1"}) [2] (ts=540, seq=3, val=31.0, tags={"tier": "primary", "az": "usw1"}) [3] (ts=590, seq=2, val=9.0, tags={"tier": "replica", "az": "usw1"}) Now run query("db_latency", {"tier": "primary"}, limit=2) walking from [3] down to [0]: - Visit [3] (590, seq=2): tier is "replica" != "primary" -> skip - Visit [2] (540, seq=3): matches {"tier": "primary"} -> collect val=31.0 (1 of 2) - Visit [1] (540, seq=1): matches {"tier": "primary"} -> collect val=28.5 (2 of 2) -> STOP! - [0] (500, seq=0) is never even inspected.The
az = "usw1"reading (val = 31.0,seq = 3) precedes theaz = "use1"reading (val = 28.5,seq = 1) at timestamp540because it was recorded later.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import bisect def has_all_tags(metric_tags: Dict[str, str], wanted_tags: Dict[str, str]) -> bool: # A metric with fewer keys than the query filter cannot possibly contain every wanted key. if len(wanted_tags) > len(metric_tags): return False for key, value in wanted_tags.items(): if key not in metric_tags or metric_tags[key] != value: return False return True class MetricStore: def __init__(self) -> None: # by_name: metric_name -> ascending list of (timestamp, seq, value, tags_copy), # e.g., {"db_latency": [(500, 0, 14.2, {"tier": "primary"}), (540, 1, 28.5, {"tier": "primary"})]}. self.by_name: Dict[str, List[Tuple[int, int, float, Dict[str, str]]]] = {} # next_seq: strictly increasing insertion ID (0, 1, 2, ...) used to break timestamp ties. self.next_seq = 0 def record(self, name: str, value: float, tags: Dict[str, str], timestamp: int) -> None: # Copy tags so later caller edits cannot mutate stored history. # Unique seq at index 1 orders equal timestamps and prevents Python from comparing dicts with '<'. entry = (timestamp, self.next_seq, value, dict(tags)) self.next_seq += 1 if name not in self.by_name: self.by_name[name] = [] # Keep each metric's list sorted ascending by (timestamp, seq) as events arrive. bisect.insort(self.by_name[name], entry) def query(self, name: str, tags: Dict[str, str], limit: int) -> List[Dict]: if limit <= 0 or name not in self.by_name: return [] results = [] entries = self.by_name[name] # Walk backwards from the right end: newest timestamp first, and latest insertion first on ties. for timestamp, seq, value, metric_tags in reversed(entries): if has_all_tags(metric_tags, tags): results.append({ "name": name, "value": value, "tags": dict(metric_tags), "timestamp": timestamp, }) # Stop as soon as we have collected `limit` matches instead of scanning older history. if len(results) == limit: break return results def metric_store(operations: List[str], arguments: List[List]) -> List[Optional[List[Dict]]]: # Replay the sequence of record/query calls against one MetricStore instance for the judge. store = MetricStore() outputs: List[Optional[List[Dict]]] = [] for op, args in zip(operations, arguments): if op == "record": store.record(args[0], args[1], args[2], args[3]) outputs.append(None) elif op == "query": outputs.append(store.query(args[0], args[1], args[2])) else: raise ValueError(f"unknown operation: {op}") return outputs✅ Submit now — all tests should pass.
Intuition & how it works
Think of MetricStore like a cabinet of labeled file folders — one folder per metric name ("db_latency", "cache_hits"). Whenever a new observation arrives, you stamp an auto-incrementing ticket number (seq = 0, 1, 2, ...) on it and slip it into its folder in chronological order from front (oldest) to back (newest), placing tied-timestamp observations with higher ticket numbers closer to the back. When a caller asks for the limit newest observations matching certain metadata tags (key-value string labels such as {"tier": "primary"}), you open straight to that metric's folder, flip backwards from the back, and stop the instant you collect limit matching entries.
Why does the naive approach fall short? Keeping all observations in one unsorted list forces every query to scan unrelated metric names, inspect tags across the full history, and sort all matches from scratch (O(M log M)) even when limit = 2 and the two newest entries already match. Worse yet, sorting by timestamp alone with reverse=True introduces a subtle tie-breaking bug because Python uses a stable sort (a sorting algorithm that preserves the original relative order of equal-key items), leaving equal timestamps in earliest-inserted-first order instead of latest-inserted-first.
Here is a compact trace of 3 "db_latency" events followed by query("db_latency", {"tier": "primary"}, limit=2):
1. record("db_latency", 28.5, {"tier": "primary"}, ts=540) -> seq=0
2. record("db_latency", 9.0, {"tier": "replica"}, ts=590) -> seq=1
3. record("db_latency", 31.0, {"tier": "primary"}, ts=540) -> seq=2 (tie at ts=540, recorded later!)
Folder by_name["db_latency"] kept sorted ascending by (ts, seq):
[(540, 0, 28.5, {"tier":"primary"}), (540, 2, 31.0, {"tier":"primary"}), (590, 1, 9.0, {"tier":"replica"})]
Query walks right-to-left:
- (590, 1): tier="replica" != "primary" -> skip
- (540, 2): matches! -> emit val=31.0 (tie won by larger seq=2)
- (540, 0): matches! -> emit val=28.5 -> collected 2 == limit, stop!
Complexity
Let M be the number of entries stored under a single metric name, N be the total number of entries across all names, T be the number of tag pairs in a query (T <= 20), and K be the number of tag pairs on an entry (K <= 20).
recordtime:O(log M + K)when in order,O(M + K)worst case. CopyingKtags takesO(K), and binary search (bisect.insort, which repeatedly halves the sorted list to locate the insertion index) performsO(log M)comparisons. Inserting near the tail of a Python list shifts almost nothing, while inserting an old out-of-order timestamp near index0shifts up toMlist pointers inO(M).querytime:O(S * T + limit * K), whereS <= Mis how many entries from the newest end are inspected before findinglimitmatches. When recent observations match the filter,Sis close tolimit; if almost no historical entries match,Scan reachM, yet we still do a single backward pass with zero sorting.- Space:
O(N * K). Every stored entry holds one 4-tuple and its copied dictionary ofKtag pairs insideby_name.
Edge cases
- Empty query
tags({}):has_all_tagsreturnsTruefor every tag dictionary, returning up tolimitof the newest entries undername. - Unseen metric
name:name not in self.by_namereturns[]immediately without allocating an empty list. limitexceeding available matches: The backward scan reaches the front of the list and returns all matching entries found.- Exact duplicate observations: Recording the identical
(name, value, tags, timestamp)twice assigns distinctseqIDs (seqandseq + 1), keeping both observations separate. - Out-of-order timestamps: Delayed older timestamps land in their true chronological slot via
bisect.insortrather than sitting at the tail. - Case-sensitive tag values and missing keys:
{"tier": "PRIMARY"}does not match{"tier": "primary"}, and an entry lacking"az"cleanly failskey in metric_tagswithout raisingKeyError. - Caller mutating
tagsdictionaries: Copyingdict(tags)onrecordanddict(metric_tags)onqueryisolates internal storage from caller-side edits.
Common mistakes
- Sorting only by
key=lambda x: x.timestamp, reverse=True: Because Python's Timsort is stable, equal timestamps stay in ascending insertion order (earliest recorded first) instead of latest recorded first. - Omitting a unique tie-breaker before
tagsin the tuple: Comparing(timestamp, value, tags)tuples works until two entries share bothtimestampandvalue, at which point Python attemptsdict < dictand raisesTypeError. - Checking tag equality (
metric_tags == wanted_tags) instead of subset containment: Stored entries commonly carry extra dimensions like"az"or"node"not listed in the query filter and must still match. - Deduplicating with a
setor overwriting(name, timestamp)keys: Multiple observations at the same millisecond must all be preserved. - Scanning and sorting all
Mentries on everyquery: WhenM = 20,000andlimit = 3, sorting or callingheapq.nlargestinspects all20,000entries every time instead of stopping after a handful of checks from the newest end.
Alternative approaches
- Append-only list +
heapq.nlargestonquery: Appending toby_name[name]keepsrecordstrictlyO(K), whilequeryscans allMentries and maintains the toplimitin a min-heap inO(M * T + M log limit). This helps only when writes vastly outnumber reads, since queries can never terminate early. - Balanced search tree / skip list (
sortedcontainers.SortedList): GuaranteesO(log M)worst-case insertion even when timestamps arrive in reverse chronological order, avoiding Pythonlistpointer shifts at massive scale.
Follow-up questions
- Suppose a single metric name accumulates millions of points and callers regularly filter on selective tag pairs—how would you index the data to avoid linear tag scans? Maintain a per-name inverted index (a lookup table mapping each
(tag_key, tag_value)pair to the sorted list of entry IDs carrying that label). On a multi-tag query, fetch the posting list for each requested(key, value)pair — returning[]immediately if any pair is absent — and scan backwards through the shortest posting list while verifying the remaining tags. Production time-series engines like Prometheus go further by interning each unique full tag map as an integerseries_id, intersectingseries_idsets via inverted indexes, and merging the newest points across matching series with a small max-heap. - When incoming timestamps are mostly monotonic with only occasional slightly delayed events, how can you keep writes and top-k recent reads fast without re-sorting full histories? Keep entries ordered at ingestion time just as
bisect.insortdoes: whenever a new timestamp is>=the tail element (entries[-1][0]), appending at the end runs inO(1)amortized time, and slightly delayed arrivals only shift the few newer items near the tail. Reads then walk backwards from the end and stop afterlimitmatches without sorting. If rare stragglers arrive hours late, you can keep the primary buffer strictly append-only for monotonic points and hold out-of-order stragglers in a small sorted side buffer merged at read time. - How would you support automatic expiration of observations older than a configurable retention window without causing latency spikes on reads or writes? Partition each metric's history into fixed-width time buckets (for instance, one sorted list per 5-minute window) rather than one monolithic array, where the retention window (time-to-live / TTL) defines the maximum age an observation remains valid. Expiring old data then drops whole expired buckets in
O(1)time via a background sweeper or lazily everyNwrites, never shifting millions of surviving entries. Between sweeps,querystays exact and fast by halting its backward scan the instant it reaches an entry older than the cutoff timestamp.
Follow-up questions
- Suppose a single metric name accumulates millions of points and callers regularly filter on selective tag pairs—how would you index the data to avoid linear tag scans?
- When incoming timestamps are mostly monotonic with only occasional slightly delayed events, how can you keep writes and top-k recent reads fast without re-sorting full histories?
- How would you support automatic expiration of observations older than a configurable retention window without causing latency spikes on reads or writes?
Similar questions
- Five-Minute Sliding Hit Counter
- Bottom-Up Tree Height Layers
- Real-Time Multi-User Document Editing Service
- Scalable URL Shortening and Edge Redirect System
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger