Build a Clickstream and Orders Warehouse for an Online Shop
System DesignModel answerLast updated
Design a warehouse for a retail platform's clickstream and orders that serves two fixed queries: monthly unique Asian viewers of an item, and the current top three orders by value.
You are building the analytics layer for an online retail platform. The product exposes these user-facing actions: searching for items, viewing an item page, logging in, adding to cart, viewing the cart, checking out, and viewing a past order.
The warehouse has to answer two pre-defined questions:
- During the current calendar month, how many distinct users located in Asia viewed a particular item, A?
- At this moment, which three orders have the largest total amount?
Describe your design. A strong answer covers:
- Event schema: fields, data types, primary and foreign keys.
- Sessions: how a session or tracking ID is created and renewed.
- Identity stitching: linking anonymous activity to a user after login.
- Objects and quantities: how to represent cart contents and order totals.
- Storage format: semi-structured JSON versus normalized columns, and the trade-offs.
- Physical layout: partitioning and indexing or clustering.
- Correctness: deduplication, idempotent writes, and late or out-of-order events.
- Dimensional model: users, items, and geography, including slowly changing dimensions.
- Pipeline: batch versus streaming, scaling, and cost.
- Optional: example SQL for the two questions.
State your assumptions (time zone, currency, what counts as a valid order, how anonymous traffic is counted) and sketch rough volumes.
Hints
Hint 1
Pin down ambiguous terms first: 'in Asia' (location at event time vs. profile country), which time zone defines the month, whether anonymous visitors count as users, and whether cancelled or refunded orders can appear in the top three.
Hint 2
Treat clickstream and money differently: behavioral events arrive from client SDKs and need dedup and sessionization, while order totals should come from the order database (via change data capture) as the source of truth, stored as decimals.
Hint 3
Keep identity stitching in a separate mapping table instead of rewriting facts, and partition the event table by event date with clustering on event type and item so Query 1 touches only about one month of one event type.
Hint 4
Real-time top-K is awkward in a columnar warehouse; consider a small serving store or streaming aggregate for Query 2, and use the warehouse for the batch/historical view.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
- "Asia": default to the location at event time (IP geolocation mapped to country), and also keep the profile's home country for comparison.
- "Current month": fix one reporting time zone (UTC or the business zone) and use it everywhere.
- "Unique users": count the stitched identity; fall back to the anonymous ID if the viewer never logged in.
- "Top three orders right now": assume all-time, valid orders only (exclude cancelled/refunded), normalized to one currency such as USD. Freshness: seconds to a minute for Q2, minutes for Q1.
Rough scale: 50M daily users x ~40 events = ~2B events/day, ~1 KB each, so ~2 TB raw and ~250 GB compressed columnar per day, with peaks near 100K events/s. Orders are only ~2M/day. Events are huge and append-only; orders and dimensions are small.
2. Event schema
One wide fact_events table, with typed columns for hot fields and a JSON column for the long tail:
| Column | Type | Notes |
|---|---|---|
| event_id | UUIDv7 string | PK, generated at the source, used for dedup |
| event_type | enum | search, item_view, login, add_to_cart, view_cart, checkout, view_order |
| event_ts / received_ts | timestamp | client time (skew-corrected) / collector time |
| event_date | date | derived from event_ts in the reporting zone |
| anonymous_id | string | device or cookie ID, always present |
| user_id | bigint null | set when logged in |
| session_id | string | see below |
| item_id, order_id, cart_id | nullable | FKs to dim_item / fact_orders |
| quantity | int null | for cart changes |
| geo_country_code | char(2) | resolved from IP at ingest |
| properties | JSON | long tail |
Cart and orders. Cart actions emit one event per line change (item, quantity, unit price); a derived fact_cart_snapshot reconstructs the cart for "view cart". Orders are not built from clickstream: they come from the order database via CDC into fact_orders (order_id PK, user_id, status, currency, total_amount DECIMAL(18,2), total_amount_usd, timestamps, source version) and fact_order_lines (order_id, line_no, item_id, quantity, unit_price, discount). Never use floats for money.
JSON vs columns. JSON gives free schema evolution but scans slowly, prunes poorly and lets types drift silently. Typed columns compress, prune and are validated. Use a hybrid: promote anything used in filters or joins to a column, keep the rest in properties, and archive the raw payload in the lake for replay.
3. Sessions
anonymous_idis a UUID stored in a first-party cookie or app storage and persists across visits.session_idis created by the SDK when there is no session or after 30 minutes of inactivity (optionally also on midnight or campaign change).- A streaming job re-applies the 30-minute rule per
anonymous_idto repair misbehaving clients, and writesfact_sessions(start, end, event count, landing page, converted flag).
4. Identity stitching
Maintain identity_map(anonymous_id, user_id, first_linked_ts, last_seen_ts), updated on every login event. Resolve the canonical user as COALESCE(user_id, mapped_user_id, anonymous_id). For shared devices, choose the user most recently logged in before the event. Keep stitching out of the facts so they stay immutable and can be re-stitched when rules change; a nightly job can materialize canonical_user_id for speed.
5. Dimensions
dim_user: SCD Type 2 (surrogate key, home country, tier, valid_from/valid_to, is_current).dim_item: Type 2 for price and category history; Type 1 for typo fixes in titles.dim_geo: static lookup, country to continent, so "Asia" is a join.dim_date: standard.
Facts hold natural keys and event time; a point-in-time join on event_ts BETWEEN valid_from AND valid_to gives "as it was", is_current gives "as it is now".
6. Partitioning and clustering
fact_events: partition byevent_date(event time, daily to avoid tiny files), cluster by(event_type, item_id). Q1 then reads about 30 partitions and only the item_view blocks for item A.fact_orders: small; partition by created date, cluster by status. In a serving store, index(status, total_amount_usd DESC).- Columnar warehouses rely on pruning and clustering instead of B-tree indexes.
7. Dedup, idempotency, late data
- SDKs retry with the same
event_id; the stream keeps keyed state with a ~24h TTL to drop repeats. - Warehouse loads use
MERGE ... ON event_idas a backstop, orROW_NUMBER() ... = 1on a periodic compaction. - Order CDC upserts are keyed on
order_id, applying a change only ifsource_versionis newer, so replays and reordering are harmless. - Late events: use watermarks (e.g., 1-2 hours) in streaming; anything later lands in the right partition via a batch reconciliation that rewrites the last few days. Partition by event time so late data goes to the correct month.
8. Pipeline
SDK to collector to Kafka. A stream processor (Flink/Spark) validates, geo-enriches, dedups and sessionizes, writing to the lake and warehouse in micro-batches (1-5 min). Orders flow separately via CDC. A nightly batch rebuilds stitching, sessions and aggregates and fixes late data (a lambda/kappa hybrid). For Q2, a streaming job or the serving store keeps a top-K by amount, updated on each order change, giving sub-minute freshness cheaply. Cost levers: columnar Parquet with compression, daily partitions, pre-aggregated daily item-viewer tables, and TTL on raw hot storage.
9. Example queries
-- Q1: distinct Asian viewers of item A this month
SELECT COUNT(DISTINCT COALESCE(m.user_id, e.user_id, e.anonymous_id))
FROM fact_events e
JOIN dim_geo g ON g.country_code = e.geo_country_code
LEFT JOIN identity_map m ON m.anonymous_id = e.anonymous_id
WHERE e.event_type = 'item_view'
AND e.item_id = :A
AND g.region = 'Asia'
AND e.event_date >= DATE_TRUNC('month', CURRENT_DATE);
-- Q2: top three valid orders
SELECT order_id, total_amount_usd
FROM fact_orders
WHERE status NOT IN ('cancelled', 'refunded')
ORDER BY total_amount_usd DESC
LIMIT 3;
For very large scale, Q1 can use HyperLogLog sketches per (day, item, region) and merge them for approximate counts.
Common mistakes
- Using floats for money or deriving order totals from clickstream.
- Partitioning by arrival time, which misfiles late events into the wrong month.
- Overwriting facts during identity stitching, losing the ability to re-stitch.
- Ignoring ties and invalid statuses in the top-three query.
- Putting everything in one JSON blob and paying for it in scan cost.