Event Ingestion Pipeline with Semi-Structured Payloads
System DesignModel answerLast updated
Design a fault-tolerant pipeline that ingests 50k heterogeneous JSON events per second and serves both per-user lookups and 90-day aggregate analytics.
Background
A digital media platform tracks user interactions across its web and mobile clients. Every interaction — reading an article, completing a quiz, watching a video — produces a JSON event. Each event shares a common header:
{
"event_id": "uuid",
"timestamp": "2025-01-15T10:23:45Z",
"user_id": "u_9821",
"event_type": "video.play",
"source": "android",
"schema_version": 2,
"payload": { ... }
}
The payload field contains feature-specific metadata that varies by event_type and changes frequently as product teams ship new features.
What You Need to Design
Ingestion (50k events/s, spikes to ~150k/s) Describe how you accept events from client SDKs, buffer them durably, and hand them off to downstream consumers — all while keeping acknowledgement latency under 50 ms p99.
Schema flexibility
Product teams add, rename, and restructure payload fields regularly. Explain how to store and query the payload without blocking feature development behind a rigid migration process.
Storage for two distinct access patterns
- Investigative queries: fetch the last 10 events for a specific
user_idin under 100 ms. - Analytical queries: compute daily active users (DAU) and per-feature adoption rates over a rolling 90-day window, returning results in seconds.
Data lifecycle and cost control Raw event volumes compound quickly. Outline a tiering strategy that moves data to progressively cheaper storage as it ages while keeping long-term trend queries possible without full scans of raw data.
Discussion Points
- How does your design handle schema evolution — specifically field additions, renames, and type changes — without breaking existing consumers?
- How would you deduplicate events given that client SDKs retry on failure?
- What are the concrete trade-offs between a columnar analytical store (e.g., ClickHouse, BigQuery) and a key-value / operational store (e.g., DynamoDB, Cassandra) for the two access patterns above?
- How do you prevent a slow analytics query from affecting ingestion throughput?
What a Strong Answer Looks Like
A concrete architecture with named components, back-of-envelope sizing that motivates your choices, clear storage trade-offs, and a lifecycle plan with specific retention windows. You don't need to design every sub-system in depth, but each major component should have a clear rationale.
Hints
Hint 1
Start with numbers before drawing boxes. Derive daily volume (events/day, GB/day, compressed) and use those figures to justify every technology choice that follows.
Hint 2
Think about which part of the system is on the critical path for ingestion latency. The collector should do as little as possible synchronously — validation, buffering, and enrichment belong in separate stages.
Hint 3
Two access patterns almost always mean two stores. Map each store to its read pattern, then decide how data flows from the buffer into each one.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the System First
Before choosing any technology, derive the numbers that will constrain every decision.
| Dimension | Estimate |
|---|---|
| Sustained ingest | 50k events/s; design for 150k/s peak |
| Event size | ~1 KB JSON average |
| Raw throughput | ~50 MB/s sustained, ~150 MB/s peak |
| Daily volume | ~4.3 B events/day ≈ 4.3 TB/day raw |
| Columnar-compressed | ~5–10x smaller → ~0.5–0.8 TB/day stored |
| 90-day analytical window | ~50–70 TB compressed |
Two more things to clarify before designing: delivery semantics (assume at-least-once from clients with server-side deduplication → effectively exactly-once analytics) and PII/GDPR (payload fields may need deletion support).
2. Overall Architecture
Clients (SDK, batch flush every 5s)
│ POST /v1/events (batch)
▼
Load Balancer
▼
Collector Fleet (stateless)
│ acks=all, idempotent producer, zstd
▼
Kafka raw-events (~128 partitions, keyed by user_id, 3-day retention)
│
├──► Flink / Stream Consumer ──► Validator + Enricher ──► clean-events topic
│ │
│ ┌──────────────────┼──────────────────┐
│ ▼ ▼ ▼
│ DynamoDB ClickHouse / S3 Iceberg
│ (user timeline) BigQuery (raw archive)
└──► S3 sink (raw Parquet, for replay / long-term)
Why Kafka as the central buffer? It physically decouples ingestion latency from everything downstream. A slow analytical consumer only accumulates lag — it never blocks the collector from returning a 202 to the client. The 3-day retention window also gives a replay buffer when a consumer has a bug.
Why Kappa over Lambda? A single streaming codebase avoids maintaining parallel batch and stream logic that inevitably disagree on numbers. Backfills replay from Kafka or from the S3 raw archive through the same consumer code.
3. Ingestion: Collectors
Collectors are stateless HTTP services. They do exactly three things synchronously:
- Validate the header fields and enforce a size cap (~64 KB per batch).
- Produce the raw bytes to Kafka with
acks=alland idempotent producers. - Return
202 Accepted.
Client SDKs generate a UUID event_id before sending. On retry, the same ID is resent — this is what makes downstream deduplication possible. Batching on the client (flush every 5 s or 50 events, whichever comes first) cuts the HTTP request rate by 10–50x without meaningful latency impact for analytics.
If Kafka is temporarily unavailable, collectors spool to local disk rather than failing the client request. This keeps the 50 ms p99 ACK target achievable.
4. Schema Flexibility
Hybrid model: strongly typed header + semi-structured payload.
Store the seven header fields as proper typed columns. Store payload as a JSON column (ClickHouse JSON type, BigQuery JSON, or a String with JSONExtract helpers). This gives you:
- Columnar compression and pruning on the fields you always filter by (
event_type,timestamp,user_id). - Freedom for product teams to add payload fields without a migration.
Hot field promotion: When a payload field is queried frequently — say, payload.content_id — add a materialized column rather than parsing JSON at query time:
ALTER TABLE events
ADD COLUMN content_id String
MATERIALIZED JSONExtractString(payload, 'content_id');
Schema registry for governance: Each event_type registers a versioned JSON Schema. The registry is also the place to tag PII fields for deletion workflows. CI blocks a team from publishing an incompatible version.
Evolution rules:
- Adding a field — always backward compatible, no action required.
- Renaming — add the new field, dual-emit both names for a deprecation window, expose
COALESCE(new_name, old_name)in a view. - Type change — requires a new field name or a version bump; never mutate a field's type in place.
5. Storage: Two Patterns, Two Stores
Investigative queries — "last 10 events for user X"
Use DynamoDB or Cassandra.
- Partition key:
user_id; sort key:timestamp#event_id(descending query with LIMIT 10). - A single-partition read returns in single-digit milliseconds.
- TTL of 30–90 days caps storage cost; older lookups fall back to ClickHouse or Athena.
- Watch for hot partitions from bots. Rate-limit or sample high-velocity users at the enrichment stage.
Analytical queries — DAU and feature adoption over 90 days
Use ClickHouse or BigQuery.
- Partition by day, order/cluster by
(event_type, timestamp). Day + event_type filters prune nearly all data before scanning. - Deduplication:
ReplacingMergeTree(event_id)in ClickHouse; MERGE onevent_idin BigQuery. - Pre-aggregate DAU with HyperLogLog sketches. Store
uniqState(user_id)per day in anAggregatingMergeTreerollup. Merging sketches across date ranges answers 7-day, 30-day, and 90-day uniques without re-scanning raw rows. Feature adoption rate =uniq(user_id WHERE event_type = X)÷ DAU, both from the same rollup.
Trade-off summary
| Columnar (ClickHouse / BigQuery) | Operational (DynamoDB / Cassandra) | |
|---|---|---|
| Strength | Aggregate billions of rows; 10x compression | Sub-10 ms point reads; high write concurrency |
| Weakness | Slow point lookups; expensive deletes/updates | Full scans are costly; poor for aggregations |
| Schema | Typed columns + JSON; easy to add columns | Schemaless (Dynamo) or wide-row (Cassandra) |
Neither store should be used outside its pattern. S3/Iceberg is the source of truth from which both can be rebuilt if needed.
6. Retention and Tiering
| Tier | Contents | Retention |
|---|---|---|
| Kafka | Raw stream | 3–7 days (replay buffer) |
| DynamoDB | Per-user event timeline | TTL 30–90 days |
| ClickHouse hot (NVMe) | Full event rows | 0–30 days |
| ClickHouse warm (S3-backed volume, TTL MOVE) | Full event rows | 30–90 days |
| S3 Iceberg (Standard) | Raw + clean Parquet | 0–90 days |
| S3 Iceberg (Infrequent Access → Glacier) | Same, lifecycle rule | 90 days → 1 year → archive |
| Rollup tables | Daily aggregates by event_type/source | Indefinite (tiny footprint) |
Long-term trend queries hit the rollup tables directly. Queries that need individual events older than 90 days run via Trino or Athena over Iceberg — pay-per-scan, no warehouse cost. Compaction jobs merge small Parquet files during off-peak hours to keep Athena scan costs low.
Common Mistakes to Avoid
- Putting Postgres or MySQL in the ingestion hot path. Row-oriented databases at 50k writes/s require serious sharding effort; Kafka + a stream consumer is simpler and more durable.
- One store for both access patterns. A columnar warehouse can do point lookups, but at 5–10x the latency and cost of a purpose-built key-value store. Run the right tool for each job.
- Skipping deduplication. At-least-once delivery plus client retries means duplicates are guaranteed. If you don't deduplicate, your DAU numbers will be wrong.
- Treating the payload as opaque forever. Storing everything as raw JSON is a starting point, not an end state. Promote hot fields to typed columns as query patterns emerge, or you'll pay in query latency and developer friction.