Monitor Concurrent Simulations for Idle Timeouts
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a stateful SimulationMonitor class that tracks thousands of concurrent simulation runs from an incoming stream of timestamped activity records and reports runs that go silent past a fixed idle threshold.
class SimulationMonitor:
def __init__(self, timeout: int): ...
def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]: ...
def is_active(self, sim_id: Hashable) -> bool: ...
def active_count(self) -> int: ...
Constructor & Query Methods
SimulationMonitor(timeout): Configure the idle thresholdtimeout(timeout >= 0, measured in the same integer time units as event timestamps). RaiseValueErroriftimeout < 0.is_active(sim_id): ReturnTrueifsim_idcurrently has an open run that has neither finished normally nor expired, andFalseotherwise.active_count(): Return how many simulations are currently active.
Event Processing Rules (process_event)
Valid calls arrive in monotonically non-decreasing timestamp order (timestamp >= previous_timestamp), with event_type equal to "start", "ping", or "end":
- Validate before mutating: If
event_typeis unrecognized ortimestampis strictly less than the most recently accepted event's timestamp, raiseValueErrorimmediately while leaving all internal monitor state untouched. - Apply the incoming event at
timestamp:"start": Markssim_idactive with its latest activity time set totimestamp. Ifsim_idhad previously finished or timed out, this opens a brand-new run; ifsim_idis already active, this refreshes its latest activity time totimestamp."ping": Updatessim_id's latest activity time totimestampifsim_idis currently active; ignored ifsim_idis not active."end": Closessim_idnormally so it is no longer active; ignored ifsim_idis not active.
- Collect newly expired runs: After applying the event, every currently active simulation satisfying the strict inequality
timestamp - last_activity > timeoutexpires:- Remove each expired simulation from the active set so that run is never reported a second time (and any later
"ping"or"end"for that finished run is ignored unless a fresh"start"arrives). - Return the newly expired
sim_idvalues ordered from oldestlast_activityto newest, breaking ties by the order in which thoselast_activityupdates were recorded.
- Remove each expired simulation from the active set so that run is never reported a second time (and any later
Examples
Example 1
monitor = SimulationMonitor(timeout=5)
monitor.process_event("sim_x", "start", 10) # -> []
monitor.process_event("sim_y", "start", 12) # -> []
monitor.process_event("sim_x", "ping", 14) # -> []
monitor.process_event("sim_z", "start", 19) # -> ["sim_y"]
monitor.process_event("sim_z", "ping", 20) # -> ["sim_x"]
monitor.process_event("sim_x", "ping", 21) # -> [] (ignored; sim_x is inactive)
monitor.process_event("sim_z", "end", 22) # -> [] (active_count() == 0)
Walk-through:
- "sim_x" starts at 10, "sim_y" starts at 12, and "sim_x" refreshes its activity to 14.
- At t = 19, "sim_y" has been silent for 19 - 12 = 7 > 5 and is returned, whereas "sim_x" has been silent for 19 - 14 = 5 <= 5 and remains active because expiration requires strict >.
- At t = 20, "sim_x" reaches idle duration 20 - 14 = 6 > 5 and expires. Its late "ping" at 21 is ignored, and "sim_z" closes cleanly at 22.
Example 2
monitor = SimulationMonitor(timeout=4)
monitor.process_event("run_b", "start", 2) # -> []
monitor.process_event("run_a", "start", 2) # -> []
monitor.process_event("run_c", "start", 3) # -> []
monitor.process_event("run_d", "start", 8) # -> ["run_b", "run_a", "run_c"]
monitor.process_event("run_b", "start", 9) # -> [] (active_count() == 2)
Walk-through:
At t = 8, "run_b", "run_a", and "run_c" all exceed timeout = 4 (6 > 4 and 5 > 4). "run_b" and "run_a" share last_activity = 2 and are emitted in arrival order ("run_b" first), followed by "run_c". Calling "start" on "run_b" at t = 9 launches a new active run alongside "run_d".
Constraints
timeout >= 0(ValueErroron negative values).sim_idcan be any hashable value (strings and integers may appear together in the same monitor, sosim_idvalues may not be mutually comparable with<).- Accepted
timestampintegers are monotonically non-decreasing across calls. - Because the monitor runs continuously over large streams, aim for
O(1)amortized (orO(log n)) time per event andO(n)memory proportional only to the number of currently active runsn.
Step-by-step walkthrough
Clarify the rules and event-processing order
We are building a stateful
SimulationMonitor(timeout)that ingests activity tuples(sim_id, event_type, timestamp)one by one in non-decreasing timestamp order:monitor = SimulationMonitor(timeout=5) monitor.process_event(sim_id, event_type, timestamp) -> list of newly expired sim_idsBefore writing code, let's lock down every boundary detail:
- Apply the incoming event first, then sweep for expirations: An active simulation sending a
"ping"after a quiet stretch updates its ownlast_activitytotimestampbefore the expiration sweep runs (so it stays alive), and a"end"closes that run cleanly rather than flagging it as expired. (If a variant asked to expire before applying the incoming event, you would simply call_expire(timestamp)ahead of_apply(...).) - Strict inequality (
>): A run expires only whentimestamp - last_activity > timeout. Withtimeout = 5andlast_activity = 14, an event at19(19 - 14 = 5) leaves the run active; an event at20(20 - 14 = 6) expires it. - Single-report guarantee: Once expired, the run leaves the active set so subsequent events never report that run again.
- Ignore
"ping"or"end"on inactive IDs: Late heartbeats or duplicate"end"calls for runs that never started, already closed, or already expired must not revive them. - Restarting via
"start": Sending"start"for an inactivesim_idlaunches a fresh run; sending"start"for an already-activesim_idrefreshes itslast_activityjust like a"ping". - Deterministic tie-breaking & validation: Return expired IDs from oldest
last_activityto newest (ties broken by activity arrival order), and raiseValueErrorbefore mutating state ifevent_typeis unrecognized ortimestampdecreases.
- Apply the incoming event first, then sweep for expirations: An active simulation sending a
Why scanning every active simulation is too slow
A naive monitor keeps a plain dictionary
last_activity[sim_id] = timestampand loops across every active run after each call to testtimestamp - last > timeout.That makes a simple reference oracle for tests, but each call costs
O(n)time acrossnconcurrent runs. With100,000active runs and1,000,000events, full scans perform up to100,000,000,000checks — almost all wasted re-inspecting runs that just reported activity. Only runs with the oldestlast_activitycan crosstimeoutfirst!First good design: hash map plus a min-heap (O(log H))
A classic priority-queue approach pairs two structures:
- Hash map
latest[sim_id]storing the sequence number of each active run's newest activity (O(1)lookup). - Min-heap — a binary tree in an array keeping the smallest
(last_activity, seq, sim_id)tuple at index0inO(log H)time per push or pop.
Because moving an arbitrary node inside a binary heap is awkward, each
"ping"pushes a fresh tuple onto the heap and leaves old tuples behind (lazy deletion — discarding outdated entries later when they surface at index0).That achieves
O(log H), though one noisy simulation pinging every millisecond inside a5-second window can pile5,000stale entries into the heap (H >> n). Can we use monotonic timestamps to getO(1)updates and zero stale entries?- Hash map
Key insight: monotonic timestamps turn the heap into an O(1) queue
Notice what every
"start"or active"ping"setslast_activityto: the current event'stimestamp. Because accepted timestamps never decrease (ts_1 <= ts_2 <= ts_3 <= ...), whichever simulation is touched right now always receives alast_activitygreater than or equal to every other active simulation!That means "ordered from oldest
last_activityto newest" is identical to "ordered from least-recently touched to most-recently touched"! Instead of a heap, we only need an ordered dictionary supporting threeO(1)operations:Front (oldest activity) Back (newest activity) | | v v [ "sim_y": 12 ] <------> [ "sim_x": 14 ] <------> [ "sim_z": 19 ] ^ ^ _expire() peeks and hash table jumps directly to pops ONLY at the front! any sim_id to delete or move_to_end!"start"or active"ping": setsim_id's timestamp and move its node to the back inO(1)."end": unlinksim_idfrom wherever it sits inO(1).- Expiration sweep: peek at the front; while
now - oldest_time > timeout, pop the front inO(1); the instantnow - oldest_time <= timeout, stop immediately because every entry behind it is at least as recent!
Python's
collections.OrderedDictwires a hash table to a doubly linked list in C (the exact structure behind an LRU cache), giving us all three operations out of the box.Implement state, validation, and event updates
Our state consists of
self.timeout,self.current_time, and oneOrderedDictnamedself.last_activity. Pay attention to two engineering details:- Bounded
O(n)memory for long-running processes: Whenever a run finishes or expires, we remove its key fromself.last_activity. Because_applyignores"ping"and"end"wheneversim_id not in self.last_activity, we never accumulate a historical graveyard of finished IDs! - Explicit
move_to_end(sim_id): Overwriting an existing key inOrderedDict(self.last_activity[sim_id] = timestamp) leaves that key at its old linked-list position! Callingself.last_activity.move_to_end(sim_id)immediately afterward moves the refreshed run to the back.
from typing import Hashable, List from collections import OrderedDict class SimulationMonitor: """Tracks concurrent simulations and reports runs whose idle time exceeds timeout.""" VALID_TYPES = ("start", "ping", "end") def __init__(self, timeout: int): if timeout < 0: raise ValueError("timeout must be >= 0") self.timeout = timeout # Timestamp of the most recently accepted event (None before the first event). self.current_time = None # self.last_activity: OrderedDict mapping active sim_id -> last_activity_timestamp, # ordered from oldest activity at the front to newest activity at the back, # e.g. OrderedDict([("B", 1), ("A", 2)]). self.last_activity = OrderedDict() def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]: # Phase 1: validate input BEFORE mutating state so rejected calls change nothing. if event_type not in self.VALID_TYPES: raise ValueError("unknown event type: " + repr(event_type)) if self.current_time is not None and timestamp < self.current_time: raise ValueError("timestamps must not decrease") # Phase 2: advance the monitor clock and apply the incoming event. self.current_time = timestamp self._apply(sim_id, event_type, timestamp) # Phase 3: pop and report every active simulation that is now strictly past timeout. return self._expire(timestamp) def _apply(self, sim_id: Hashable, event_type: str, timestamp: int) -> None: if event_type == "end": # Normal completion: remove if active; ignore if unknown or already finished. self.last_activity.pop(sim_id, None) return if event_type == "ping" and sim_id not in self.last_activity: # Ignore pings for runs that never started, already ended, or already timed out. return # Either a "start" (new or active run) or a "ping" on an active run. # Because timestamps never decrease, `timestamp` is >= every value in the dict, # so moving `sim_id` to the back preserves sorted oldest-to-newest order. self.last_activity[sim_id] = timestamp self.last_activity.move_to_end(sim_id)- Bounded
Implement the front-to-back timeout sweep
Inside
_expire(self, now),next(iter(self.last_activity.items()))inspects the front(oldest_sim_id, oldest_time)pair inO(1)time:- If
now - oldest_time <= self.timeout, the oldest active run is still within the threshold — and every run behind it haslast_activity >= oldest_time, so webreakright away. - Otherwise
now - oldest_time > self.timeout, soself.last_activity.popitem(last=False)removes the front run inO(1)and appendsoldest_sim_idtotimed_out.
def _expire(self, now: int) -> List[Hashable]: timed_out: List[Hashable] = [] while self.last_activity: # Peek at the front entry, which always has the oldest last_activity timestamp. oldest_sim_id, oldest_time = next(iter(self.last_activity.items())) # Timeout requires strict `>` (idle for exactly `timeout` is still alive). if now - oldest_time <= self.timeout: # Every entry behind the front was touched at `>= oldest_time`, so stop here. break self.last_activity.popitem(last=False) timed_out.append(oldest_sim_id) return timed_out def is_active(self, sim_id: Hashable) -> bool: return sim_id in self.last_activity def active_count(self) -> int: return len(self.last_activity)Each started run enters
self.last_activityonce and is popped at most once, so acrossmevents the total work inside_expireis bounded byO(m)—O(1)amortized per event!- If
Walk through Example 1 step by step
Let's trace
timeout = 5across all 7 calls in Example 1, showingself.last_activityfrom front (oldest) to back (newest):Event After _apply Front checks in _expire Returned Queue after ---------------------------------------------------------------------------------------------------------------------- sim_x start 10 [sim_x:10] 10 - 10 = 0 <= 5 -> stop [] [sim_x:10] sim_y start 12 [sim_x:10, sim_y:12] 12 - 10 = 2 <= 5 -> stop [] [sim_x:10, sim_y:12] sim_x ping 14 [sim_y:12, sim_x:14] (moved!) 14 - 12 = 2 <= 5 -> stop [] [sim_y:12, sim_x:14] sim_z start 19 [sim_y:12, sim_x:14, sim_z:19] 19 - 12 = 7 > 5 -> pop sim_y; ['sim_y'] [sim_x:14, sim_z:19] 19 - 14 = 5 <= 5 -> stop (strict >!) sim_z ping 20 [sim_x:14, sim_z:20] 20 - 14 = 6 > 5 -> pop sim_x; ['sim_x'] [sim_z:20] 20 - 20 = 0 <= 5 -> stop sim_x ping 21 [sim_z:20] (inactive, ignored) 21 - 20 = 1 <= 5 -> stop [] [sim_z:20] sim_z end 22 [] queue empty [] []At
t = 19,sim_xhas been silent for19 - 14 = 5 == timeout, so strict>keepssim_xactive untilt = 20, and att = 21its late"ping"is ignored cleanly.Complete solution
from typing import Hashable, List from collections import OrderedDict class SimulationMonitor: """Tracks concurrent simulations and reports runs whose idle time exceeds timeout.""" VALID_TYPES = ("start", "ping", "end") def __init__(self, timeout: int): if timeout < 0: raise ValueError("timeout must be >= 0") self.timeout = timeout # Timestamp of the most recently accepted event (None before the first event). self.current_time = None # self.last_activity: OrderedDict mapping active sim_id -> last_activity_timestamp, # ordered from oldest activity at the front to newest activity at the back, # e.g. OrderedDict([("B", 1), ("A", 2)]). self.last_activity = OrderedDict() def process_event(self, sim_id: Hashable, event_type: str, timestamp: int) -> List[Hashable]: # Phase 1: validate input BEFORE mutating state so rejected calls change nothing. if event_type not in self.VALID_TYPES: raise ValueError("unknown event type: " + repr(event_type)) if self.current_time is not None and timestamp < self.current_time: raise ValueError("timestamps must not decrease") # Phase 2: advance the monitor clock and apply the incoming event. self.current_time = timestamp self._apply(sim_id, event_type, timestamp) # Phase 3: pop and report every active simulation that is now strictly past timeout. return self._expire(timestamp) def _apply(self, sim_id: Hashable, event_type: str, timestamp: int) -> None: if event_type == "end": # Normal completion: remove if active; ignore if unknown or already finished. self.last_activity.pop(sim_id, None) return if event_type == "ping" and sim_id not in self.last_activity: # Ignore pings for runs that never started, already ended, or already timed out. return # Either a "start" (new or active run) or a "ping" on an active run. # Because timestamps never decrease, `timestamp` is >= every value in the dict, # so moving `sim_id` to the back preserves sorted oldest-to-newest order. self.last_activity[sim_id] = timestamp self.last_activity.move_to_end(sim_id) def _expire(self, now: int) -> List[Hashable]: timed_out: List[Hashable] = [] while self.last_activity: # Peek at the front entry, which always has the oldest last_activity timestamp. oldest_sim_id, oldest_time = next(iter(self.last_activity.items())) # Timeout requires strict `>` (idle for exactly `timeout` is still alive). if now - oldest_time <= self.timeout: # Every entry behind the front was touched at `>= oldest_time`, so stop here. break self.last_activity.popitem(last=False) timed_out.append(oldest_sim_id) return timed_out def is_active(self, sim_id: Hashable) -> bool: return sim_id in self.last_activity def active_count(self) -> int: return len(self.last_activity)✅ Submit now — all tests should pass.
Intuition & how it works
Picture a row of folders on a desk — one folder per currently running simulation — ordered left to right from longest untouched to most recently touched. Because event timestamps never go backwards, any simulation that starts or pings right now automatically gets the newest timestamp on the desk, so you simply pull its folder out and place it at the far right end! When a simulation finishes ("end"), you remove its folder completely. And when checking which runs have been silent strictly longer than timeout (current_time - last_activity > timeout), you only ever inspect the leftmost folder: pop folders from the left while they are expired, and stop the instant the leftmost folder is still within timeout because every folder to its right was touched even more recently.
Why do simpler designs fall short? Keeping an unordered dictionary and scanning all n active simulations on every call costs O(n) time per event — far too slow when 100,000 concurrent runs emit millions of pings. Even a min-heap (a binary tree in an array that exposes its smallest item at index 0 in O(log H) time) does extra work here: because you cannot cheaply reposition a node inside a heap on every ping, you must push duplicate entries and skip stale ones later, paying O(log H) time and holding stale entries in RAM. Python's OrderedDict — a hash table wired to a doubly linked list (a chain of nodes with prev/next links so any node can be unlinked or moved to the back in O(1) time, just like an LRU cache) — gives O(1) updates and zero stale entries!
Let's trace the first 5 events of Example 1 with timeout = 5 (oldest on the left, newest on the right):
1. ("sim_x", "start", 10) -> [sim_x:10] 10 - 10 = 0 <= 5 -> []
2. ("sim_y", "start", 12) -> [sim_x:10, sim_y:12] 12 - 10 = 2 <= 5 -> []
3. ("sim_x", "ping", 14) -> [sim_y:12, sim_x:14] sim_x moves to back -> []
4. ("sim_z", "start", 19) -> [sim_y:12, sim_x:14, sim_z:19] 19 - 12 = 7 > 5 (pop sim_y);
19 - 14 = 5 <= 5 (stop!) -> ["sim_y"]
5. ("sim_z", "ping", 20) -> [sim_x:14, sim_z:20] 20 - 14 = 6 > 5 (pop sim_x) -> ["sim_x"]
Complexity
Let n be the number of currently active simulations, k be the number of newly expired simulation IDs returned by the current call, and m be the total number of events processed over time.
- Time per
process_event:O(1 + k)average (O(1)amortized — meaning the average cost per event acrossmevents is constant). Updating or removingsim_idinOrderedDicttakesO(1)average hash-table + linked-list work, and_expireperforms oneO(1)front peek that terminates the loop pluskO(1)front pops. Because each started run enters the queue once and is popped at most once, total pops acrossmevents never exceedm. - Time for
is_activeandactive_count:O(1)average hash membership check andO(1)length lookup. - Space complexity:
O(n). Both closed and expired runs are removed immediately fromself.last_activity, keeping memory bounded strictly by live concurrent runs rather than growing forever in a long-lived service.
Edge cases
- Silent for exactly
timeout(now - last == timeout): Still alive because expiration uses strict>. In Example 1 (timeout = 5,sim_xtouched at14),t = 19leavessim_xactive whilet = 20expires it. - Zero threshold (
timeout = 0): Valid boundary — runs survive other events at the exact same timestamp (now - last == 0) and expire on the very next strictly larger timestamp. - Activity arriving after a long quiet gap for that same
sim_id: Because_applyruns ahead of_expire, a"ping"refreshes its own run before the sweep and an"end"closes it cleanly without reporting an expiration, while any other stale runs expire on that call. - Late
"ping"or"end"after expiration or normal"end":sim_idis absent fromself.last_activity, so the call is ignored — an expired run is never revived or reported twice. - Restarting a finished
sim_id: A fresh"start"insertssim_idat the back as an independent new run. - Mixed
sim_idtypes (e.g.,7and"a"):OrderedDicthashes keys without comparingid_1 < id_2, avoidingTypeError. - Unrecognized event type or decreasing timestamp: Checked before mutating
self.current_timeorself.last_activity, keeping state completely intact.
Common mistakes
- Assigning
self.last_activity[sim_id] = timestampwithoutmove_to_end(sim_id): Overwriting an existing key's value inOrderedDictleaves its linked-list node near the front, causing a freshly pinged run to be falsely expired or block older runs behind it! - Checking
>=instead of>:now - oldest_time >= self.timeoutprematurely expires runs whose idle duration equalstimeout. - Maintaining a permanent
expired_idsset: Saving every historical expired ID to reject late pings leaks memory unboundedly in a long-lived daemon; checkingsim_id not in self.last_activitygives the exact same behavior inO(n)live space. - Updating
self.current_timebefore validating inputs: Ifprocess_event("sim_x", "bad_kind", 999999)mutatesself.current_timebefore raisingValueError, every subsequent valid call at normal timestamps falsely fails the monotonic check. - Pushing
(timestamp, sim_id)tuples intoheapqwithout a tie-breaker: Equal timestamps force Python to comparesim_idvalues directly, raisingTypeErrorwhen strings and integers mix. Always include a unique monotonic counter(timestamp, seq, sim_id).
Alternative approaches
- Hash map + min-heap with lazy deletion (
O(log H)per event): Needed whenever expiration order differs from touch order (such as per-simulation custom thresholds). Lazy deletion pushes a fresh(deadline, seq, sim_id)tuple on every ping instead of mutating old heap entries in place, ignoring outdated tuples when popped ifseq != latest.get(sim_id). - Balanced binary search tree (
SortedList/TreeMap): Keeps exactly one(last_activity, seq, sim_id)entry per active run, removing the old tuple and inserting the new tuple inO(log n)worst-case time while keeping space strictlyO(n). - Hierarchical timing wheel: Hashes runs into circular array buckets indexed by integer timestamp ticks, sweeping expired slots in
O(1)per tick when timestamps advance smoothly.
Follow-up questions
- How would the data structures change if every simulation declared its own custom timeout threshold upon starting? A run touched at
t = 14withtimeout = 2(deadline16) expires sooner than one touched att = 10withtimeout = 10(deadline20), so touch order no longer matches expiration order! ReplaceOrderedDictwith a min-heap using lazy deletion (or a balanced BST) keyed by(timestamp + timeout_i, seq, sim_id)alongside an active dictionary storing each run'stimeout_iand latestseq, achievingO(log H)(orO(log n)) per event. - How could the service report expired simulations promptly during quiet intervals when no new events arrive? Add a background timer task driven by a monotonic clock (
time.monotonic()). Have the timer sleep until the earliest active deadline (oldest_time + timeout + 1), wake to run_expire(clock_now)and emit any expired IDs, and guardself.last_activitywith a mutex (or route both incoming events and timer ticks through a single-threaded event loop). - How would you adapt this design if network delays caused events to arrive slightly out of timestamp order? Track a watermark — a delayed progress clock
watermark = max_timestamp_seen - max_latenessguaranteeing that nearly all packets older thanwatermarkhave already arrived. Hold active runs in a deadline min-heap where each ping updateslast_activity[sim_id] = max(last_activity[sim_id], event.timestamp)(so a delayed packet never overwrites a newer ping), and trigger expirations only whenwatermark - last_activity > timeout.
Follow-up questions
- How would the data structures change if every simulation declared its own custom timeout threshold upon starting?
- How could the service report expired simulations promptly during quiet intervals when no new events arrive?
- How would you adapt this design if network delays caused events to arrive slightly out of timestamp order?
Similar questions
- Indexed Deduplication of 3D Vertices
- Transactional Key-Value Store with Arbitrary Nesting
- In-Memory Key-Value Store with Nested Transactions
- Resolve Arithmetic Assignments with Forward References
- Dependency-Ordered Variable Evaluator
- Group Files with Matching Byte Sizes
More Applied Intuition interview questions
- In-Memory Key-Value Store with Nested Transactions Medium
- Company Mission Alignment and Academic-to-Career Decision History Medium
- Sensor Run Ingestion Store and Time-Indexed Query Service Medium Pro
- Two-Hour Prototype and Presentation of a 3D Vehicle Log Player Medium Pro
- Separating Syntax Parsing from Type Resolution in Message Schemas Medium Pro
- Transactional Key-Value Store with Arbitrary Nesting Medium Pro
- Interactive 3D Replay Architecture for Autonomous Vehicle Drive Logs Medium Pro
- Production Architecture for a Distributed Heartbeat Timeout Detector Hard Pro
- Resolve Arithmetic Assignments with Forward References Medium Pro
- Pinpoint Grid Vehicles via Square-Region Queries Medium Pro