Multi-Tenant Ad Delivery and Performance Analytics Platform
System DesignModel answerLast updated
Architect a multi-tenant ad server and analytics engine that reliably serving ads, deduplicates metrics, and aggregates cross-campaign performance stats.
Architect an end-to-end advertising system capable of hosting multiple distinct organizations, serving targeted ads under low latency, tracking user interaction events, and serving deduplicated performance metrics to compare ad effectiveness across campaigns.
Key Requirements
- Campaign & Ad Management: Allow multiple organization accounts to upload, update, and manage their creative assets, targeting criteria, and budget parameters.
- Ad Selection & Serving: Process incoming ad requests from publisher placements, filter and select eligible ads based on targeting rules, and return the response within strict latency budgets (< 50ms).
- Event Ingestion & Deduplication: Capture lifecycle events (impressions, clicks, conversions) reliably. Filter out spam, duplicate impressions, and late-arriving events.
- Analytics & Fair Comparison: Store and aggregate metrics to enable tenant-isolated dashboards and fair, normalized performance comparisons between different ads and campaigns.
Key Constraints & Considerations
- Clarify latency SLAs, scale (QPS for serving vs. event ingestion throughput), and consistency requirements.
- Account for tenant isolation: an organization should never access another organization's raw data.
- Detail how duplicate clicks or impressions are identified and handled in high-throughput streaming environments.
Hints
Hint 1
Break the architecture down into distinct paths: a low-latency read/serving path, a high-throughput event ingestion path, and an asynchronous analytical/aggregation path.
Hint 2
To prevent double-counting impressions or clicks, use unique transaction/impression tokens generated at ad-serving time with a sliding-window cache or stream processing key (e.g., Redis or Flink state).
Hint 3
When measuring comparative performance across campaigns, raw click counts are insufficient due to differences in reach; consider normalized metrics like CTR, CPC, or statistical significance tests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scope Clarification
Functional Requirements
- Tenant & Campaign Management: Organizations manage campaigns (budgets, schedules, targeting criteria, and ad creatives).
- Ad Serving (Real-Time Path): Given a user request context (user location, device type, publisher placement), return the most relevant creative in < 50 ms.
- Event Logging & Deduplication: Capture impression, click, and conversion events, ensuring duplicate or fraudulent triggers are filtered out.
- Analytics & Reporting: Provide real-time and historical dashboards to compare ad performance using metrics like Click-Through Rate (CTR) and Conversion Rate (CVR).
Non-Functional Requirements & Scale
- Read (Ad Serving) Scale: 100,000 QPS global ad request load. Strict p99 latency < 50ms.
- Write (Event Streaming) Scale: ~500,000 events/sec (impressions outnumber requests when multiple ad slots exist; clicks are ~1-2% of impressions).
- Availability: 99.99% for ad serving (downtime directly loses revenue).
- Consistency: Eventual consistency for reporting analytics; strong data isolation across organizational tenants.
2. High-Level Architecture
┌─────────────────────────┐
│ Advertiser Portal / │
│ Management API │
└────────────┬────────────┘
│
▼
┌──────────────┐ ┌─────────────────────────┐
│ Publisher / │ │ Campaign DB (SQL) │
│ Client App │ └────────────┬────────────┘
└──────┬───────┘ │ Async Sync
│ ▼
│ Ad Request ┌─────────────────────────┐
├──────────────►│ Ad Serving Service │◄─── Cache (Redis Cluster)
│ └────────────┬────────────┘
│ Ad Response │
│ (w/ Signed Token) │ Emit Ad Served Event
▼ ▼
┌──────────────┐ ┌─────────────────────────┐
│ Event Tracker│──────►│ Ingestion Gateway API │
│ (Client Side)│ └────────────┬────────────┘
└──────────────┘ │
▼
┌─────────────────────────┐
│ Kafka Event Streaming │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ Flink Deduplication & │◄─── Stateful Token Store
│ Aggregation Engine │ (RocksDB / Redis)
└────────────┬────────────┘
│
┌────────────────┴────────────────┐
▼ ▼
┌─────────────────────────┐ ┌─────────────────────────┐
│ ClickHouse / Pinot │ │ Data Lake (S3/Parquet) │
│ (OLAP Dashboard DB) │ │ (Batch / Deep ML) │
└─────────────────────────┘ └─────────────────────────┘
3. Detailed Component Design
A. Ad Management & Serving Path (Low Latency)
- Storage: Active campaign metadata, targeting rules, and creative references are stored in a primary relational database (e.g., PostgreSQL).
- In-Memory Caching: To achieve sub-50ms latency, active ads and targeting indices are synced to distributed memory caches (e.g., Redis Cluster) deployed close to edge locations.
- Ad Selection Algorithm:
- Filtering: Match request context (Geo IP, Device, User Demographics) against campaign targeting rules.
- Scoring/Auction: Rank remaining ads using a scoring function: $$\text{Score} = \text{eCPM} = \text{Bid Price} \times \text{pCTR} \times \text{pCVR}$$ (Where $\text{pCTR}$ is predicted click-through rate, estimated via a machine learning model).
- Impression Token Generation:
- Upon selecting an ad, the serving engine generates an encrypted, time-stamped Impression Token: $$\text{Token} = \text{HMAC_Sign}(\text{ImpressionID} \parallel \text{TenantID} \parallel \text{AdID} \parallel \text{Timestamp})$$
- This token is embedded in the creative payload sent to the client browser/app.
B. Event Tracking & Deduplication Engine (High Throughput)
When an ad is rendered (Impression) or clicked (Click), the client fires a lightweight beacon containing the encrypted Impression Token.
- Ingestion Gateway: Stateless REST nodes validate token signatures to prevent spoofing, appending a server timestamp before publishing to Apache Kafka.
- Deduplication Strategy (Stream Processing with Apache Flink):
- Windowing: Maintain a rolling 1-hour state window indexed by
ImpressionID. - Stateful Store: Flink uses RocksDB backed by key-value lookups.
- Logic:
- If
ImpressionIDis received for the first time: emit tovalid_impressionsstream and storeImpressionIDin memory with a 1-hour TTL. - If
ImpressionIDexists in state: discard as duplicate/fraud. - Clicks must match a pre-existing, valid
ImpressionIDin the state engine within a reasonable window (e.g., 30 minutes).
- If
- Windowing: Maintain a rolling 1-hour state window indexed by
C. Analytics & Reporting Layer (OLAP)
- Analytical Database: Validated, aggregated streams are sinked into a distributed column-oriented database like ClickHouse or Apache Pinot.
- Data Schema (Optimized for Multi-Tenancy):
- Table Partitioning by
TenantIDandEventDate. - Primary Keys:
(TenantID, CampaignID, AdID, Timestamp). - Columnar layout allows real-time aggregations (e.g., calculating CTR over millions of rows in milliseconds).
- Table Partitioning by
SELECT
ad_id,
COUNT(CASE WHEN event_type = 'impression' THEN 1 END) AS total_impressions,
COUNT(CASE WHEN event_type = 'click' THEN 1 END) AS total_clicks,
(COUNT(CASE WHEN event_type = 'click' THEN 1 END) * 1.0 /
NULLIF(COUNT(CASE WHEN event_type = 'impression' THEN 1 END), 0)) AS ctr
FROM ad_events
WHERE tenant_id = 'org_123'
AND timestamp >= NOW() - INTERVAL '7 DAYS'
GROUP BY ad_id;
4. Fair Performance Comparisons across Campaigns
To fairly compare different ads across organizations or campaigns without bias, raw counts are insufficient due to confounding variables (e.g., audience size, placement quality, time of day).
-
Normalized Performance Metrics:
- CTR (Click-Through Rate): $\frac{\text{Clicks}}{\text{Impressions}}$
- CVR (Conversion Rate): $\frac{\text{Conversions}}{\text{Clicks}}$
- eCPM (Effective Cost Per Mille): Revenue generated per 1,000 impressions.
-
Statistical Significance Testing:
- When comparing two creative variants (A/B testing), calculate the $Z$-score or run a Chi-Square test on CTR to ensure performance differences are statistically significant before declaring a winner: $$Z = \frac{p_A - p_B}{\sqrt{p_{pool}(1 - p_{pool}) \left(\frac{1}{n_A} + \frac{1}{n_B}\right)}}$$ (Where $p_A, p_B$ are sample CTRs, and $n_A, n_B$ are total impressions).
-
Multi-Armed Bandit Integration:
- Instead of static allocations, use Thompson Sampling or Upper Confidence Bound (UCB) algorithms in the ad-serving layer to dynamically shift traffic toward higher-performing creatives over time while continuing to explore newer/under-sampled ads.
5. Edge Cases & System Trade-Offs
| Challenge | Solution / Trade-Off |
|---|---|
| Late-Arriving Events | Use Flink Event-Time Processing with allowed lateness (watermarks) up to 24 hours. Late events write directly to long-term OLAP storage rather than updating fast in-memory windows. |
| Tenant Data Leakage | Enforce tenant isolation at the API gateway layer using Row-Level Security (RLS) and strict multi-tenant authorization filters on all analytical queries. |
| Ad Click Flooding (DDoS/Spam) | Implement sliding-window rate limiting per IP/Device ID at the Ingestion Gateway alongside token-level deduplication in Flink. |
| Storage Growth | Raw event logs are archived to cold object storage (S3/Parquet) after 30 days. Historical queries beyond 30 days hit pre-aggregated rollup tables in ClickHouse (hourly/daily metrics). |