Design an Enterprise Event Analytics and Tracking Platform
System DesignModel answerLast updated
Design an end-to-end event collection, processing, and storage platform supporting interactive dashboard queries and deep historical analytics.
Problem
Design a scalable Enterprise Event Analytics and Tracking Platform that captures, enriches, and serves user interactions across multiple web and mobile client applications.
The platform must ingest events (e.g., button_click, view_item, complete_checkout), collect payload data via client-side libraries and backend HTTP APIs, and deliver data to two distinct analytical query patterns:
- Interactive Metrics & Dashboards: Sub-second to low-second P95 latencies for real-time aggregation, filtering, conversion funnels, and high-level engagement metrics (such as DAU/WAU/MAU). Freshness lag target is under 3 minutes.
- Deep Historical Analytics & Data Science: Ad-hoc queries across multi-terabyte datasets spanning up to 13 months of historical log data.
The engine must also provide contextual enrichment (such as IP-to-geo resolution and user profile lookup) and enforce data privacy and compliance guidelines (e.g., PII tokenization, data residency enforcement, and deletion requests).
Scale & Requirements
- Ingestion Volumetrics: Average throughput of 50,000 events per second (EPS), peaking at 250,000 EPS during high-traffic events. Average compressed JSON event size is ~1 KB.
- Storage Retention: 30 days of granular data in hot/warm serving stores for interactive dashboards; 13 months of data in cold storage for deep analytics.
- Freshness & Latency: Dashboards should reflect events within 1 to 3 minutes of generation. Interactive dashboard P95 query latency should be < 2 seconds.
- Delivery & Accuracy: At-least-once ingestion combined with downstream deduplication to ensure exact metric counts. Zero tolerated data loss for verified client events.
Key Aspects to Cover
- Capacity & Volume Projections: Estimate network bandwidth, daily storage footprint, and peak ingestion throughput.
- End-to-End Architecture: Outline the path from SDK client collectors to API gateways, message queues, stream processors, and serving data stores.
- Data Contract & Schema Management: Formulate a extensible schema structure, schema versioning strategy, registry validation, and dead-letter queue (DLQ) path for corrupted payloads.
- Client SDK & Ingestion Mechanics: Explain client-side batching, retries under unstable network conditions, offline queueing, stateless server ingestion, and partition routing.
- Dual-Tier Storage Design: Select and justify storage technologies for low-latency interactive queries versus cost-efficient long-term historical storage.
- Enrichment & Compliance Architecture: Detail the placement of real-time stream enrichment vs. offline batch processing, identity resolution, PII masking, and data deletion workflows.
Hints
Hint 1
Calculate storage and network bandwidth early: 250K EPS at 1 KB per payload creates significant ingress bandwidth and daily storage requirements.
Hint 2
Decouple the ingestion pipeline completely from serving paths using a durable, partitioned commit log (e.g., Apache Kafka or AWS Kinesis).
Hint 3
Distinguish between client-side generation timestamps and server ingress timestamps to handle network delays and offline event batching.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Level System Architecture
To decouple heavy write workloads from interactive and batch analytical read workloads, the system uses an event-driven architecture with a durable streaming buffer.
[Mobile SDK / Web SDK] ──┐
├──> [API Gateway / Ingestion Nodes] ──> [Kafka Event Log]
[Backend Microservices] ─┘ │
├─> [Stream Engine (Flink)] ─> [ClickHouse / Pinot] (Dashboards)
│
└─> [Batch Ingestion (S3)] ─> [Iceberg / Parquet] (Snowflake/Trino)
Core Architecture Components
-
Edge Collectors & Ingestion Layer:
- Stateless, auto-scaling API servers running behind a Geo-DNS routing Layer 7 load balancer.
- Performs TLS termination, basic rate limiting, initial authorization validation, structural payload validation, and server timestamp tagging before pushing raw messages to the streaming buffer.
-
Durable Message Log (Ingestion Buffer):
- Technology: Apache Kafka or AWS Kinesis.
- Serves as an immutable append-only log providing a buffer between ingestion and downstream consumers.
- Partitioned by
workspace_idoruser_idto guarantee ordering per entity while enabling massive horizontal scalability.
-
Stream Processing Layer:
- Technology: Apache Flink or Spark Streaming.
- Consumes events from Kafka to perform real-time validation, IP-to-Geo enrichment, PII masking, exact-once deduplication windowing, and streaming aggregations.
- Routes parsed events to the hot analytical store and raw/unstructured events to object storage.
-
Dual Storage Layer:
- Hot / Interactive Store (ClickHouse or Apache Pinot): Columnar, real-time OLAP database optimized for slice-and-dice aggregations, high-cardinality indexing, and fast filtering across hot window periods (last 30 days).
- Cold / Historical Lakehouse (S3 / GCS + Apache Iceberg / Parquet): Cost-efficient, columnar object storage layer structured for long-term historical queries executed via query engines like Snowflake, Databricks, or Trino.
Capacity Estimation & Volumetrics
Ingestion Throughput
- Average Events/Sec: $50,000\text{ EPS}$
- Peak Events/Sec: $250,000\text{ EPS}$
- Average Payload Size: $1\text{ KB}$ (JSON serialized)
Network Bandwidth
- Average Ingestion Ingress: $50,000 \times 1\text{ KB} = 50\text{ MB/s} = 400\text{ Mbps}$
- Peak Ingestion Ingress: $250,000 \times 1\text{ KB} = 250\text{ MB/s} = 2.0\text{ Gbps}$
Storage Footprint
- Uncompressed Daily Raw Data: $$50,000\text{ EPS} \times 86,400\text{ s/day} \times 1\text{ KB} \approx 4.32\text{ TB/day}$$
- Compressed Daily Storage (assuming standard 4:1 compression ratio in Parquet/ClickHouse format): $$\approx 1.08\text{ TB/compressed data per day}$$
- Hot Tier (30-day retention in ClickHouse): $$30\text{ days} \times 1.08\text{ TB/day} \approx 32.4\text{ TB}$$
- Cold Tier (13-month / 395-day retention in Lakehouse): $$395\text{ days} \times 1.08\text{ TB/day} \approx 426.6\text{ TB}$$
Data Model & Schema Evolution
To balance strict type safety with flexibility across different products, events use a hybrid schema format: top-level strongly typed canonical fields combined with typed dynamic payload maps.
{
"event_id": "a1b2c3d4-e5f6-7890-abcd-1234567890ab",
"app_id": "product_checkout_prod",
"event_name": "payment_completed",
"schema_version": "2.1.0",
"client_timestamp": 1700000000123,
"server_timestamp": 1700000000185,
"user_id": "usr_998877",
"anonymous_id": "anon_sess_554433",
"device_context": {
"os": "iOS",
"os_version": "17.2",
"app_version": "4.12.0",
"ip_address": "198.51.100.42",
"user_agent": "Mozilla/5.0..."
},
"traits": {
"currency": "USD",
"amount": 149.99,
"item_count": 3,
"is_first_purchase": false
}
}
Schema Governance & Evolution Rules
- Schema Registry: Enforce contract validation using JSON Schema or Protocol Buffers backed by a centralized schema registry service (e.g., Confluent Schema Registry).
- Backward and Forward Compatibility Rules:
- Allowed: Adding optional/nullable fields; deprecating fields.
- Forbidden: Changing fundamental data types (e.g., String to Integer), renaming existing fields without aliases, or removing required top-level attributes.
- Dead-Letter Queue (DLQ) Quarantine Flow:
- Events failing JSON structure validation or schema verification are tagged with error metadata and written to a separate Kafka DLQ (
events.malformed). - Prevents malformed client payload releases from blocking streaming ingestion pipelines or corrupting downstream analytical databases.
- Engineering teams monitor DLQ rates and reprocess payload streams once schema configurations are updated.
- Events failing JSON structure validation or schema verification are tagged with error metadata and written to a separate Kafka DLQ (
Client SDK Design & Ingestion Mechanics
Client SDK Interface
┌────────────────────────────────────────────────────────┐
│ - In-Memory Event Queue │
│ - Local SQLite / IndexedDB Persistent Store │
│ - Batching Aggregator (Size: 100 events, Time: 5s) │
│ - Network State Listener & Retry Backoff Engine │
└───────────────────────────┬────────────────────────────┘
│ HTTPS POST /v1/batch
v
API Gateway / Ingestion Layer (Stateless Autoscaling Node)
┌────────────────────────────────────────────────────────┐
│ - TLS Termination & Rate Limiting │
│ - Schema Structure & Envelope Validation │
│ - Server Timestamp Tagging (`server_timestamp`) │
│ - Partitioning Key Assignment (`user_id` / `anon_id`) │
└───────────────────────────┬────────────────────────────┘
│ Produce Record
v
Kafka Topic Cluster (`events.raw`)
Client SDK Logic & Resilience Strategies
- Adaptive Batching Strategy: The client SDK buffers events in memory and flushes them to the ingestion endpoint when:
- The batch count reaches 100 events, OR
- The timer reaches a max flush interval of 5 seconds, OR
- The application goes into a background lifecycle state.
- Network Interruption Handling & Storage: On network loss, events persist to a local durable storage engine (SQLite for mobile apps, IndexedDB for web applications).
- Exponential Retry & Jitter: Retries trigger with exponential backoff and random jitter (
delay = min(max_delay, base * 2^attempt + jitter)) to prevent thundering herd spikes when connectivity returns. - Timestamp Handling:
client_timestamp: Clock recorded by device at event origination. Subject to device clock drift or local clock manipulation.server_timestamp: UTC timestamp assigned by collector nodes upon physical receipt.- Stream processing filters anomalous events (e.g.,
client_timestamp>server_timestamp+ 5 minutes or <server_timestamp- 7 days).
Real-Time Enrichment & Privacy Architecture
Kafka `events.raw`
│
v
┌──────────────────────────────┐
│ Apache Flink Streaming Core │
└───────────────┬──────────────┘
│
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ IP -> Geo │ │ PII Mask │ │ Identity │
│ Lookup │ │ & Hash │ │ Resolution│
└─────┬─────┘ └─────┬─────┘ └─────┬─────┘
│ (MaxMind MMDB) │ (HMAC-SHA256) │ (KV Cache/Redis)
└───────────────────────┼───────────────────────┘
│
v
Kafka `events.enriched`
Processing Pipeline Details
- IP-to-Location Enrichment: Fast, local, in-memory IP lookup (e.g., MaxMind GeoIP2 MMDB files refreshed via sidecar container processes) transforms IP addresses into geolocation traits (country, state, city) without introducing network latency.
- Identity Resolution & Stitching:
- Anonymous users receive a UUID stored in browser dynamic storage or secure device keychains.
- When users log in, an identity mapping event binds
anonymous_idtouser_idin a low-latency key-value cache (e.g., Redis cluster). - Stream processors stitch historical event profiles retroactively or join session identities within a tumbling time window.
- PII Anonymization & Security:
- PII attributes (IP addresses, user emails, raw names) are tokenized or hashed using salt-rotated
HMAC-SHA256keys before reaching persistent storage layers. - Full unmasked PII stays restricted to isolated microservice boundary layers with strict RBAC audit access.
- PII attributes (IP addresses, user emails, raw names) are tokenized or hashed using salt-rotated
- Data Deletion Compliance (GDPR / CCPA):
- Hot Store (ClickHouse): Uses lightweight delete partitions or
ALTER TABLE UPDATE / DELETEqueries targetinguser_id. - Cold Lakehouse (Iceberg): Employs Apache Iceberg partition rewrites or copy-on-write mechanisms via targeted Spark data processing jobs to scrub deleted records across analytical data stores.
- Hot Store (ClickHouse): Uses lightweight delete partitions or
Storage Layer Strategy: Hot vs. Cold Serving Engine
| Functional Feature | Hot Storage Engine (ClickHouse / Pinot) | Cold Lakehouse Engine (Iceberg / S3 + Trino) |
|---|---|---|
| Primary Workload | Interactive dashboards, funnels, real-time slice-and-dice | Ad-hoc analytics, data science, deep history |
| Target Query Latency | < 500 ms – 2 seconds | 10 seconds – several minutes |
| Data Retention Window | 30 Days | 13 Months+ |
| Partitioning Strategy | Primary Key: (app_id, toYYYYMM(event_date), event_name, user_id) | year=YYYY/month=MM/day=DD/app_id= |
| Storage Format | Native Columnar Vectorized Storage Format | Compressed Parquet (Snappy or ZSTD) |
Optimization Techniques for High-Cardinality Real-Time Queries
- Materialized Views & Aggregation States:
ClickHouse
AggregatingMergeTreetables compute continuous real-time aggregations for canonical metrics (such as unique active users or total daily events) grouped by time intervals, skipping expensive full-table scans. - HyperLogLog (HLL) Cardinality Estimation: Rather than storing distinct raw user IDs for long-term active user analytics, calculate approximate distinct counts (DAU/WAU/MAU) using HyperLogLog data structures. This delivers 99%+ count accuracy while reducing storage footprint and compute costs by multiple orders of magnitude.
- Optimized Primary Key & Ordering Indexing:
Sorting physical records on disk by
(app_id, event_name, event_date, user_id)enables binary search skip-indexing over block headers, scanning only target event files during dashboard execution.
Trade-offs, Operational Risks & Mitigation Matrix
1. Ingestion Backpressure & Partition Bottlenecks
- Risk: High event volumes during promotional campaigns could overwhelm stream consumers, generating long processing lag.
- Mitigation: Partition Kafka streams by high-cardinality keys like
user_idorsession_id(rather than low-cardinality keys likeevent_nameorapp_id) to ensure even message distribution across all consumer instances. Implement auto-scaling strategies based on Kafka consumer lag metrics (records-lag-max).
2. Client Clock Drift and Delayed Event Batches
- Risk: Offline mobile SDKs uploading accumulated event logs days late can corrupt aggregate time-series metric tables.
- Mitigation: Process late-arriving events through streaming logic using watermark bounds (e.g., maximum allowable lag of 2 hours). Route events with timestamps older than 2 hours directly to the cold lakehouse tier for historical backfill updates rather than pushing them to hot real-time metrics tables.
3. High Cardinality Dynamic Payload Properties
- Risk: Developers emitting dynamic JSON tags (e.g., random UUID keys inside properties) can exhaust columnar indexes in databases like ClickHouse.
- Mitigation: Enforce payload parameter depth limits. Store unpredictable dynamic event properties inside a single compressed JSON map column (e.g., ClickHouse
JSONorObject(Nullable(String))type) while indexing only pre-approved, schema-validated top-level properties.