KatInterview

Multi-Device Login Burst Detector over a Late-Tolerant Stream

Data Structure DesignModel answer
MediumModel answerData Structure Designsliding-windowstreamingwatermark

Last 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

  1. 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.
  2. Events up to 30 seconds late must be handled correctly.
  3. 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.