As asked
You are consuming a Kafka topic of click events. Due to producer retries, some events are duplicated. Each event has a unique event_id (UUID) and an event_timestamp. Write a function that processes a batch of events and returns only the first occurrence of each event, keeping the one with the earliest timestamp if event_ids collide. Assume the batch fits in memory.
Sample answer outline
Group by event_id and keep the entry with the minimum event_timestamp. A dictionary keyed by event_id with the earliest event wins. O(n) time and O(n) space where n is batch size. Strong candidates handle the edge case where two events with the same event_id have identical timestamps (tie-break deterministically), and discuss how this changes when the batch does not fit in memory (use a distributed dedup key store like Redis or a MERGE in the sink).
Reference implementation (python)
from typing import List, Dict
from datetime import datetime
def deduplicate_events(events: List[Dict]) -> List[Dict]:
"""
events: list of dicts with keys: event_id (str), event_timestamp (datetime), payload (dict)
Return deduplicated list keeping earliest timestamp per event_id.
"""
seen: Dict[str, Dict] = {}
for event in events:
eid = event["event_id"]
if eid not in seen or event["event_timestamp"] < seen[eid]["event_timestamp"]:
seen[eid] = event
return list(seen.values())
Expect these follow-ups
- How would your approach change if the stream is unbounded and you need to deduplicate across many batches without storing all seen IDs forever?
- What is a Bloom filter and how could it help here?