The Firehose
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
- Asked in
- Amazon
Problem
You're rolling up a stream of metric events, each carrying a numeric timestamp and a numeric value, into fixed-width time windows of size bucket_width, where a window spans [bucket_start, bucket_start + bucket_width). The events arrive unsorted, so collapse every window holding at least one of them into its event count, the total of its values, and the bucket_start it begins at, dropping any window that caught nothing. Return the windows in chronological order, earliest bucket_start first.
A stream arrives out of order. Roll it up, one time window at a time.
Example
Input:
events = [{"value":10,"timestamp":100},{"value":20,"timestamp":250},{"value":15,"timestamp":150},{"value":5,"timestamp":310}], bucket_width = 100Output:
[{"count":2,"total":25,"bucket_start":100},{"count":1,"total":20,"bucket_start":200},{"count":1,"total":5,"bucket_start":300}]Worked solution and explanation
Every timestamp already knows its window
This is a tumbling window aggregation: fixed-width windows that never overlap, with each event in exactly one of them. What makes it cheap is that an event's window depends on nothing but its own timestamp. Floor the timestamp to a multiple of bucket_width and you have its bucket_start, so the unsorted arrival order stops mattering. You group by a computed key in one pass and sort only the keys that came out.
Step 1: Compute the key from the event alone
(ts // bucket_width) * bucket_width floors a timestamp to the start of its window. With a width of 100, 250 becomes 200 and 310 becomes 300. A timestamp of exactly 200 stays at 200, which is what the half-open span [bucket_start, bucket_start + bucket_width) asks for: the left edge belongs to the window and the right edge belongs to the next one.
Step 2: Keep count and total under one key
A dict keyed by bucket_start holds a small record per window, and each event updates both numbers in the same visit. A key is created only when an event lands in it, so windows that caught nothing never exist and there's nothing to filter out afterwards.
Step 3: Sort the windows at the end
sorted(buckets.items()) orders the pairs by bucket_start. The keys are unique, so each tuple comparison is settled on the key and never reaches the dict behind it. The output record is then built in the order the statement lists its fields: count, total, bucket_start.
def aggregate_events(events: list[dict], bucket_width: int) -> list[dict]:
buckets = {}
for event in events:
ts = event['timestamp']
bucket_start = (ts // bucket_width) * bucket_width
if bucket_start not in buckets:
buckets[bucket_start] = {'count': 0, 'total': 0}
buckets[bucket_start]['count'] += 1
buckets[bucket_start]['total'] += event['value']
return [
{
'count': agg['count'],
'total': agg['total'],
'bucket_start': bucket_start,
}
for bucket_start, agg in sorted(buckets.items())
]The sample passes without the sort
The example's events arrive at 100, 250, 150, 310, so their windows are first seen in the order 100, 200, 300. A dict remembers insertion order, which means returning buckets.items() unsorted reproduces the expected output on the sample exactly. The ordering requirement only bites when an event from a later window arrives first. Move the 310 event to the front and the unsorted version returns this:
def aggregate_events(events: list[dict], bucket_width: int) -> list[dict]:
buckets = {}
for event in events:
bucket_start = (event['timestamp'] // bucket_width) * bucket_width
if bucket_start not in buckets:
buckets[bucket_start] = {'count': 0, 'total': 0}
buckets[bucket_start]['count'] += 1
buckets[bucket_start]['total'] += event['value']
return [
{'count': agg['count'], 'total': agg['total'], 'bucket_start': bucket_start}
for bucket_start, agg in buckets.items() # insertion order, no sort
]
events = [
{'value': 5.0, 'timestamp': 310},
{'value': 10.0, 'timestamp': 100},
{'value': 15.0, 'timestamp': 150},
]
print(aggregate_events(events, 100))
# [{'count': 1, 'total': 5.0, 'bucket_start': 300}, {'count': 2, 'total': 25.0, 'bucket_start': 100}]Without sorted, window 300 comes out ahead of window 100.
Common follow-up questions
- What does this return for an empty
eventslist, and for abucket_widthof 0?An empty list returns
[]because the loop never creates a key, and a width of 0 raisesZeroDivisionErroron the first event. Say whether a non-positive width should be rejected up front, because a negative one runs without error and produces windows that do not match the span in the statement. - One event is missing
timestampor carries avalueofNone. Skip it, set it aside, or fail?As written, a missing key raises
KeyErrorand aNonevalue raisesTypeError, so the whole batch fails. For metrics, a common choice is to route bad records to a side list with a reason and keep aggregating: one malformed event shouldn't blank a dashboard, and the rejected count tells you when a producer broke. - The events now come as an unbounded stream. What changes?
You can no longer sort at the end, so the dict becomes running state and a window is emitted once a watermark passes
bucket_start + bucket_width. Late events are what makes this worth asking: you have to say whether they're dropped, sent to a correction path, or allowed to reopen a window. - The dashboard wants the empty windows too, as zeros. How do you add them?
Walk from the smallest
bucket_startto the largest in steps ofbucket_widthand emit a zero record wherever the dict has no key. The cost then follows the time span divided by the width instead of the number of non-empty windows, so a sparse stream with a tiny width can produce far more rows than events.