Design a Distributed Calendar Aggregation Engine
System DesignModel answerLast updated
Architect a MapReduce-based system to process massive calendar datasets and identify mutual free time slots of length d across large organizations.
System Requirement
Design a distributed processing pipeline (such as MapReduce) to analyze historical and upcoming calendar events for millions of users. The goal is to compute all common available time windows of at least duration $d$ for given user cohorts (e.g., team calendars, project groups, or entire enterprise divisions).
Input Data Format
- User Busy Intervals: High-volume logs formatted as
(user_id, start_timestamp, end_timestamp). Timestamps are standard UTC Unix epoch values. Intervals are half-open $[start, end)$. - Cohort / Group Membership: A mapping dataset structured as
(group_id, user_id). A single user may belong to multiple groups.
Key Objectives
- Formulate a scalable multi-stage MapReduce workflow. Clearly specify Map keys/values, Partitioning strategies, Combiner applicability, and Reducer logic for each stage.
- Define how time discretization and window partitioning (e.g., daily buckets vs. discrete slotting) are handled without introducing edge artifacts.
- Provide clear mechanisms to eliminate data skew caused by massive "all-hands" groups (up to tens of thousands of members) or power users with thousands of events/groups.
- Detail validation strategies to guarantee correctness and idempotency across batch executions.
Hints
Hint 1
Interval union is associative and commutative. Use map-side combiners to merge individual busy blocks before shuffling group data.
Hint 2
Avoid fixed-size grid discretization to prevent precision loss and inflated data volume. Use boundary-clipped continuous intervals alongside temporal buckets.
Hint 3
For massive groups (high fan-out key skew), apply salting (key split) with a k-way secondary merge step.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. System Scale & Key Requirements
Requirements Scope
- Input Data:
- User Events:
(user_id, start_time, end_time)in UTC epoch seconds/minutes. - Group Maps:
(group_id, user_id).
- User Events:
- Query Parameters: Target time window $[W_{start}, W_{end})$ and minimum continuous duration threshold $d$.
- Output: For each group, produce a list of disjoint, maximal free time windows $[t_{start}, t_{end})$ where length $\ge d$ and no group member has a conflicting busy interval.
Quantitative Assumptions (Back-of-the-Envelope)
- User Base: $100\text{M}$ active users.
- Interval Volume: Average $30$ events/user per 2-week window $\approx 3\text{B}$ input raw events ($\sim 100\text{ GB}$ uncompressed).
- Group Scale: $10\text{M}$ total groups. Average group size = $10$ users, but maximum group size can reach $50,000$ (e.g., enterprise-wide groups).
- Fan-out Load: If an average user belongs to $5$ groups, raw map fan-out yields $15\text{B}$
(group_id, interval)pairs. Unoptimized shuffle will cause severe network and disk IO bottlenecks.
2. Theoretical Foundation & Core Strategy
Finding mutual free time across $N$ users is equivalent to calculating the complement of the union of all members' busy intervals within window $[W_{start}, W_{end})$.
$$\text{FreeTime}(\text{Group}) = [W_{start}, W_{end}) \setminus \left( \bigcup_{u \in \text{Group}} \text{BusyTime}(u) \right)$$
Because interval set union ($\cup$) is both associative and commutative:
- Early Aggregation (Combiners): Merging overlapping busy intervals can occur safely at any intermediate step.
- Horizontal Partitioning (Salting): A group's members can be split across multiple parallel workers to compute partial busy unions, which are later combined without altering the final output.
3. Architecture & Distributed Pipeline Design
The system runs as a 3-stage MapReduce job to minimize fan-out, prevent shuffle explosion, and avoid Memory Overhead in Reducers.
+------------------+ +------------------------+ +-----------------------+
| Stage 1: User | --> | Stage 2: Group Fan-Out | --> | Stage 3: Cross-Bucket |
| Normalization | | & Bucket Merging | | Stitch & Filter |
+------------------+ +------------------------+ +-----------------------+
Stage 1: Per-User Normalization & Compaction
Before broadcasting or mapping events to groups, reduce per-user redundancy (e.g., overlapping meetings, double bookings, pre-expanded recurring events).
- Map Input:
(user_id, start, end) - Map Function: Clip event to global window $[W_{start}, W_{end})$. Discard invalid records where $end \le start$. Emit
key = user_id,value = (start, end). - Reducer: Sort intervals by
start, merge overlapping or contiguous intervals for each user. - Output: Cleaned, non-overlapping busy intervals for each single user:
(user_id, List[(start, end)]). - Impact: Reduces overall event count per user by $20\text{--}40%$ before fan-out.
Stage 2: Group Join, Temporal Bucketing, & Map-Side Union
In this phase, we join user busy schedules with group memberships and slice time into daily/weekly temporal buckets $[B_{start}, B_{end})$ to bound memory usage during interval sweeps.
- Broadcast Join Optimization: Group membership datasets ($\sim 1\text{--}2\text{ GB}$) are pre-distributed to all Mappers via Distributed Cache as a lookup hash table:
Map[user_id, List[group_id]]. - Map Function:
- For each
(user_id, List[interval]), lookup associatedgroup_ids. - Divide each interval across intersecting temporal buckets $[B_{start}, B_{end})$.
- For large groups (detected via metadata), append a salt value $s \in [0, k-1]$.
- Emit:
- Key:
(group_id, bucket_id, salt) - Value:
(clipped_start, clipped_end)
- Key:
- For each
- Combiner: Merges overlapping intervals locally on the map node for each
(group_id, bucket_id, salt)key. This collapses hundreds of individual user events into a minimal set of merged busy blocks before cross-network shuffle. - Reducer (Secondary Sort):
- Sort values incoming to each reducer by
clipped_start. - Perform a single-pass interval sweep to merge all overlapping busy intervals in the bucket.
- Invert the merged busy intervals to identify intermediate free slots within $[B_{start}, B_{end})$.
- Emit:
key = group_id,value = (bucket_id, free_start, free_end, touches_left_boundary, touches_right_boundary).
- Sort values incoming to each reducer by
# Stage 2 Reducer Interval Sweep Logic
def reduce_bucket_free_slots(group_bucket_key, intervals, bucket_start, bucket_end):
merged_busy = []
curr_start, curr_end = None, None
for start, end in intervals: # Pre-sorted by start
if curr_start is None:
curr_start, curr_end = start, end
elif start <= curr_end:
curr_end = max(curr_end, end)
else:
merged_busy.append((curr_start, curr_end))
curr_start, curr_end = start, end
if curr_start is not None:
merged_busy.append((curr_start, curr_end))
# Compute Complement (Free Slots)
free_slots = []
prev_end = bucket_start
for b_start, b_end in merged_busy:
if b_start > prev_end:
free_slots.append((prev_end, b_start))
prev_end = max(prev_end, b_end)
if prev_end < bucket_end:
free_slots.append((prev_end, bucket_end))
return free_slots
Stage 3: Bucket Stitching & Duration Filtering
Because temporal bucketing cuts gaps at bucket borders, Stage 3 connects bordering free gaps and drops any final window smaller than duration $d$.
- Map Input:
key = group_id,value = (bucket_id, free_start, free_end) - Reducer:
- Group by
group_idand order byfree_start. - Merge consecutive free slots where
slot1.free_end == slot2.free_start. - Retain only merged slots where
(free_end - free_start) >= d. - Write final output to Distributed Key-Value Store (e.g., Cassandra / DynamoDB).
- Group by
4. Handling Skew & Boundary Edge Cases
Data Skew Strategies
| Skew Driver | Risk | Mitigation Strategy |
|---|---|---|
| Hot Groups (e.g., All-Hands group with $50\text{K}$ members) | Single reducer memory crash & long tail latency. | Salting: Assign salt = hash(user_id) % k for hot groups. Distribute work across $k$ reducers. Stage 3 performs a $k$-way merge of partial busy sets. |
| Power Users (Bots/Automated Schedules) | Excessively long input list in Stage 1. | Cap maximum per-user events or consolidate dense continuous blocks during Stage 1 map parsing. |
| Temporal Skew (Workday peak vs Weekend quiet) | Reducers handling weekday buckets become bottlenecks. | Dynamic bucket sizes: use smaller buckets (e.g., 6 hours) for high-density periods and larger buckets (e.g., 3 days) for weekends. |
Edge Case Management
- Halo Expansion (Boundary Optimization):
Instead of running an explicit Stage 3 job to stitch adjacent bucket boundaries, extend each bucket boundary by duration $d$ (halo region). A free slot is assigned exclusively to the bucket where its
start_timefalls. This eliminates Stage 3 entirely at the expense of slight map-side interval duplication. - Timezone & Daylight Saving Time (DST) Transitions: All map and reduce mathematical operations take place strictly in absolute UTC epoch values. Local working-hour constraints (e.g., 9 AM - 5 PM local time) are converted into synthetic busy intervals (e.g., adding busy blocks for nighttime hours) before Stage 1.
5. Verification & Fault Tolerance
- Mathematical Invariant Counters:
- During Stage 2 reduce operations, assert: $$\sum \text{Duration}(\text{Busy}) + \sum \text{Duration}(\text{Free}) = B_{end} - B_{start}$$
- Counter metrics track dropped invalid intervals ($end \le start$) and missing membership lookups.
- Idempotency & Determinism:
- Standardized sorting criteria (primary by
start_time, secondary byend_time) guarantee that rerun operations yield byte-for-byte identical output stores.
- Standardized sorting criteria (primary by
- Sampling Validation:
- An auxiliary audit worker randomly picks $0.01%$ of groups, computes the naive single-node intersection of raw events, and verifies the output against the distributed job's results in the KV store.