Windowed Aggregation Pipeline for Calendar Event Logs
System DesignModel answerLast updated
Design a Spark/MapReduce pipeline that computes rolling 15-minute concurrent meeting counts and room utilization from a large-scale event log.
Scenario
Your company operates hundreds of offices worldwide, each containing dozens of bookable rooms. A centralized scheduling system emits a log entry every time a user joins a meeting. Each record has the shape:
{ user_id, room_id, office_id, start_time, end_time }
Because the log is attendee-level, a ten-person meeting produces ten rows. The log accumulates roughly 500 million records per day and must support backfill over historical months.
What you need to build
Design a Spark (or MapReduce) job that reads this raw log and produces two outputs for every rolling 15-minute window (15-minute length, 5-minute step, UTC-aligned):
- Office concurrency — the peak number of simultaneously active meetings inside each office during the window.
- Overloaded rooms — every room whose utilization exceeds 80% in the window. Utilization is
occupied_seconds / 900; double-booked or multi-attendee rows must not inflate it above 100%.
What the answer should cover
- How you clean, deduplicate, and collapse attendee rows into distinct meetings.
- The interval-transformation strategy you use to make windowed aggregation efficient (e.g., delta encoding, interval splitting, or another approach) — and why.
- Map keys and values, shuffle/partition strategy, and how you avoid or handle skew from large offices.
- How you handle late-arriving and duplicate events in both a batch and an optional streaming path.
- At least three concrete validation checks you would run at scale before trusting the output.
There is no coding judge. Walk through your design as you would in a technical interview, covering correctness, scalability, and operational concerns.
Hints
Hint 1
A raw log row is an attendee record, not a meeting record. Before computing any metric, think about what key uniquely identifies one meeting and how you collapse rows to it — otherwise concurrency and utilization counts will be inflated by the attendee multiplier.
Hint 2
Summing raw durations to compute utilization double-counts overlapping intervals. The correct approach is to take the *union* of intervals per room per window, then measure covered seconds. A line-sweep (sort by time, track active-interval count) achieves this in O(n log n) per room.
Hint 3
A naïve partition on office_id alone concentrates all of a large HQ's traffic onto one reducer. Partitioning on (office_id, day) spreads work proportionally with backfill depth, and map-side combiners on additive deltas (+1/−1) collapse burst keys before the shuffle.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify before designing
Weak answers jump straight to code. Strong answers spend two or three minutes locking down definitions, because the metrics are ambiguous by nature.
What is a "meeting"? Each log row represents one attendee. A room booked by eight people produces eight rows. Both metrics — concurrency and utilization — must operate on distinct meetings, identified by (room_id, start_time, end_time) or by a meeting_id if the schema carries one.
What is "peak concurrent meetings"? The most common interpretation is the highest number of meetings active at the same instant inside the window. A secondary metric is the count of meetings that overlap the window at all. Confirm which is needed; the design below computes both.
How is utilization calculated? occupied_seconds(room, window) / 900. Occupied seconds come from the union of intervals, not their sum. Without union, a double-booked room could show utilization above 100%, which is nonsensical.
Interval convention. Use half-open [start, end). Back-to-back meetings share an endpoint but do not overlap.
Scale envelope to state aloud:
| Signal | Assumption |
|---|---|
| Raw rows/day | 500 M |
| Average attendees/meeting | 4 |
| Distinct meetings/day | ~125 M |
| Average meeting duration | ~45 min |
| Offices | ~1,000 |
| Rooms | ~200,000 |
A handful of large HQ offices account for 20%+ of traffic — skew is real and must be addressed.
2. Pipeline stages
raw log
└─ [S0] validate → deduplicate → collapse to meetings
└─ [S1] office concurrency (delta encoding + line sweep)
└─ [S2] room utilization (interval union per room-day)
Outputs are partitioned by (date, office_id) and written with idempotent overwrite so the job is safe to re-run.
3. Stage 0 — clean, deduplicate, collapse
Validation. Drop or quarantine rows where end <= start, duration exceeds 24 hours, or room_id/office_id is null. Count quarantined rows as a job metric; alert if the rate spikes.
Deduplication. Key on event_id if present; otherwise on hash(user_id, room_id, start_time, end_time). When the log carries updates or cancellations, keep the row with the latest updated_at and discard cancelled events entirely.
Meeting collapse. Map on (room_id, start_time, end_time), reduce to one record per meeting with attendee_count = countDistinct(user_id). This key is small and uniform, so no skew mitigation is needed here.
4. Stage 1 — office concurrency via delta encoding
Why delta encoding beats grouping raw intervals:
Instead of shuffling full intervals to office reducers, emit a +1 at each meeting's start and a -1 at its end. These integers are additive, so Spark's map-side combiners collapse thousands of meetings starting at the same second — e.g., 9 AM Monday in a large HQ — into a single record before any data crosses the network.
Emit step. Split meetings that cross UTC midnight first (the morning segment gets +1 at 00:00 on the next day). Then:
map(meeting):
emit ((office_id, day, start_sec), +1)
emit ((office_id, day, end_sec), -1)
Sweep step. After combining, group by (office_id, day). Each group holds at most 86,400 entries — trivial in memory.
- Sort by timestamp. At ties, apply
-1before+1(required by half-open semantics). - Take a running prefix sum to get the concurrency curve
c(t). - Bucket the curve into 5-minute base intervals; record the max per bucket.
- The peak for any 15-minute sliding window is the max of three consecutive bucket maxima. Because max is decomposable, this is exact.
Overlapping-meetings count is not decomposable this way. Compute it by emitting (office_id, window_start) for every window the meeting overlaps; the replication factor is roughly duration/step + 2 ≈ 11 for a 45-minute meeting, which is acceptable. Sum with combiners.
Partition on (office_id, day), not office_id alone. This distributes backfill work evenly across tasks. If a single day's HQ data is still too large for one task, salt on (office_id, day, hour) and pass carry-in counts between hour boundaries in a lightweight second pass.
5. Stage 2 — room utilization via interval union
- Key each (post-midnight-split) meeting by
(room_id, day). - In the reducer, sort intervals by start time and merge overlapping ones into a disjoint union.
- Clip the merged intervals to each 5-minute base bucket; sum occupied seconds per bucket.
- Window occupancy = sum of three consecutive buckets (exact, because buckets are disjoint).
- Divide by 900; emit rows where the result exceeds 0.8.
With 200k rooms and a few dozen bookings per room per day, keys are small and uniformly distributed — no skew concern here.
Common mistake: summing raw durations. That double-counts double-bookings and multi-attendee rows, and can produce utilization > 1. The union is non-negotiable for correctness.
6. Late and duplicate events
Batch path (source of truth): Re-run the last N days on a daily schedule (N = 3 is a reasonable default, sized from observed lateness distributions). Overwrite partitions atomically. Because Stage 0 deduplicates by key and keeps the latest version, re-runs are fully idempotent. Late updates and cancellations are automatically incorporated.
Streaming path (optional, for live dashboards): Use Structured Streaming with event-time windows and a 2-hour watermark:
withWatermark("start_time", "2 hours")
dropDuplicates(["event_id"]) # state bounded by watermark
Events that arrive after the watermark drain into a late-events table, triggering a batch recompute of the affected partitions. This is a classic lambda trade-off: fast approximate numbers from streaming, corrected exact numbers from the nightly batch.
A pure kappa design (streaming only, long watermarks) is technically possible but expensive — calendar edits can arrive days before the meeting, requiring very large deduplication state. Lambda is the pragmatic choice here.
7. Validation at scale
Run these checks per output partition and fail or alert on violation:
- Non-negative concurrency:
c(t) ≥ 0everywhere. A negative value means a delta-encoding or sort bug. - Delta balance: the sum of
+1deltas per(office_id, day)equals the distinct meeting count from Stage 0. Catches missed emissions. - Concurrency ceiling:
peak_concurrent ≤ number of rooms in the office. A peak higher than the room count is physically impossible. - Utilization bounds:
0 ≤ utilization ≤ 1. Values above 1 indicate the union step was skipped or the wrong duration field was used. - Quarantine rate monitoring: alert if the Stage 0 drop rate increases by more than one standard deviation — signals an upstream schema change or ingestion problem.
These checks are cheap relative to the job runtime and catch the most common failure modes before results reach downstream consumers.