Pattern 17: Event Replay Deduplication¶
Some devices send startup event replay — they deliver historical events from GetAllEvents() or similar on every connection. Without deduplication, the same events are published to the audit log on every restart, creating duplicate records.
Use route.SkipReplayed with IEventCursor<TKey> to deduplicate in one line. The cursor is a high-watermark: it records the highest event ID seen, persists it across restarts via LiteDB, and silently drops any event at or below the watermark on the next connection.
When to Use¶
Use SkipReplayed when:
- The device replays historical events on every connect (startup/reconnect replay)
- Events have a monotonically increasing numeric identifier
- The same event must not appear twice in the audit log
Do not use for:
- Status/state callbacks (these are not audit events; route them to
StatusBatchinstead — see RULE-024) - Real-time push events that cannot replay (no dedup needed)
- Events without a monotonic ID
Setup¶
Declare IEventCursor<TKey> as a constructor parameter on your ConnectionFunction or routing class. The framework resolves and scopes it per device automatically.
public partial class EventRouting(
ILogger<EventRouting> logger,
IEventCursor<uint> cursor)
{
partial void ConfigureRoutes(IEventRoute<SdkEvent> route)
{
route.SkipReplayed(e => e.Id, cursor);
route.When(e => e.Type == SdkEventType.DoorOpened)
.WithAddress<DoorThing, int>(e => e.DoorId)
.Handle(async (door, e) =>
{
await door.Opened(DeviceTimestamp.FromDevice(e.Timestamp, door.TimeZone));
return true;
});
// ... other routes
}
}
For object routers where only one subtype carries the replay stream, use the two-type overload:
How It Works¶
SkipReplayed registers a replay gate on the router. On each Dispatch call:
- Gate checks
cursor.HasPassed(id)— ifid ≤ LastSeen, the event is silently dropped. - If the event passes, it flows through normal routing.
- After routing, the gate calls
cursor.Advance(id)— ifid > LastSeen, persists the new watermark.
The gate fires before the interceptor (command-response pattern), so replayed events never trigger pending waiters either.
What Not To Do¶
// WRONG: manual HashSet dedup in Protocol
private readonly HashSet<uint> _seenEventIds = [];
bool TryRememberEvent(SdkAuditEvent evt)
{
if (!_seenEventIds.Add(evt.Id))
return false;
// ... bounded eviction logic
return true;
}
// and in dispatch:
if (!TryRememberEvent(e))
return;
// WRONG: manual IPersistentSettings wiring in Panel/Thing
public Panel(IPersistentSettings<EventStoreIndex> eventStore) { ... }
// ... ConfigureEventPersistence(eventStore) in Connect()
Both patterns require 5–8 boilerplate lines per adapter and are replaced by a single SkipReplayed call. See RULE-025 in compliance-rules/events.md.
Multiple Event Streams¶
If the device exposes separate active-event and history-event streams with overlapping IDs, route them through the same router with the same IEventCursor so the gate covers both. If IDs are independent per stream, use a separate IEventCursor per stream (declare two parameters with distinct type arguments, or scope by a different TKey type).
See RULE-024 for how to separate status streams from audit streams.
Connect Ordering: Live Stream vs Backlog Replay¶
A connect that both subscribes a live event stream and reads the device backlog (history) has a race. A live event dispatched during the backlog read advances the persisted cursor past every older event of the outage. If the backlog read then fails, the next replay drops those older events as already seen. The audit loses them for good.
Order the connect like this:
- Subscribe the live stream before the backlog read, so no event falls into the gap between the two.
- Hold live events in arrival order while the replay runs. Do not dispatch them yet.
- Read the backlog from the persisted cursor minus a safety margin, not the whole history. Read the whole history only when no cursor exists yet.
- Give a bulk history read its own long timeout. The normal command answer timeout is too short for a large history.
- Dispatch the replay. Then dispatch the held events in arrival order and drop each one the replay already carried.
- If the connect fails, drop the held events. The next replay reads them again. A failed connect never advances the cursor.
Declare the device-scoped IEventCursor<TKey> as a constructor parameter of the Thing that reads the backlog (or of its router or connection function). The tree builder keys a cursor taken in a Thing constructor by that Thing's own DeviceId, the same key its functions and routers get, so the connect reads the cursor the router advances.
Evidence (Dominus, lab 2026-11-13): a live row advanced the cursor during the connect, the whole-history read timed out on the normal answer timeout, and the next replay skipped the outage. Two access-granted rows were lost.
Coarse Timestamp Keys¶
The cursor needs a key that orders every event uniquely. A device timestamp with coarse resolution (whole seconds) is not unique: one second can hold several events. A plain "greater than last seen" check then drops every later event of the boundary second.
When the key is such a timestamp, make it unique:
- Add a per-run ordinal inside the second (for example, add +n ms for the n-th event of the same second in one read), or
- At the boundary second, compare the whole event (type, address, credential, parameters) against the events of that second already dispatched, not the timestamp alone.
Document the remaining limit in the adapter CLAUDE.md. For example: two identical rows in one second, one logged before the subscription, look like one row.
Evidence (Dominus): history rows carry only whole-second timestamps and no id; the adapter adds a per-run ordinal and compares whole rows at the boundary second.