KatInterview

Subtracting Two Sensor Feeds with Late-Arriving Corrections

System DesignModel answer
EasyModel answerSystem Designstreamingidempotencyevent-time

Last updated

Design the contract for subtracting two timestamped numeric streams, including missing and duplicate timestamps, and a versioned, idempotent way to publish corrections for late events.

You have two feeds of timestamped numeric readings, call them A and B. The goal is to produce a feed of differences, A − B, and to keep that feed correct when events show up after a result has already been published.

Within each feed as initially supplied, timestamps never go backwards. However:

  • A timestamp may appear in only one of the two feeds.
  • Non-decreasing order still allows the same timestamp to appear several times in one feed.
  • Nobody has told you what a missing counterpart means, or what repeated timestamps mean.
  • Events can arrive after the corresponding result has been emitted.

There is no fixed schema, no agreed lateness bound, and no guarantee of exactly-once delivery.

Discuss the following:

  1. The decisions you must pin down about timestamp alignment, missing counterparts and duplicates before writing any algorithm.
  2. How you would compute the difference over the ordered feeds.
  3. A protocol for publishing corrections so that downstream consumers can tell an initial result from a revision, and so that retries and replays are safe.
  4. The memory and retention costs of your design.

State your assumptions explicitly where the problem leaves things open.

Hints

Hint 1

Before any code, list the semantic questions: are readings independent points, additive contributions, or a value that stays in effect until replaced? The answer decides how to treat missing and repeated timestamps.

Hint 2

With sorted inputs, a two-pointer merge works. Group all events sharing a timestamp in each feed first, then apply your declared rule to the groups, so duplicates and one-sided timestamps are handled in one place.

Hint 3

Give each output a stable key (such as the timestamp) and a monotonically increasing revision. Make consumers apply an update only if its revision is higher than what they hold, so replays and out-of-order delivery cannot regress state.