Multi-Device Login Burst Detector over a Late-Tolerant Stream
Data Structure DesignModel answerLast updated
Design a streaming detector that flags users with 4 or more distinct devices logging in successfully within 10 minutes, tolerating events up to 30 seconds late, with bounded memory.
Multi-Device Login Burst Detector
You are building part of an account-takeover monitor. Login events arrive as a stream of tuples:
(user_id, ts, device_id, success)
ts is the event time in seconds. The stream is roughly sorted by ts, but any event may arrive up to 30 seconds late relative to the newest timestamp seen so far.
Write a function process_logins(stream) that yields an alert
(user_id, window_start_ts, window_end_ts, distinct_devices)
whenever a user has successful logins from at least 4 distinct device_ids within a 10-minute sliding window.
Constraints
- Memory is O(U · K), where U is the number of active users and K is the number of distinct devices a user has used in the last 10 minutes.
- Events up to 30 seconds late must be handled correctly.
- Amortized time per event is between O(1) and O(log K).
What to cover
A. Data structures and eviction. Describe the per-user state, the global state, and how old data is removed. Explain why your choice satisfies the memory bound even if a user logs in hundreds of times from one device.
B. Late events. Explain how you accept late events and still avoid emitting duplicate alerts for the same burst.
C. Exact semantics and code. Give Python-like code and state precisely:
- whether the window boundaries are inclusive or exclusive,
- which events count toward the distinct-device total,
- how often a continuing burst alerts,
- what happens to events later than 30 seconds.
Hints
Hint 1
Separate the problem into two layers: one that restores timestamp order (using the 30-second tolerance), and one that does a simple sliding window over events already in order.
Hint 2
Storing one entry per login breaks the O(K) bound. Keep only the latest success time per device for each user, in an insertion-ordered map where re-seen devices move to the back.
Hint 3
Define a watermark equal to the newest timestamp minus 30 seconds. Release buffered events at or below it in (ts, arrival) order. To avoid repeat alerts, give each user an armed or disarmed flag that resets only when the count falls below 4.
Hint 4
Do not forget users who go quiet. Their state must be swept out as the watermark advances, otherwise memory grows with every user ever seen.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into two layers so that each stays simple.
- Reorder buffer with a watermark. It absorbs lateness and releases events in event-time order.
- Per-user in-order window. It never sees disorder, so its logic is deterministic and easy to prove.
Layer 1: reorder buffer
- Track
newest, the largest timestamp seen on any event, including failed logins. - The watermark is
newest - 30. No legal future event can have a timestamp below it. - Successful events are pushed onto a min-heap keyed by
(ts, arrival_seq). Whenever the watermark advances, pop and process everything withts <= watermark. - An event with
ts < newest - 30is beyond the lateness bound. Drop it, or route it to a side output for auditing. It must never reach the detector, because that would break the ordering guarantee. - At end of stream, drain the heap completely.
Because the watermark never decreases and accepted events satisfy ts >= newest - 30, the sequence handed to the detector is non-decreasing in ts. Ties are broken by arrival order, so output is reproducible.
Layer 2: per-user window state
The obvious design is a deque of events plus a device -> count map. It stores one entry per login, so a user who logs in 500 times from one phone uses 500 slots, which violates O(K).
A better structure is an insertion-ordered map device_id -> latest success ts:
- On a login, remove any old entry for that device and re-insert it at the back with the new timestamp. Since processing is in time order, the map stays sorted by timestamp from front to back.
- Before handling an event at time
t, evict from the front whilefront_ts < t - 600. - The number of distinct devices is
len(map), available in O(1).
Each user holds exactly K entries, so total state is O(U·K), plus O(B) for the heap, where B is the events arriving in roughly 30 seconds.
Idle users. Keep a second ordered map user -> last processed ts. After each watermark advance, drop users from the front while last_ts < watermark - 600. Every future event has ts >= watermark, so such a user's window would be empty anyway. Without this sweep, memory grows with every user ever seen.
Exact semantics
- Window. For a triggering event at time
t, the window is the closed interval[t - 600, t]. A device last seen at exactlyt - 600still counts. Eviction therefore uses the strict testts < t - 600. - Alert payload.
(user, t - 600, t, len(map)), emitted when the triggering event is processed. - Which events count. Only
success == Trueevents add devices. Failed logins still advancenewestand therefore the watermark. - One alert per episode. Each user starts armed. When the count first reaches 4, emit an alert and disarm. Re-arm only after eviction takes the count below 4. A 5th or 6th device in the same burst does not alert again. A count that goes 4, then 3, then 4 again is a new episode and alerts again.
- Late beyond 30 s. Dropped deterministically.
Why late events cannot cause duplicates
The detector sees every event exactly once, in order, so each burst is evaluated once. Nothing needs to be retracted or back-dated.
The alternative is to evaluate immediately and patch the window when a late event shows up. A late event could complete a window that was already passed over, forcing an out-of-order alert. Or the same four devices could be detected from two directions. The price of buffering is that alerts lag real time by up to about 30 seconds, which is normally acceptable for fraud signals and worth saying explicitly.
If zero latency is required, a speculative variant emits immediately and keeps alerted_until[user], suppressing any alert whose window overlaps one already sent. It is more complex and depends on arrival order, so mention it only as a trade-off.
Correctness sketch
- No misses. Take any window with at least 4 distinct successful devices and let
tbe its latest login. When the event attis processed, each of those devices has a stored timestamp in[t - 600, t], because stored timestamps are only ever refreshed upward and nothing later thanthas been processed. Solen(map) >= 4, and either an alert fires or the user is already inside an active episode. - No false alerts. After eviction, every entry has
ts >= t - 600, so a count of 4 or more is itself a witness of a real qualifying window.
Complexity
- Heap push and pop: O(log B).
- Window update: amortized O(1), since each device entry is inserted and evicted once per appearance.
- Idle sweep: amortized O(1).
- To get strictly O(log K), keep a small reorder heap per user plus a global heap of per-user minimum timestamps. In practice B is small, so stating this is enough.
- Space: O(U·K + B).
Code
import heapq
from collections import OrderedDict
def process_logins(stream, window=600, threshold=4, lateness=30):
"""
stream: iterable of (user_id, ts, device_id, success), ts in seconds.
Yields (user_id, window_start, window_end, distinct_devices).
Window is the closed interval [ts - window, ts].
"""
pending = [] # heap of (ts, seq, user, device)
seq = 0
newest = float("-inf")
per_user = {} # user -> OrderedDict(device -> latest ts)
fired = set() # users currently in an alerted episode
last_seen = OrderedDict() # user -> last processed ts, ascending
def apply(user, ts, device):
devs = per_user.setdefault(user, OrderedDict())
cutoff = ts - window
while devs:
oldest_ts = next(iter(devs.values()))
if oldest_ts >= cutoff: # boundary is inclusive
break
devs.popitem(last=False)
if len(devs) < threshold:
fired.discard(user) # episode over, re-arm
devs.pop(device, None)
devs[device] = ts # move to back with new time
last_seen.pop(user, None)
last_seen[user] = ts
if len(devs) >= threshold and user not in fired:
fired.add(user)
return (user, cutoff, ts, len(devs))
return None
def sweep(watermark):
while last_seen:
user, ts = next(iter(last_seen.items()))
if ts >= watermark - window:
break
last_seen.popitem(last=False)
per_user.pop(user, None)
fired.discard(user)
def release(limit):
while pending and pending[0][0] <= limit:
ts, _, user, device = heapq.heappop(pending)
alert = apply(user, ts, device)
if alert:
yield alert
for user, ts, device, success in stream:
newest = max(newest, ts)
if success and ts >= newest - lateness:
heapq.heappush(pending, (ts, seq, user, device))
seq += 1
watermark = newest - lateness
yield from release(watermark)
sweep(watermark)
yield from release(float("inf")) # flush at end of stream
Edge cases and common mistakes
- Two devices exactly 600 s apart still co-occur because the window is inclusive. Using
<=in the eviction test is an off-by-one. - Repeated logins from the same device refresh its timestamp and never inflate the count.
- Letting failed logins create device entries produces false alerts. They should only move the watermark.
- Skipping the idle-user sweep is a silent memory leak.
- Alerting on every event while the count is at least 4 floods the consumer. Use the armed flag.
- Processing late events directly, without a buffer, breaks the sorted-map invariant that eviction relies on.