Scrivio Interview library
InternalsIntermediate7 min read · updated 13 November 2026

An ad click stream job counts clicks per ad per minute using processing-time windows. Mobile apps send clicks in batches when they regain signal, some 30 minutes late, and when the job restarts after a crash some minutes are counted twice.

How do you make the per-minute click counts correct despite late events and job restarts, and which trade-off between latency and completeness do you choose?

We window by event time, the click's own timestamp, and use watermarks to estimate how far event time has progressed so a window can be emitted. A window is emitted when the watermark passes it and then updated as late events arrive within an allowed lateness such as 1 hour, with anything later sent to a side output and corrected by batch. Restarts stop double counting because the processor checkpoints its state together with the input offsets and writes output transactionally or as an idempotent upsert keyed by ad and window, and duplicates are dropped by click id. We publish provisional real-time counts for dashboards and final counts after the lateness period for billing.

Why this question is asked

This job has two separate bugs that both corrupt the numbers advertisers pay for. Processing-time windows count a click in the minute it arrived rather than the minute it happened, so phones that reconnect after 30 minutes move clicks into the wrong minutes. And restarts replay input that was already counted, so some minutes are counted twice. Interviewers ask this because it tests the core ideas of stream processing: event time, watermarks, lateness and exactly-once results. In this answer, we will see both bugs, introduce event time and watermarks, handle late data, make restarts safe, deduplicate clicks, and choose the trade-off between latency and completeness.

1Two Bugs in One Job

Processing time is the clock of the machine running the job; event time is the timestamp recorded when the click happened. A processing-time window from 10:42 to 10:43 contains whatever arrived in that minute. When a phone in a tunnel sends a batch of clicks from 10:12 at 10:42, all of them are counted at 10:42. The total per day may be right, but the per-minute counts are wrong, and they change if the job is rerun, because arrival times differ on every run.

The restart bug is different. The job reads from Kafka and commits its read position, the offset, separately from writing counts. After a crash, it resumes from the last committed offset, which may be earlier than the last event it counted, and it adds those events again to counts already written. Each restart double counts a few minutes.

2Event Time and Watermarks

The first fix is to window by event time: each click goes to the minute of its own timestamp, however late it arrives. But that raises a question: when is the 10:42 window complete? In event time, more 10:42 clicks could always arrive later.

A watermark answers that question approximately. It is a marker flowing through the stream that says 'event time has reached T; I do not expect earlier events any more'. A common strategy sets the watermark to the highest timestamp seen minus a bound, for example 30 seconds. When the watermark passes 10:43:00, the 10:42 window is emitted.

Clicks arriving out of order
Arrives atEvent timeWindowWhat happens
10:43:0510:42:5010:42counted, window still open
10:43:3110:43:3110:43watermark moves to 10:43:01, 10:42 emitted
10:44:1010:42:2010:42late but within allowed lateness: window updated
11:20:0010:12:0010:12within 1 hour: 10:12 updated again
12:30:0011:05:0011:05beyond lateness: side output for batch

3Allowed Lateness and the Side Output

A watermark of 30 seconds handles network jitter, but not phones that come back after 30 minutes. Making the watermark wait 30 minutes would delay every count by 30 minutes. Instead, we emit on time and then correct: allowed lateness keeps each window's state for an extra period, say 1 hour, and every late event within that period updates the window and emits a new result for it.

Java
OutputTag<Click> tooLate = new OutputTag<>("too-late") {};
SingleOutputStreamOperator<AdMinuteCount> counts = clicks
.assignTimestampsAndWatermarks(WatermarkStrategy
.<Click>forBoundedOutOfOrderness(Duration.ofSeconds(30))
.withTimestampAssigner((c, t) -> c.eventTimeMillis()))
.keyBy(Click::adId)
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(1)))
.allowedLateness(Duration.ofHours(1)) // late clicks update their window
.sideOutputLateData(tooLate) // later than 1 hour: not dropped silently
.aggregate(new CountClicks());
counts.sinkTo(upsertByAdAndMinute); // (77, 10:12) -> 940, later -> 1,013
counts.getSideOutput(tooLate).sinkTo(lateClicksForBatch);

Notice two consequences. The sink must accept updates for the same window, which is why it upserts by ad and minute rather than appending. And events later than an hour are not lost; they go to a side output that a daily batch job folds into the final counts. One hour is chosen from data: if 99.9 percent of mobile batches arrive within 40 minutes, an hour covers them with margin.

4Exactly-Once Results Across Restarts

To stop double counting, the processor must save its state and its input position together, as one consistent snapshot. Flink does this with checkpoints: it periodically records the Kafka offsets it has read and the window state built from exactly those events. After a crash, it restores both from the last checkpoint, so state and position always match, and events after that point are processed once more against state that has not seen them.

That makes the state exactly-once, but output written between the checkpoint and the crash would be written again. There are two ways to make output safe. A transactional sink writes to Kafka inside a transaction that commits only when the checkpoint completes, and downstream consumers read with isolation.level=read_committed, so they never see output from a failed attempt. Or the sink is an idempotent upsert keyed by ad and window, so writing the same result twice leaves the same row.

Step throughCrash and recovery without double counting
Kafka inputProcessorCheckpoint storeOutput
events up to offset 5,000
checkpoint: offsets 5,000 + window state
events 5,001 to 5,400
write in open transaction (not visible)
crash
restore offsets 5,000 + state
replay 5,001 to 5,400
commit with next checkpoint

8 messages in order. Play them, or step through them one at a time.

The aborted transaction is never seen by read_committed consumers.

5Deduplicating Clicks by Click ID

Exactly-once processing only means each input event is counted once. If the same click arrives as two events, because a client retried or a redirect fired twice, both are separate input events and both would count. So we deduplicate by click id: the processor keeps the ids seen recently in keyed state and drops repeats.

That state must be bounded in time, or it would grow forever. We keep each click id for the allowed-lateness period plus a margin, for example 2 hours, using a state time-to-live. At 115,000 clicks per second, two hours is about 830 million ids, which is large but manageable in RocksDB-backed state spread across the cluster; a Bloom filter per time bucket can shrink it further at the cost of rare false drops.

6Choosing the Trade-off: Provisional and Final

Latency and completeness pull against each other: emit early and some clicks are still missing, wait and the dashboard is stale. We do not have to choose one. We publish provisional counts as soon as the watermark passes, within about a minute, for dashboards and pacing, and they are updated as late clicks arrive. Once the allowed lateness has passed for a whole day, plus the batch correction for very late events, we publish final counts, and those are what invoices use.

The important part is to label them. Advertisers see real-time numbers marked provisional, and invoices state that they are based on final counts closed after a defined period. Then a small difference between the two is expected behaviour, not a dispute.

7Follow-up questions

Why not use a much larger watermark delay instead of allowed lateness?

Because the watermark delays every result for every ad. With a 30-minute delay, dashboards would always be 30 minutes behind, to cover a small share of late events. Allowed lateness gives fast results for the common case and corrects them for the rare late ones.

Does exactly-once in Flink mean the sink sees each record exactly once?

Not by itself. It means the processor's state reflects each input once. End-to-end exactly-once also needs a transactional or idempotent sink, and consumers of a transactional Kafka topic must read with read_committed, otherwise they can see uncommitted output from a failed attempt.

What does a transactional sink cost?

Latency: output becomes visible only when the checkpoint commits, so a 30-second checkpoint interval adds up to 30 seconds. An idempotent upsert sink avoids that delay, which is why it suits a dashboard store well.

8Conclusion

In this answer, we fixed two different bugs. Processing-time windows put late mobile clicks in the wrong minute, so we windowed by event time with watermarks, emitted windows on time and updated them within an allowed lateness of an hour, and sent anything later to a side output for batch correction. Restarts double counted, so we relied on checkpoints that save state and offsets together and on a transactional sink read with read_committed or an idempotent upsert. We deduplicated by click id in time-bounded state, and published provisional counts for dashboards and final counts for billing.

What to say in the interviewAbout 90 seconds aloud

Open with

There are two separate problems. Processing-time windows count a click in the minute it arrived, so mobile batches thirty minutes late land in the wrong minutes, and restarts replay events that were already counted.

Then, if they want more

For the first, I window by event time, the click's own timestamp, and use watermarks, for example the highest timestamp seen minus thirty seconds, to decide when a window can be emitted.

For the late phones, I set an allowed lateness of about an hour: the window is emitted when the watermark passes and then updated as late clicks arrive, so the sink must be an upsert keyed by ad and minute.

Anything later than that goes to a side output that a batch job folds into the final numbers, so nothing is silently dropped.

For restarts, the processor checkpoints its state together with the Kafka offsets, so after a crash both are restored consistently, and output is either transactional, Kafka transactions read with read_committed, or an idempotent upsert, so a replay does not double count.

Separately, I deduplicate by click id in state with a time-to-live a bit longer than the lateness, because clients and redirects can send the same click twice.

On the trade-off, I would not pick one: provisional counts within a minute for dashboards and pacing, clearly labelled, and final counts after the lateness period closes, which are the ones we bill on.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you make the per-minute click counts correct despite late events and job...": https://scrivio-interview-library.netlify.app/architecture/system-design-problems/fcdeb96d9f/