KatInterview

Input Event Capture and Deterministic Text Replay Design

System DesignModel answer
HardModel answerSystem Designsystem-designevent-sourcingime

Last updated

Design a pipeline that records keyboard, mouse and IME events from several devices, orders them globally, persists a log, and rebuilds the exact typed text on replay.

Problem

You are asked to design a subsystem that observes input from keyboards and mice (possibly several devices at once) and can answer one question reliably: what text did the user actually enter?

The same event history must always produce the same final document, whether it is processed live or replayed later from storage, including after a crash.

What to cover

  1. Capture and data models. Handle key down/up, auto-repeat, modifiers, Backspace/Delete and text composition. Define the models for raw device events, normalized events, derived editing operations, and sessions.
  2. Pointer and selection. Handle clicks, movement, scrolling, double and triple click (word and line selection), drag selection and caret movement.
  3. Clipboard and history. Support copy, cut, paste, undo and redo, with sensible grouping of edits into transactions.
  4. Text reconstruction. Build the visible text from the text-input and composition-commit stream, not from raw key codes. Handle IME composition (start, update, end), dead keys, and Unicode grapheme clusters such as emoji and combining marks.
  5. Ordering and concurrency. Keep timestamps monotonic and define a single total order across devices. Discuss queues, buffering, back-pressure and thread safety.
  6. Robustness. Address key/button bounce, mouse-move coalescing, double-click detection, and lost or duplicated events.
  7. API surface. Offer something like recordEvent(event), getCurrentText(), getSelectionRange(), undo(), redo(), startSession, endSession and replay.
  8. Durability. Keep an append-only event log, support deterministic replay, and recover after a crash using snapshots plus a write-ahead log.
  9. Quality. Describe the main components, latency, throughput and memory targets, a test strategy and failure handling.

Be explicit about the trade-offs behind your choices.

Hints

Hint 1

Ask which inputs are non-deterministic (layout hit-testing, clipboard contents, OS double-click timing). If the log stores their resolved outcomes, replay no longer depends on the environment.

Hint 2

Key codes depend on keyboard layout, dead keys, AltGr and IMEs, so derive document text only from text-input and composition-commit events; use key events only for commands such as Backspace, arrows and shortcuts.

Hint 3

Use one writer thread that owns editor state, fed by a bounded multi-producer queue, and have it assign the global sequence number. Treat undo and redo as logged events so replay matches live state.