Skip to content

76. Drop Duplicate Events from a Retrying Producer

Difficulty: Medium · Topics: Streaming, Filtering & Selection

A mobile app sends events to events (event_id, user_id, ts). When a send times out, the app retries, so the same event can arrive twice, in the same batch or a later one. Two rows are the same event only when both event_id and ts match: the app reuses ids after a reinstall.

Write each event once. The stream runs for months, so Spark must not remember every event_id forever: use a 30-minute watermark on ts so old ids are forgotten. As a result, an event that arrives when the watermark has already passed its ts is dropped, duplicate or not.

Return event_id, user_id, ts in append mode.

The stream arrives in micro-batches: batch in the preview is the batch an event arrives in, not a column of the stream. The expected output lists every row your query writes, with batch set to the micro-batch after which it is written.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

events

batchevent_iduser_idts
1e1u12024-05-01 10:00:00
1e2u22024-05-01 10:05:00
1e1u12024-05-01 10:00:00
2e3u12024-05-01 10:40:00
2e2u22024-05-01 10:05:00
3e4u32024-05-01 10:08:00
3e5u22024-05-01 10:45:00
3e6u12024-05-01 10:25:00

Expected output

batchevent_iduser_idts
1e1u12024-05-01 10:00:00
1e2u22024-05-01 10:05:00
2e3u12024-05-01 10:40:00
3e5u22024-05-01 10:45:00
3e6u12024-05-01 10:25:00

Hints

Hint 1dropDuplicates([...]) on a stream keeps every key it has seen as state, so it can drop a copy that arrives in a later batch.
Hint 2The state is only cleaned up when the event-time column is part of the key: deduplicate on ["event_id", "ts"] after withWatermark("ts", "30 minutes").
Hint 3Deduplicating on event_id alone treats a reused id as a duplicate, and Spark can then never forget an id: its state grows forever.

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice