Hourly Unique Viewer Counts With Retries And Late Events
Last updated: November 29, 2026
Quick Overview
Write a Python function that consumes impression events (event id, user, post, event time) in ingest order, drops client retries, counts unique viewers per post per hour, and rejects events that arrive after their hour has been finalized by a watermark.
X
November 29, 20260
0
0 solved
Write a Python function that consumes impression events (event id, user, post, event time) in ingest order, drops client retries, counts unique viewers per post per hour, and rejects events that arrive after their hour has been finalized by a watermark.
View counts are shown publicly on every X post, and impressions also feed creator payouts and ads billing, so double counting and silently changing past numbers are both costly. The screen checks deduplication by idempotency key, distinct counting, and event-time versus ingest-time reasoning.
What the Interviewer Expects
- Dedupes on event id before any counting
- Buckets by event time, not ingest time
- Counts distinct viewers with a set per bucket
- Implements a watermark with allowed lateness
- Reports dropped late events instead of hiding them
- Discusses memory and approximate counting at scale
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- The seen-event-id set grows forever. How do you bound it?
- How would you use HyperLogLog here and what error would you accept?
- Late events for creator payouts must not be dropped. What do you do instead?
- How does this map onto a streaming framework with windows and triggers?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Each event: event_id (client generated, reused on retry), user_id, post_id, event_ts in seconds. Events arrive roughly but not strictly in time order. An hour bucket is finalized once the wate...
Approach
Single pass. Skip any event_id already seen. Compute bucket = ts - ts % 3600. If bucket + 3600 <= watermark, count it as late and skip. Otherwise add user_id to the set for (post_id, bucket)...