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:

  1. "record" with [name, value, tags, timestamp]:
    • Appends the observation to the store and produces None in the output list.
    • Identical observations—even sharing the exact same name, value, tags, and timestamp—are kept as distinct entries rather than deduplicated.
  2. "query" with [name, tags, limit]:
    • Finds stored observations whose name equals the requested name and whose tags map contains every (key, value) pair present in the query's tags filter. Extra keys on a stored observation are allowed, and an empty filter {} matches every tag map under name.
    • Orders matching observations by timestamp from largest to smallest (newest first). Whenever two matching observations have the same timestamp, the one ingested by a later "record" call comes first.
    • Returns at most limit matching observations (or all matches if fewer than limit exist), each formatted as {"name": str, "value": float, "tags": dict[str, str], "timestamp": int}.

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 name has length 1 <= len(name) <= 100 and contains only ASCII letters, digits, and underscores (_).
  • Every tags dictionary has 0 <= len(tags) <= 20 string keys and string values.
  • 1 <= timestamp <= 2^63 - 1, with no guarantee of chronological arrival order.
  • 1 <= limit <= 1000 for every "query" operation.

Step-by-step walkthrough

  1. Understand the operations and ordering rules

    We need an in-memory MetricStore that 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 same name, value, tags, and timestamp, both are retained as separate entries.
    • query(name, tags, limit): Returns up to limit stored entries under name whose tags include every (key, value) pair requested by the query's tags filter:
      • Additional keys on the stored entry are allowed ({"tier": "primary", "az": "usw1"} matches query {"tier": "primary"}).
      • An empty filter {} matches every entry stored under name.
    • Sorting and tie-breaking:
      1. Primary order: timestamp descending (largest timestamp first).
      2. Tie-breaker: insertion order descending (when two entries share the same timestamp, the one ingested later comes first).

    Timestamps can arrive out of chronological order, and metric_store(operations, arguments) replays a sequence of "record" and "query" commands against one shared MetricStore.

  2. Why filtering and sorting everything per query is too slow

    A naive implementation appends every observation into one flat list, and on each query scans the whole list, checks name and tags, sorts all matches from scratch, and slices [:limit].

    With up to 50,000 operations, consider 25,000 "db_latency" writes followed by 25,000 queries with limit = 2. Scanning unrelated metric names and sorting 25,000 entries 25,000 times performs hundreds of millions of comparisons — even though previously stored entries never change relative order and limit = 2 only needs the two newest matches!

  3. 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:

    1. Bucket by name in a dictionary (by_name): A query for "db_latency" looks up by_name["db_latency"] directly and skips every other metric name.
    2. Keep each bucket sorted ascending as (timestamp, seq, value, tags_copy): Assign each record call an increasing integer seq = 0, 1, 2, ..., and insert into the list with bisect.insort (which binary-searches for the sorted index and inserts there).
    3. Walk backwards with reversed(...) and stop at limit: 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 seq
    

    Reading from right to left yields exact (timestamp DESC, seq DESC) order with zero sorting during query, allowing us to break as soon as we collect limit matches!

    Placing seq at tuple index 1 also prevents a subtle Python crash: tuple comparison proceeds left to right and stops at the first differing element. Because every entry gets a unique seq, Python never attempts dict < dict on tags (which would raise TypeError).

  4. Write the subset tag-matching helper

    A stored entry satisfies wanted_tags when every (key, value) pair in wanted_tags appears in metric_tags with the identical value. If wanted_tags has more keys than metric_tags, we can return False immediately; if wanted_tags is {}, the loop completes immediately and returns True.

    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
    
  5. Implement `MetricStore.record`

    Each record call copies dict(tags) defensively (so caller mutations afterwards cannot alter stored history), packs (timestamp, self.next_seq, value, dict(tags)), increments self.next_seq, and inserts into self.by_name[name] using bisect.insort.

    Whenever timestamps arrive roughly in order, bisect.insort places 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)
    
  6. Implement `MetricStore.query` and the judge wrapper

    query returns [] immediately if name has never been recorded, otherwise iterates reversed(self.by_name[name]) (creating an O(1) reverse iterator without copying the list). Each matching entry is emitted with a fresh copy of metric_tags, and iteration stops once len(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 results
    
  7. Trace Example 1 step by step

    Let's trace the four "record" calls from Example 1 (seq = 0, 1, 2, 3), where seq = 3 arrives with timestamp = 540 after seq = 2 at timestamp = 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 the az = "use1" reading (val = 28.5, seq = 1) at timestamp 540 because it was recorded later.

  8. 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).

  • record time: O(log M + K) when in order, O(M + K) worst case. Copying K tags takes O(K), and binary search (bisect.insort, which repeatedly halves the sorted list to locate the insertion index) performs O(log M) comparisons. Inserting near the tail of a Python list shifts almost nothing, while inserting an old out-of-order timestamp near index 0 shifts up to M list pointers in O(M).
  • query time: O(S * T + limit * K), where S <= M is how many entries from the newest end are inspected before finding limit matches. When recent observations match the filter, S is close to limit; if almost no historical entries match, S can reach M, 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 of K tag pairs inside by_name.

Edge cases

  • Empty query tags ({}): has_all_tags returns True for every tag dictionary, returning up to limit of the newest entries under name.
  • Unseen metric name: name not in self.by_name returns [] immediately without allocating an empty list.
  • limit exceeding 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 distinct seq IDs (seq and seq + 1), keeping both observations separate.
  • Out-of-order timestamps: Delayed older timestamps land in their true chronological slot via bisect.insort rather 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 fails key in metric_tags without raising KeyError.
  • Caller mutating tags dictionaries: Copying dict(tags) on record and dict(metric_tags) on query isolates 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 tags in the tuple: Comparing (timestamp, value, tags) tuples works until two entries share both timestamp and value, at which point Python attempts dict < dict and raises TypeError.
  • 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 set or overwriting (name, timestamp) keys: Multiple observations at the same millisecond must all be preserved.
  • Scanning and sorting all M entries on every query: When M = 20,000 and limit = 3, sorting or calling heapq.nlargest inspects all 20,000 entries every time instead of stopping after a handful of checks from the newest end.

Alternative approaches

  • Append-only list + heapq.nlargest on query: Appending to by_name[name] keeps record strictly O(K), while query scans all M entries and maintains the top limit in a min-heap in O(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): Guarantees O(log M) worst-case insertion even when timestamps arrive in reverse chronological order, avoiding Python list pointer 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 integer series_id, intersecting series_id sets 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.insort does: whenever a new timestamp is >= the tail element (entries[-1][0]), appending at the end runs in O(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 after limit matches 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 every N writes, never shifting millions of surviving entries. Between sweeps, query stays exact and fast by halting its backward scan the instant it reaches an entry older than the cutoff timestamp.

Follow-up questions

Similar questions

More Vercel interview questions

All 5 Vercel questions →