Ad Campaign Event Aggregator with Pluggable Event Types
Data Structure DesignModel answerLast updated
Design an object-oriented component that ingests ad events and returns windowed per-campaign metric sums and ratios, while letting new event types be added without editing core code.
Build a Campaign Metrics Aggregator
You are designing the core of a service that watches a stream of advertising events and answers questions about campaign performance. Events such as clicks, impressions and conversions arrive one at a time. At any moment, a caller may ask for a metric of one campaign over a time window.
What to deliver
Sketch the classes and method signatures for this component, explain how data flows through them, and implement the main parts in code (Python or a language of your choice).
Requirements
- Pluggable event types. A developer must be able to introduce a new kind of event (for example
video_vieworhover) without changing the ingestion or query code that already exists. - Windowed sums. Given a
campaign_idand an inclusive time range[start_time, end_time], return the total of a named base metric (such as clicks or spend) for that campaign. - Derived metrics. Support ratio-style metrics such as click-through rate (clicks divided by impressions) and conversion rate over the same window.
- Public interface. Define the classes and methods used to record events and to fetch metrics.
Constraints
- Events are delivered in order of arrival, and you may assume timestamps are mostly non-decreasing.
- Concentrate on class structure and API design. Durable storage and distributed deployment are out of scope; an in-memory design is fine.
- The result should be decoupled, readable and easy to maintain.
Example usage
tracker = MetricsTracker()
tracker.record_event(ClickEvent(campaign_id="C1", timestamp=100, cost=0.5))
tracker.record_event(ImpressionEvent(campaign_id="C1", timestamp=101))
total_clicks = tracker.get_metric("C1", "clicks", start=0, end=200) # 1
Discussion points to cover
- How the tracker avoids branching on event type.
- How range queries stay fast as data grows.
- Where ratio metrics are computed, and why.
- How you handle empty windows, unknown campaigns, a zero denominator and an out-of-order event.
Hints
Hint 1
Let each event describe its own contribution: give the event base class a method that returns a mapping from base metric names to numeric values. The tracker then only loops over that mapping and never inspects the concrete class.
Hint 2
Keep one time-ordered series per (campaign, metric) pair, storing a running prefix sum. An inclusive range sum becomes two binary searches (left bound for start, right bound for end) and a subtraction.
Hint 3
A ratio such as CTR cannot be added across events or buckets. Store only base sums, and compute derived metrics at query time from windowed sums using a registry of small formula functions. Decide and state what you return when the denominator is zero.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Separate three concerns, and extensibility follows from the structure:
- What an event contributes is decided by polymorphism on event classes.
- How contributions are stored and summed over time is the job of a time-series store.
- How higher-level metrics are derived is handled by a registry of formulas evaluated at query time.
1. Events declare their own contributions
An abstract Event holds campaign_id and timestamp, and has one abstract method, metrics(), returning a mapping from base metric name to value.
ClickEventreturns{"clicks": 1, "spend": cost}ImpressionEventreturns{"impressions": 1, "spend": cost}(cost may be nonzero for CPM billing)ConversionEventreturns{"conversions": 1, "revenue": value}- A new
VideoViewEventreturns{"video_views": 1}
record_event calls event.metrics() and pushes each pair into storage. It never checks the event's type, so adding a type means adding one subclass. This is the open/closed principle applied directly. A common mistake is an if event_type == "click" chain inside the tracker, which breaks requirement 1.
2. Storage: prefix sums per (campaign, metric)
Keep a dictionary keyed by (campaign_id, metric), with each value a TimeSeries containing:
- a sorted list of timestamps,
- a list of values,
- a prefix array where
prefix[i]is the sum of the firstivalues.
Because events arrive in order, add appends in O(1). A range sum over inclusive [start, end] is:
lo = bisect_left(ts, start) # first index with timestamp >= start
hi = bisect_right(ts, end) # one past last index with timestamp <= end
return prefix[hi] - prefix[lo]
Using bisect_left for the start and bisect_right for the end makes both bounds inclusive and keeps duplicate timestamps correct.
class TimeSeries:
def __init__(self):
self.ts, self.vals, self.prefix = [], [], [0.0]
def add(self, t, v):
if not self.ts or t >= self.ts[-1]:
self.ts.append(t); self.vals.append(v)
self.prefix.append(self.prefix[-1] + v)
return
i = bisect_right(self.ts, t) # out-of-order fallback
self.ts.insert(i, t); self.vals.insert(i, v)
del self.prefix[i + 1:]
for x in self.vals[i:]:
self.prefix.append(self.prefix[-1] + x)
def range_sum(self, s, e):
if s > e:
return 0.0
return self.prefix[bisect_right(self.ts, e)] - self.prefix[bisect_left(self.ts, s)]
3. Derived metrics at query time
Ratios cannot be summed or averaged across events or buckets. Averaging per-bucket CTRs over-weights sparse buckets. The correct window CTR is Σclicks / Σimpressions over that same window. So store only base metrics, and register derived ones as functions of a "windowed sum" callable:
class MetricsTracker:
def __init__(self):
self._series = {} # (campaign, metric) -> TimeSeries
self._derived = {
"ctr": lambda s: _ratio(s("clicks"), s("impressions")),
"conversion_rate": lambda s: _ratio(s("conversions"), s("clicks")),
"cpc": lambda s: _ratio(s("spend"), s("clicks")),
}
def record_event(self, ev):
for metric, value in ev.metrics().items():
self._series.setdefault((ev.campaign_id, metric), TimeSeries()) \
.add(ev.timestamp, value)
def register_derived(self, name, fn):
self._derived[name] = fn
def get_metric(self, campaign, metric, start, end):
def base(m):
ts = self._series.get((campaign, m))
return ts.range_sum(start, end) if ts else 0.0
if metric in self._derived:
return self._derived[metric](base)
return base(metric)
def _ratio(n, d):
return n / d if d else 0.0
New derived metrics are added with register_derived, with no changes to storage or ingestion.
Complexity
Let n be the number of points in one series, k the number of base metrics an event emits (typically 1 to 2), and d the number of base metrics a formula uses.
| Operation | Time | Space |
|---|---|---|
record_event (in order) | O(k) amortized | O(k) per event |
record_event (out of order) | O(n) for each affected series | none extra |
get_metric (base) | O(log n) | O(1) |
get_metric (derived) | O(d log n) | O(1) |
Total memory is proportional to the number of emitted data points.
Edge cases
- Unknown campaign or metric, or empty window: return 0.0. A freshly added event type with no data is a valid zero, not an error.
start > end: return 0.0.- Zero denominator: return 0.0 and document it. Returning
Noneis also defensible, as long as it is a deliberate choice. - Equal timestamps: included, since the range is inclusive and the bisects treat ties consistently.
- Out-of-order event: insert at the sorted position and rebuild the prefix tail. Correct, but O(n); mention that a Fenwick tree gives O(log n) for both updates and queries if late data is common.
Trade-offs and follow-ups
- Unbounded memory: raw points grow forever. Roll old data into fixed buckets (per minute or hour) and query buckets for coarse windows, accepting reduced timestamp precision.
- Concurrency: use per-series locks or a single-writer queue, because appends and prefix updates must be atomic with respect to readers.
- Floating-point drift: long prefix sums of money can accumulate error. Use integer micro-currency units or
Decimalfor spend. - Scale-out: shard by
campaign_id, which keeps every query on one shard, and persist events in a log so state can be rebuilt. - Schema evolution: because events self-describe through
metrics(), new fields need no migration of the tracker.
Common mistakes
- Branching on event type inside the tracker.
- Storing CTR per event and averaging it.
- A linear scan per query instead of prefix sums plus binary search.
- Off-by-one errors from using
bisect_leftfor both bounds, which drops events at exactlyend. - Raising exceptions on empty windows or zero denominators without stating the contract.