Input Event Capture and Deterministic Text Replay Design
System DesignModel answerLast 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
- 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.
- Pointer and selection. Handle clicks, movement, scrolling, double and triple click (word and line selection), drag selection and caret movement.
- Clipboard and history. Support copy, cut, paste, undo and redo, with sensible grouping of edits into transactions.
- 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.
- Ordering and concurrency. Keep timestamps monotonic and define a single total order across devices. Discuss queues, buffering, back-pressure and thread safety.
- Robustness. Address key/button bounce, mouse-move coalescing, double-click detection, and lost or duplicated events.
- API surface. Offer something like
recordEvent(event),getCurrentText(),getSelectionRange(),undo(),redo(),startSession,endSessionandreplay. - Durability. Keep an append-only event log, support deterministic replay, and recover after a crash using snapshots plus a write-ahead log.
- 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and numbers
Functional: capture key, mouse and IME events from multiple devices; maintain text, caret and selection; support clipboard, undo and redo; persist a log; replay it to rebuild the exact final text.
Non-functional targets (state them aloud):
- Rate: typing is about 10-15 keys/s (20-30 events counting down and up). High-polling mice report up to about 1,000 Hz, so plan for roughly 2k raw events/s per device.
- Latency: under 2 ms p99 from event arrival to updated state, well within a 16 ms frame.
- Storage: a canonical event is about 64 bytes. With mouse-move coalescing and moves kept only during drags, an hour of typing is on the order of 1 MB.
- Memory: document size plus bounded undo history (say 1,000 transactions) plus an event ring buffer of about 8k entries.
- Correctness:
replay(log) == live state, exactly. A committed text event is never lost.
2. API
startSession(config) -> sessionId
recordEvent(event) // non-blocking enqueue
getCurrentText() -> string // read of an immutable snapshot
getSelectionRange() -> {anchor, focus} // grapheme-aligned
undo() / redo() // logged as events
endSession(sessionId) // flush log, final snapshot
replay(sessionId, uptoSeq?) -> State
undo() and redo() must be logged commands. If they mutate state out of band, replay diverges from the live document.
3. Data model
- RawEvent:
deviceId, deviceSeq, hwTs, type, keyCode, scanCode, modifiers, isRepeat, x, y, button, data. - CanonicalEvent:
sessionId, globalSeq, monoTs, deviceId, deviceSeq, kind, payload. It is deduplicated and carries resolved values: the text offset from hit-testing (not x/y), the click count, and the clipboard string on paste. - Operation:
opId, txnId, type (Insert, Delete, SetSelection, SetComposition, CommitComposition), range, text, inverse. - Session:
id, startTs, devices, reducerVersion, lastSeq, snapshotRefs, status.
The key principle is that canonical events store the outcomes of non-deterministic inputs. Replay then never depends on window size, fonts or the live clipboard.
4. Architecture
Device hooks -> capture adapters (stamp monotonic ts + deviceSeq)
-> bounded MPSC ring buffer
-> normalizer (dedupe, debounce, coalesce, click detection, hit-test)
-> sequencer (assign globalSeq)
-> WAL writer (group commit)
-> editor reducer (single thread, pure) -> immutable snapshot via atomic pointer
-> periodic snapshotter
Readers use the latest snapshot without locks.
5. Deep dives
Text and IME
- Text comes only from
TextInputand composition-commit events. Key codes vary with layout (QWERTY vs AZERTY), dead keys, AltGr and IMEs, so mapping them to characters is wrong. Key events drive commands only: Backspace, Delete, arrows, Home/End, shortcuts. - Dead keys: the accent keystroke inserts nothing; the following key yields one
TextInput("é"). - Composition: start opens a provisional marked range; each update replaces the marked text and is not an undoable edit; end commits the string as a single Insert transaction; cancel removes the marked text. While composing, Backspace and arrows belong to the IME.
- Graphemes: store text in a rope. Caret movement, selection snapping and Backspace work on extended grapheme clusters (UAX #29), so a family emoji or
e+ combining accent is removed as one unit. Make the behavior for decomposed Indic or Hangul sequences a policy flag, since platforms differ.
Mouse and selection
- Mouse down resolves a text offset via the layout service and logs it. Shift+click extends the selection.
- Click counting: same button, within the OS interval (about 500 ms) and a few pixels of the previous click. Two clicks select a word, three select a line or paragraph.
- Drag: down sets the anchor, moves update the focus, up finalizes. Coalesce moves to the latest position per frame.
- Scroll affects only the viewport; log it at low fidelity for analytics since replay does not need it.
Clipboard and undo
- Copy changes no text. Cut is copy plus a Delete transaction. Paste logs the pasted string inside the event.
- Undo and redo use the command pattern: transactions hold ops with inverses, two stacks, and a new edit clears redo.
- Grouping: merge consecutive single-grapheme inserts until a pause over about 1 s, a caret move or click, a switch between insert and delete, or a word boundary. Paste, cut, IME commit and replace-selection are each their own transaction. A held Backspace is one transaction.
Ordering and concurrency
- Use a monotonic clock, never wall time; record wall time once per session for display.
- A single sequencer assigns
globalSeq; if hardware timestamps exist, apply a small reorder window (about 5 ms) sorted by(monoTs, deviceId, deviceSeq). Replay uses onlyglobalSeq. - Capture threads only enqueue into a lock-free MPSC ring. One writer owns the editor state, so the document needs no locks, and it publishes immutable snapshots (persistent rope behind an atomic pointer).
- Back-pressure, in order: coalesce mouse moves, drop hover moves outside drags, spill to an overflow buffer. Never drop key, text or composition events, and never block the OS input thread.
Robustness
- Duplicates: dedupe on
(deviceId, deviceSeq). - Gaps: a hole in
deviceSeqmeans loss; log a gap marker and reconcile, e.g. synthesize a KeyUp for a stuck key. - Bounce: ignore a repeat transition of the same key or button within a few milliseconds.
Persistence and recovery
- Append canonical events to a write-ahead log with group commit (fsync every few ms or N events); text-committing events may force a flush.
- Take snapshots every N events or seconds, storing state plus
lastSeq. - Recovery: load the latest valid snapshot, then replay WAL records with
seq > lastSeq. Use per-record checksums and truncate a torn tail. - Pin
reducerVersionin the session so old logs replay with the matching logic.
6. Testing
- Property test: for random event streams,
replay(log) == liveand replay from any snapshot equals full replay. - Golden corpora: IME sequences (Japanese, Korean, Chinese), dead keys, emoji ZWJ sequences, combining marks.
- Fault injection: kill the process mid-write, corrupt the tail, duplicate and reorder events.
- Load tests: 1 kHz mouse streams on several devices with p99 latency checks.
7. Trade-offs and common mistakes
- Inferring text from key codes breaks on layouts and IMEs.
- Storing raw coordinates or reading the live clipboard during replay makes it non-deterministic.
- Out-of-band undo, or using wall-clock time for ordering, causes divergence.
- Indexing by code units or code points instead of graphemes splits emoji.
- Blocking the capture thread on disk I/O; keep logging asynchronous with bounded group commit.
- A single writer limits throughput, but at these rates (thousands of events/s) it is far from a bottleneck and buys simplicity and determinism.