Interview question
Deduplicate events by idempotency key
Implements duplicate suppression while preserving the first event for each idempotency key.
TL;DR
Implements duplicate suppression while preserving the first event for each idempotency key.
Hash sets, stable ordering, idempotency thinking, input validation, and duplicate-safe processing.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement DeduplicateEvents(IEnumerable<EventRecord> events). Keep the first event for each non-empty idempotency key, preserve arrival order for kept events, and skip later duplicates.
Input keys: A, B, A, C, B
Output keys: A, B, C
I would maintain a HashSet<string> of keys already seen and a result list. For each event, I validate that the key exists, then call seen.Add(key). Add returns true only for the first occurrence, so the condition stays concise. I would mention that this is in-memory dedupe; production idempotency still needs durable storage or database constraints.
public sealed record EventRecord(string IdempotencyKey, string Payload);
public static IReadOnlyList<EventRecord> DeduplicateEvents(IEnumerable<EventRecord>? events)
{
if (events is null)
{
return Array.Empty<EventRecord>();
}
var seen = new HashSet<string>(StringComparer.Ordinal);
var result = new List<EventRecord>();
foreach (var eventRecord in events)
{
if (string.IsNullOrWhiteSpace(eventRecord.IdempotencyKey))
{
continue;
}
if (seen.Add(eventRecord.IdempotencyKey))
{
result.Add(eventRecord);
}
}
return result;
}
Time is O(n) on average because hash lookups are O(1). Space is O(k), where k is the number of unique idempotency keys kept.
Distinct() and losing control over which event is kept.Next in Coding Practice: Merge Time Ranges