Year-Long Ad Click Aggregation with External Logging Integration
System DesignModel answerLast updated
Design an aggregator that answers queries over a rolling one-year window of ad clicks, ingesting from an existing logging API rather than a real-time stream.
You are tasked with building an aggregation service for advertising click data. The system must support queries that span up to one year of historical data, and all click events arrive via an external logging API that your team does not control.
This problem differs from the typical real-time click counter in two critical ways: the query window extends to a full year rather than minutes or hours, and you must work within the constraints of a third-party logging interface instead of designing your own event pipeline.
What You Should Clarify
Before proposing a design, ask questions to understand:
- Time window semantics: Does "last year" mean a rolling 365-day window, the most recent calendar year, or arbitrary ranges within the past year?
- Logging API characteristics: Does it offer a push stream, a pull-based query interface, or periodic batch dumps? What are its delivery semantics (at-least-once, exactly-once, best-effort), latency, throughput limits, and can it serve historical data for backfills?
- Query patterns: What dimensions are queried (per ad, per campaign, per advertiser)? What time granularities (hourly, daily)? What is the expected query latency and volume?
- Accuracy requirements: Are counts used for billing (requiring exact deduplication and auditability) or analytics dashboards (where approximation is acceptable)?
- Scale: How many distinct ads exist? What is the daily click volume? What query throughput must the system sustain?
- Data quality: Must the system filter invalid or fraudulent clicks before aggregating?
What You Should Deliver
Present a complete architecture that addresses ingestion from the external API, storage optimized for year-long queries, query serving, and operational concerns such as backfill, correctness guarantees, and failure recovery.
Hints
Hint 1
Think about how pre-aggregation at different time granularities can make year-long queries efficient without scanning raw events.
Hint 2
Consider how you will track ingestion progress and handle replay or backfill when the logging API allows it.
Hint 3
Deduplication across a year requires a different strategy than keeping recent IDs in memory—what persistent, space-efficient structure fits?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong answer begins by clarifying requirements, then derives an architecture tailored to the one-year horizon and the external logging API. The key insight is that querying a year of raw click events is prohibitively expensive, so the system must pre-aggregate data at chosen time granularities and dimensions, while still handling late arrivals, deduplication, and correctness.
Requirements Clarification
Start by establishing concrete requirements:
Time semantics: Assume a rolling 365-day window ending at the current moment. Queries ask for counts over arbitrary date ranges within that window.
Logging API: Suppose it exposes a pull-based interface that returns click events in time-ordered batches, with at-least-once delivery. It supports resuming from a checkpoint (e.g., a timestamp or offset) and can serve historical data for backfill. Rate limit: 10,000 events per second.
Query patterns: Queries request total clicks grouped by ad ID, optionally filtered by campaign or advertiser, with daily or hourly breakdowns. Expected latency: under 200 ms. Query load: 500 QPS.
Accuracy: Counts are used for billing, so exact deduplication is required. Each click has a unique ID.
Scale: 10 million active ads, 10 billion clicks per day globally, resulting in roughly 3.65 trillion clicks per year.
Fraud filtering: Assume a separate fraud-detection service marks clicks as valid or invalid; only valid clicks are counted.
High-Level Architecture
Components:
- Ingestion Service: Pulls click events from the logging API, checkpoints progress, and writes to raw storage.
- Deduplication Layer: Ensures each click ID is counted once, even if delivered multiple times.
- Aggregation Pipeline: Pre-computes rollups at multiple granularities (hourly, daily) for all relevant dimensions (ad, campaign, advertiser).
- Rollup Storage: Stores aggregated counts in a format optimized for range queries.
- Query Service: Serves requests by reading from rollup storage, merging granularities as needed.
- Backfill & Correction Service: Rebuilds aggregates when ingestion fails or data corrections arrive.
Detailed Design
Ingestion
The ingestion service polls the logging API continuously. It maintains a checkpoint (e.g., the timestamp of the last successfully processed event) in a durable store (e.g., a database or distributed coordination service like ZooKeeper). On restart, it resumes from the checkpoint.
Each batch of events is written to a raw event store (e.g., append-only object storage like S3, partitioned by ingestion timestamp) for durability and backfill. Writing raw events before aggregation ensures we can reprocess if a bug is discovered.
Rate limiting: If the logging API rate-limits us, the ingestion service backs off and retries, ensuring we never drop data.
Deduplication
Since the logging API provides at-least-once delivery, duplicates are possible. Each click carries a unique ID. We track seen IDs in a persistent Bloom filter or a distributed deduplication table (e.g., a key-value store with a TTL of 1 year + buffer).
For every incoming click, we check the deduplication store:
- If the ID exists, discard the duplicate.
- Otherwise, insert the ID and proceed with aggregation.
Space concern: Storing 3.65 trillion unique IDs naively (16 bytes each) requires ~58 PB. Instead, use a Bloom filter with acceptable false-positive rate (~1%), reducing space to a few TB, or a distributed hash table sharded by click ID with expiration.
Aggregation Pipeline
Rather than querying raw events, we pre-aggregate at two levels:
- Hourly rollups: For each hour, compute counts per (ad_id, hour, campaign_id, advertiser_id). Store in a table partitioned by date.
- Daily rollups: Aggregate hourly data into daily counts per (ad_id, date, campaign_id, advertiser_id).
The pipeline runs continuously, consuming deduplicated events from a queue (e.g., Kafka) or directly from the ingestion service. It writes aggregates to a columnar store (e.g., ClickHouse, BigQuery, or a time-series database like TimescaleDB) optimized for analytical range queries.
Why two levels? Daily rollups answer most queries quickly (365 rows per ad for a year), but hourly rollups provide finer granularity when needed without scanning raw events.
Rollup Storage
Store aggregates in a partitioned table:
hourly_clicks:
ad_id, campaign_id, advertiser_id, hour_timestamp, click_count
daily_clicks:
ad_id, campaign_id, advertiser_id, date, click_count
Partition by date to enable efficient retention (drop old partitions after 1 year + buffer). Index on ad_id, campaign_id, and advertiser_id for fast filtering.
Space estimate: Assume 10M ads, 365 days: 3.65 billion rows in daily rollups. Each row ~40 bytes → ~146 GB uncompressed, ~30 GB compressed. Hourly rollups: 24× larger, ~700 GB compressed. Manageable.
Query Service
For a query like "total clicks for ad X between dates D1 and D2":
- If D1 and D2 align with day boundaries, sum daily rollups:
SELECT SUM(click_count) FROM daily_clicks WHERE ad_id = X AND date BETWEEN D1 AND D2. - If the range includes partial days, use hourly rollups for those edges and daily rollups for the middle.
Latency: With proper indexing, range queries over 365 days return in <100 ms. Caching common queries (e.g., "last 30 days for top 1000 ads") reduces load.
Backfill and Correction
If ingestion stops or a bug corrupts aggregates, we reprocess from raw storage:
- The backfill service reads raw events for the affected time range.
- It re-applies deduplication and re-computes rollups.
- It writes corrected aggregates, overwriting or merging with existing data.
Idempotency: The aggregation pipeline should be idempotent—reprocessing the same raw events yields the same rollups, so backfill can safely overwrite.
Handling Late and Out-of-Order Events
The logging API may deliver events late (e.g., a click that occurred yesterday arrives today). The aggregation pipeline groups events by their event timestamp (not ingestion time). When a late event arrives:
- It updates the rollup for its event hour/day.
- If rollups are immutable (append-only), append a correction record; the query service sums all records for a given period.
- If rollups are mutable, update in place.
Grace period: Accept late arrivals up to 7 days. Beyond that, corrections require manual backfill.
Failure Handling and Monitoring
Ingestion failure: Checkpoints ensure we resume without data loss. Alert if ingestion lag exceeds a threshold (e.g., 1 hour behind real-time).
Aggregation failure: If the pipeline crashes, it restarts from the last committed offset in the event queue. Rollups are recomputed from queued events.
Data quality: Monitor for anomalies (sudden drop in click volume, duplicate spikes) and compare deduplicated vs. raw counts.
Common Mistakes
- Scanning raw events at query time: Infeasible at this scale. Pre-aggregation is essential.
- Ignoring deduplication: At-least-once delivery means duplicates will inflate counts unless explicitly handled.
- Not checkpointing ingestion: Without checkpoints, restarts may skip or double-count data.
- Immutable storage for corrections: If late events or bug fixes require updating old aggregates, purely append-only storage complicates correction.
- Under-provisioning storage: A year of hourly rollups for 10M ads is non-trivial; estimate and validate space requirements.
Complexity and Trade-offs
Time complexity: Queries scan O(days in range × ads matching filter) rows, typically <1000 rows per query with indexes.
Space complexity: O(ads × hours in a year) for hourly rollups, O(ads × 365) for daily. Compression and partitioning keep this manageable.
Consistency vs. freshness: Aggregates lag raw events by minutes. For billing, eventual consistency is acceptable if late events are reconciled within the grace period.
Summary
The architecture ingests from the logging API with checkpointed pulls, deduplicates using a persistent store, pre-aggregates into hourly and daily rollups stored in a columnar database, and serves queries by summing rollups over the requested range. Backfill and correction mechanisms ensure accuracy despite failures or late data. This design handles the one-year horizon and external API constraints efficiently, avoiding common pitfalls of naive raw-event queries.