Event Store for Shopper Behavior Analytics and Fixed Reports
System DesignModel answerLast updated
Design a storage and ingestion system for shopper activity events that serves a known set of reports, such as regional unique viewers and top orders, with low latency.
Behavioral Analytics Store for an Online Shop
You are building the analytics backend for a shopping platform. The product emits the following user actions:
- searching for an item
- viewing an item page
- logging in
- adding an item to the cart
- viewing the cart
- completing a purchase
- viewing an order
The reports that the business wants are known in advance. Two examples:
- How many distinct users from Asia viewed item A during the current month?
- Which three orders currently have the highest value?
What to deliver
Design the database and the pipeline around it. Your answer should cover:
- Requirements and scale assumptions: freshness, accuracy, expected event volume, and growth.
- Event model: the fields every event carries and how type-specific data is handled.
- Schema: table layout, partitioning and sort keys, and any pre-aggregated structures.
- Data flow: how events travel from clients to queryable storage, including deduplication and replay.
- The two sample queries: show how your design answers each one efficiently.
- Trade-offs and failure modes: late or duplicate events, mutable order state, exact versus approximate counts, and how you would roll the system out.
State your assumptions explicitly. There is no single correct answer, but your choices should be justified by the access patterns.
Hints
Hint 1
Because the reports are known ahead of time, you can denormalize and pre-aggregate for them instead of building a fully general model. Think about which columns each report filters and groups on.
Hint 2
Distinct-user counts cannot simply be added across days. Consider mergeable sketches (HyperLogLog) or bitmaps for the rollup, and decide where exactness matters.
Hint 3
Orders change state (cancelled, refunded), so a click event is not a reliable source of truth for 'current' order value. Consider a separate current-state table fed from the transactional orders database.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to separate capture from serving and to exploit the fact that the queries are known in advance. That lets us denormalize the hot columns and pre-aggregate the expensive question (distinct users).
1. Requirements and scale
Assumptions to state up front:
- Freshness: a lag of about 1 minute is acceptable for dashboards.
- "At present" for orders: reflects current state, so cancelled and refunded orders are excluded.
- Region semantics: region at the time of the event (geo-IP or profile snapshot), so history is not rewritten when a user moves.
- Accuracy: exact for money-related figures, about 1% error acceptable for engagement counts such as unique viewers.
- Extensibility: new event types will appear.
Rough numbers: 50M daily users at about 40 events each gives about 2B events/day, roughly 23K/s average and about 100K/s at peak. At about 200 bytes per raw event that is about 400 GB/day, and columnar compression (5-10x) brings it to roughly 50-80 GB/day, or about 25 TB/year. Orders are only around 2M/day.
Conclusion: events are append-only and scan-heavy but touch few columns, which suits a columnar OLAP store. Orders are small and mutable, so they get a separate current-state table.
2. Event model
One envelope for all event types:
| Field | Notes |
|---|---|
event_id | client-generated UUID, used for dedup |
event_type | enum of the seven actions |
event_time / ingest_time | business time vs server time |
user_id (nullable), session_id | anonymous users still have a session |
region, country | resolved at ingestion |
item_id, order_id, amount | nullable, set only where relevant |
properties | map for the long tail (search text, cart size) |
Promote the fields that queries filter on to real columns, and keep everything else in properties so new event types need no migration. Validate against a schema registry (Avro or Protobuf) at the edge.
3. Data flow
- Collector API (stateless, batch
POST) authenticates, stampsingest_time, and writes to Kafka partitioned byuser_id. Delivery is at-least-once because clients retry. - Stream processor (Flink): deduplicates on
event_idwith keyed state and a roughly 24h TTL, enriches the region, and sends malformed events to a dead-letter topic. - Raw archive in object storage (Parquet, partitioned by date) is the immutable source of truth for replay and backfill.
- OLAP store (ClickHouse, Druid or Pinot) holds the events fact table plus materialized rollups.
- Orders via CDC from the transactional orders database into an
orders_currenttable. The purchase event is telemetry, not the system of record. - Query service exposes the parameterized reports and caches results.
4. Schema
Fact table events, partitioned by month and sorted by (event_type, item_id, region, event_date, user_id, event_id). The sort key matches the query predicates, so "views of item A in Asia" skips almost all data, and "this month" touches one partition. A replacing engine on event_id provides a second line of defense against duplicates.
Dimensions (dim_user, dim_item, dim_region) are joined only for ad-hoc analysis. The hot reports use the denormalized columns.
Rollup for query 1, item_views_daily, keyed by (item_id, region, day), updated on insert from view_item events. It stores a mergeable distinct sketch (HyperLogLog, or a Roaring bitmap if exactness is needed) plus a raw view count. Distinct users must not be summed across days, since a user active on two days would be counted twice; sketches merge correctly.
Query 1: merge the sketches for item_id = A, region = ASIA, day >= first day of month. That is at most about 31 small rows, so latency is milliseconds regardless of raw volume.
Table for query 2, orders_current: one row per order with total, status, updated_at, and a version, using a versioned replacing engine so the latest state wins.
Query 2: filter out cancelled and refunded statuses, order by total descending, LIMIT 3. With one row per order and a small table this is a cheap partial sort. If it ever became hot, keep a tiny top-K table maintained by the CDC consumer.
5. Trade-offs and failure modes
- Exact vs approximate: sketches give about 1% error with tiny storage. Bitmaps give exact counts at higher memory cost; use them only where needed.
- Late events: the rollup is keyed by event day, so late events update the right bucket. Set a lateness watermark, and run a nightly reconciliation from the raw archive to correct stragglers.
- Duplicates: handled by client
event_id, Flink dedup state, and the replacing engine. Flink state is bounded by the TTL, so duplicates beyond that window rely on the store-level dedup. - Order mutability: reading the current state from CDC avoids stale values that a click-based approach would produce after refunds.
- Region changes: snapshotting region at event time keeps historical numbers stable but means "current region" questions need a join to
dim_user. - Hot keys: a viral item concentrates writes; mitigate by partitioning on
user_id, notitem_id, upstream. - Schema evolution: the registry enforces backward-compatible changes, and new fields land in
propertiesfirst, then get promoted if they prove hot.
6. Validation and rollout
- Run the new pipeline in shadow alongside any existing reporting and compare the two report outputs daily.
- Backfill rollups from the raw archive to verify that replay reproduces live numbers.
- Monitor consumer lag, dedup rate, dead-letter volume, and query p95.
- Roll out by event type, starting with the low-risk ones (view_item), and add purchase flows last.
Common mistakes
- Summing daily distinct counts to get a monthly figure.
- Treating the purchase click event as the authoritative order record.
- Using a normalized OLTP-style schema with many joins for dashboard queries.
- Ignoring dedup despite at-least-once delivery.
- Leaving out a raw archive, which makes backfills and bug fixes impossible.