Subtracting Two Sensor Feeds with Late-Arriving Corrections
System DesignModel answerLast 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:
- The decisions you must pin down about timestamp alignment, missing counterparts and duplicates before writing any algorithm.
- How you would compute the difference over the ordered feeds.
- 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.
- 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Settle the contract first
The ordering guarantee only tells us how to scan the data. It says nothing about meaning, so I would fix these decisions up front and write them down.
What a reading represents. I will assume each reading is a point measurement and that A − B is only defined at a timestamp where both sides have a value. Alternatives are additive contributions (sum per timestamp, then subtract) or step-function state (the last value stays in effect until replaced, so A − B is defined at every moment both feeds have started). The choice changes the output, so it must be explicit.
Missing counterpart. Options: omit the row, emit it as incomplete (a null difference with a status flag), carry forward the last known value, interpolate, or use a default such as 0. Defaults and interpolation invent data, so I would pick emit nothing final until both sides are present, and optionally emit a pending marker. Whatever is chosen, the rule must be declared and consistent.
Duplicates. Three readings are possible: distinct measurements (aggregate them, e.g. sum or mean), true duplicates from retries (deduplicate by an event id), or revisions (last write wins by a sequence number). Without an event id I cannot distinguish the first two, so I would ask. If forced to assume: collapse each timestamp per feed with a declared aggregate, and dedupe by event id when one exists.
Lateness. Define a watermark: a result for timestamp t is final once the watermark passes t + allowed_lateness. Before then it is provisional. After that, late events are either rejected, routed to a side channel, or still applied as corrections with a larger retention window. This is a business choice, not a technical default.
2. Computing the difference
Both feeds are sorted, so use a two-pointer merge. For each step, take the smaller current timestamp t, consume the whole run of events with timestamp t from each feed, and collapse each run with the declared aggregate.
def subtract(a, b, agg=sum):
i = j = 0
out = []
while i < len(a) or j < len(b):
ta = a[i][0] if i < len(a) else float("inf")
tb = b[j][0] if j < len(b) else float("inf")
t = min(ta, tb)
va, vb = [], []
while i < len(a) and a[i][0] == t:
va.append(a[i][1]); i += 1
while j < len(b) and b[j][0] == t:
vb.append(b[j][1]); j += 1
if va and vb:
out.append((t, agg(va) - agg(vb), "complete"))
else:
out.append((t, None, "incomplete")) # or skip, per contract
return out
Time is O(n + m), and extra memory is O(largest duplicate run). In a true streaming setting I keep a small buffer of timestamps that have only one side so far, and I emit or expire them as the watermark advances.
3. Publishing corrections
For late data, keep per-timestamp state (the aggregates for A and B, plus the last published revision) and re-derive the output when that state changes.
Result identity. Key each output by (series_id, timestamp). This never changes across revisions.
Revision. Each output carries a revision that increases by one every time the value for that key changes. The first publish is revision 1 with kind = "initial". Later ones use kind = "correction".
Replacement versus delta. I prefer replacement: the correction carries the full new value (and optionally the previous one for auditing). Replacement is idempotent, because applying it twice has the same effect as once. Deltas ("add +2.5") are compact but break under retries and replays, so if they are required, include the revision they apply to and the source event id so they can be deduplicated.
Consumer rule. Upsert by key and apply a message only if revision > stored_revision. This makes the consumer safe against duplicate delivery, reordering and replays, and an older message can never overwrite a newer one.
Producer side. Deduplicate input events by event id, persist the state and the revision counter atomically with the output (or via a transactional outbox), and assign revisions from that persisted state. After a crash, replaying input then reproduces the same revisions, or at worst re-sends messages that consumers ignore. This gives effectively-once results on top of at-least-once delivery without needing exactly-once transport.
Suppress no-ops. If a late event does not change the final value (for example, an exact duplicate), do not bump the revision.
Example message:
{"series":"s1","ts":1700000000,"value":4.5,"revision":2,"kind":"correction","supersedes":1,"status":"complete"}
4. Memory and retention
- State per open timestamp is small (two aggregates and a revision), but it must be kept for the whole lateness window, so memory is roughly event rate × allowed lateness.
- Unmatched one-sided timestamps stay buffered until the counterpart arrives or the window closes, then they are emitted as incomplete or dropped, per the contract.
- Longer lateness windows improve accuracy but increase memory, latency to finality, and the churn that consumers see. Spill state to a keyed store with TTL when it does not fit in memory.
- After the window closes, late events go to a dead-letter or audit stream, or a periodic batch backfill re-publishes affected keys with higher revisions.
Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Emit only when both sides present | No invented data | Higher latency, buffering |
| Emit provisional then correct | Low latency | Consumers must handle revisions |
| Replacement corrections | Idempotent, simple | Larger messages |
| Delta corrections | Compact | Need dedup and ordering |
| Long lateness window | Accurate | Memory, delayed finality |
Common mistakes
- Starting to code the merge without asking what missing or repeated timestamps mean.
- Assuming sorted order means unique timestamps.
- Silently filling missing values with 0.
- Using wall-clock arrival time rather than event time for alignment.
- Sending corrections without a revision, so consumers cannot order them.
- Delta corrections without dedup, which double-count on retry.
- Ignoring the retention cost of waiting for late data.