IntermediateData Modeling · 27 min · 12 challenges

Event Streams

A LinkedIn member views a profile. That one action has to reach the who-viewed-your-profile page and search ranking. Recommendations need it too, as do security monitoring and the data warehouse. LinkedIn's engineers wrote about connecting every system to every other and watching the pipelines multiply. Their published fix was a central log: record the view once as an event, and let each system read it.

Event-Driven Architecture

Daily Life
Interviews
FreshCart is a grocery delivery app. When a customer checks out, 4 things must happen: stock is reserved, a receipt is emailed, the fraud model scores the order, and the sales warehouse records the purchase. The first version of checkout does all of this itself, calling each system directly, one after another.

When every system calls every other

With direct calls, the checkout code itself names each downstream system it notifies, the email provider included. To add a loyalty-points service, someone edits checkout and redeploys it, then has to decide what happens when the new call times out. A slow email provider now slows every purchase. The checkout team ends up responsible for the uptime of 4 systems it did not build, with a 5th on the way.
An event-driven design reverses who knows about whom. Checkout announces what happened by writing an event to a shared log, and each system that cares subscribes to that log. Checkout no longer holds a list of listeners.
producer
Checkout
event log
Order events
reserves stock
Inventory
sends email
Receipts
scores order
Fraud scoring
hourly load
Sales warehouse

Checkout writes one order_placed event. Each consumer reads the log at its own pace, and a 5th consumer can be added without touching any existing box.

An event is a fact in the past tense

An event is a record that something happened, at a specific time, to a specific thing. Its name is in the past tense because it describes a fact that is already true: order_placed, payment_captured, item_restocked. A command is a different kind of message. reserve_stock asks one system to do something, and that system can refuse. order_placed asks nothing of anyone, and nothing can refuse it, because the order already exists.

MessageKindAddressed toCan it be refused?
reserve_stockCommandThe inventory systemYes
send_receiptCommandThe email systemYes
order_placedEventWhoever subscribesNo, it already happened
payment_capturedEventWhoever subscribesNo, it already happened

What goes inside one event

Every event carries the same outer fields, called the envelope, plus a payload specific to its type.
{
"event_id": "7f3a9c1e-52b4-4d0a-9e61-0c8b2a41d7f5",
"event_type": "order_placed",
"occurred_at": "2026-11-03T18:42:07Z",
"order_id": 88142,
"payload": {
"customer_id": 5071,
"total_amount": "94.00",
"currency": "USD",
"item_count": 9
}
}
What each envelope field answers
  • event_id is a unique key the producer generates, so a consumer that receives the same event twice can tell.
  • event_type is the past-tense name. It decides which fields the payload holds.
  • occurred_at is the moment the fact became true, stored in UTC.
  • order_id is the key of the thing the event is about. It lets a consumer collect every event for one order.

How much should the payload carry?

Thin event
  • Carries keys only: order_id and customer_id
  • A consumer calls checkout back for the details
  • Small messages, but every consumer now depends on checkout's API
  • Details fetched later may have changed since the event
Fat event
  • Carries the values as of that moment: total, currency, item count
  • A consumer needs nothing else to do its work
  • Larger messages, and the payload becomes a contract
  • Removing a field can break a consumer the producer never heard of

For modeling, lean toward the fat event. An event is a statement about one moment, and the values true at that moment belong in it. Suppose order_placed omits the total and the customer removes an item 10 minutes later. A consumer that looks the total up afterwards reads a number that was never the total at checkout.

Multiple Choice

FreshCart adds a loyalty service that awards 1 point per dollar spent. Checkout already publishes order_placed, whose payload holds customer_id and total_amount. What has to change?

The price of this design is that an event's shape becomes a public interface. Any field you publish may have a reader you have never met. Treat an event definition with the care you give a primary key. Name and type it deliberately, and expect it to outlive the code that first wrote it.

Immutable Append-Only Logs

Daily Life
Interviews

A log is the most restricted table you can design. It allows one kind of write, adding a row at the end. It has no UPDATE and no DELETE, and each new row takes the next position in a sequence that only grows. Those restrictions are what let many readers share one log and trust it.

Why an edit in place misleads readers

FreshCart's fraud model reads the order log within seconds of each write. The sales warehouse loads it once an hour. Suppose a payment_captured event is written at 18:42 with 2 digits swapped: 49.00, where the card was charged 94.00. An engineer edits the row to 94.00 at 18:50. The fraud model scored the order on 49.00 and will never revisit that row. The warehouse loads at 19:00 and sees 94.00. The 2 systems now disagree, and no record anywhere explains why.

The append-only repair writes a second event that states the correction. Every reader, whatever position it has reached, meets the correction as a new row and can react to it.
positionevent_idevent_typeorder_idamountoccurred_at
1041a17epayment_captured8814249.0018:42:09
1042b902order_packed88142NULL18:47:30
1043c3d5payment_corrected8814245.0018:50:12
The row at position 1043 carries the difference, 45.00. Summing the payment rows for order 88142 gives 94.00. The history still shows that 49.00 was recorded first and stood for 8 minutes, so an auditor can read the mistake and its repair in order.
SELECT
order_id,
SUM(amount) AS captured_amount
FROM (
SELECT DISTINCT
event_id,
order_id,
amount
FROM order_events
WHERE event_type IN ('payment_captured', 'payment_corrected')
) AS payments
GROUP BY order_id

Designing the log table

order_events
positionPKBIGINT
event_idVARCHAR
event_typeVARCHAR
order_idBIGINT
amountDECIMAL(12,2)
occurred_atTIMESTAMP
received_atTIMESTAMP
event_dateDATE
What each column is for
  • The grain is one row per event. No row ever summarizes several events.
  • position is assigned by the log on arrival and identifies a row.
  • event_id is generated by the producer before its first write attempt and identifies a fact, so a retry carries the same id.
  • occurred_at is when the fact happened. received_at is when the log accepted the row. The table keeps both.
  • event_date is the date of occurred_at. It splits the stored files by day, so a query for one day reads one day of data.

The same event, written twice

Networks drop acknowledgements. A producer that sends an event and hears nothing back cannot tell whether the write failed or only the reply was lost, so it sends again. Most event systems accept that trade: an event may be delivered more than once, and in exchange none is silently lost. The log can therefore hold 2 rows for one fact. The 2 rows have different positions and the same event_id, and that shared id lets any reader collapse them into one.

SELECT
event_id,
COUNT(*) AS copies,
MIN(received_at) AS first_received_at
FROM order_events
WHERE event_date = DATE '2026-11-03'
GROUP BY event_id
HAVING COUNT(*) > 1
TIP
position can't do this job. The log assigns it on arrival, so each retry gets a fresh one, and 2 copies of one payment would look like 2 payments.

What append-only costs

A log that never deletes grows without limit, and it keeps everything it was given. That collides with a customer's right to have personal data erased. The modeling answer is to keep personal fields out of events. order_placed carries customer_id, while the name and email stay in a customer table whose rows can be edited or removed, along with the street address. Erasing one customer row leaves their events in place, pointing at a key with no person behind it.

Multiple Choice

Order 88142 has an order_shipped event in the log, but a warehouse scanner misfired and the parcel never left the building. How should the log be repaired?

The habit to build is one question, asked of any proposed fix: what would a reader that already passed this row see? If the answer is nothing, the fix belongs in a new event.

Event Sourcing

Daily Life
Interviews
Most tables store current state: a wallet row says the balance is 30.00. Event sourcing stores the events that produced the state and treats the state itself as something you compute. The log is the system of record, and every table of current values is derived from it.

State is a fold over events

FreshCart gives each customer a wallet for credits and refunds. Wallet 5071 has 4 events. Read them top to bottom, apply each one to a running balance, and you have the state after every step. That procedure is called a fold.
seqevent_typeamountoccurred_atbalance after
1wallet_credited50.001 Nov 09:1550.00
2wallet_debited12.502 Nov 18:4237.50
3wallet_debited20.005 Nov 12:0317.50
4wallet_refunded12.506 Nov 08:3030.00
Only the first 4 columns are stored. The last column is computed, and this query computes its final value for every wallet.
SELECT
wallet_id,
SUM(
CASE
WHEN event_type = 'wallet_debited' THEN - amount
ELSE amount
END
) AS balance
FROM wallet_events
GROUP BY wallet_id

Any past moment is one filter away

A customer disputes a charge and asks what their balance was on the evening of 3 November. A table of current state cannot answer, because the 37.50 it held that evening was overwritten on 5 November. The event log answers with one added line.
SELECT
wallet_id,
SUM(
CASE
WHEN event_type = 'wallet_debited' THEN - amount
ELSE amount
END
) AS balance
FROM wallet_events
WHERE occurred_at <= TIMESTAMP '2026-11-03 20:00:00'
GROUP BY wallet_id

Projections: tables you can throw away

Folding the whole log on every page load is too slow, so event-sourced systems keep derived tables called projections. A projection is built by reading the log and is shaped for one kind of question. wallet_balances holds one row per wallet for the app to display. A corrupted projection, or one built with buggy logic, gets dropped and rebuilt from event 1.

wallet_events: the record
wallet_idseqevent_typeamount
50711wallet_credited50.00
50712wallet_debited12.50
50713wallet_debited20.00
50714wallet_refunded12.50
wallet_balances: a projection
wallet_idbalancelast_seq
507130.004
The same log supports projections nobody planned. If finance asks next year for total refunds per wallet per month, the answer exists for every month since launch, because the refund events were kept. A state table would hold that history only from the day someone thought to add a column for it.

Order decides the answer

Credits and debits can be summed in any order. Many events cannot. If an order's log holds address_changed to 12 Elm St and then address_changed to 9 Oak Ave, the delivery address is whichever was applied last. Timestamps from different servers can tie or disagree, so event-sourced tables give each entity its own counter. seq starts at 1 for every wallet and rises by 1 with each event.

Make (wallet_id, seq) the composite primary key and the counter does a second job. Suppose 2 checkouts each read a balance of 30.00, and each tries to append a 25.00 debit as event 5. The key accepts one write and rejects the other. The rejected checkout re-reads the log, finds 5.00, and declines the purchase.

TIP
Long logs get snapshots. A snapshot is a stored copy of the state at a known seq. To load a wallet with 40,000 events, read the snapshot taken at seq 39,900 and fold the 100 events after it. A snapshot is a projection too: it can be deleted and rebuilt.
Multiple Choice

Wallet 6310 has a snapshot after event 4: balance 60.00, last_seq 4. Then 2 events arrive: seq 5 is wallet_debited 8.00 and seq 6 is wallet_credited 15.00. A bug deletes the snapshot. What does a full replay from event 1 return?

Event sourcing earns its cost where history is the product: money, inventory, orders, anything audited. For a table of display preferences, where nobody asks what the theme was last March, a plain state row is the better model.

Clickstream Modeling

Daily Life
Interviews

Clickstream data is the record of what people do inside a product: every page view and search, down to each tap and scroll, captured as an event. Business events like order_placed come from servers FreshCart owns. Behavior events arrive in far greater volume from browsers and phones FreshCart does not control, and each was designed by whoever needed a metric that week. The model has to impose order on that.

Name events as object, then action

A clickstream model starts with a naming convention, because event_name is the column every query filters on. The durable convention is the object, then a past-tense action, in one fixed case: product_viewed, search_submitted, cart_item_added, checkout_started. Without it, one team ships AddToCart for a tap that another team logs as add_to_cart and a third as cart-add, and every funnel query has to know all 3 spellings.

Teams write the convention down in a tracking plan: one entry per event, stating when it fires and which properties it must carry.
event_nameFires whenRequired properties
product_viewedA product page finishes loadingproduct_id, price
search_submittedThe customer submits a queryquery, result_count
cart_item_addedAn item enters the cartproduct_id, quantity, price
order_completedPayment succeedsorder_id, total_amount

One envelope, flexible properties

Every behavior event records who acted and when, plus where it happened. Those become typed columns. What differs per event goes into a properties map, so a new event type or a new property needs no change to the table.

events
event_idPKVARCHAR
event_nameVARCHAR
occurred_atTIMESTAMP
received_atTIMESTAMP
anonymous_idVARCHAR
user_idBIGINT
session_idVARCHAR
deviceSTRUCT
propertiesMAP
event_dateDATE
identity_links
anonymous_idPKVARCHAR
user_idBIGINT
linked_atTIMESTAMP

The grain is one row per action by one visitor at one instant, with duplicates already collapsed on event_id. product_id starts life as a key in properties. Once most queries filter on it, promote it to a typed column of its own. A columnar file can read a typed column alone, while one key of a map costs a read of every key and value in it.

Who is this visitor?

Most browsing happens before login. The app generates an anonymous_id on first launch and stamps it on every event. user_id stays NULL until the visitor signs in. The first time that id signs in, one row is appended to identity_links, pairing the 2 ids. Earlier events stay exactly as written, and a join through identity_links attributes them to the account at query time. Most anonymous ids never sign in and never get a link row, so that join is a LEFT JOIN, and events.anonymous_id carries no foreign key that would reject them.

occurred_atevent_nameanonymous_iduser_idsession_id
18:36:02product_viewedanon-7c2NULLs-901
18:38:40cart_item_addedanon-7c2NULLs-901
18:40:12account_signed_inanon-7c25071s-901
18:42:10order_completedanon-7c25071s-901

session_id groups one visit. A common convention ends a session after 30 minutes without an event, and the client issues a new id on the next action. Storing the id on each event lets a query count visits without reconstructing them from timestamps.

The query this model exists for

A funnel asks how many visitors reached each step. With one events table and consistent names, it is a single scan.
SELECT
COUNT(DISTINCT
CASE
WHEN event_name = 'product_viewed' THEN anonymous_id
END
) AS viewed,
COUNT(DISTINCT
CASE
WHEN event_name = 'cart_item_added' THEN anonymous_id
END
) AS added,
COUNT(DISTINCT
CASE
WHEN event_name = 'order_completed' THEN anonymous_id
END
) AS ordered
FROM events
WHERE event_date = DATE '2026-11-03'
From a plays table to a clickstreamStep 1
>

Loop is a video app. Its only behavior table is `plays`: one row per video started, written for logged-in users. 2 requirements arrive over the next quarter. Pick how the model changes for each.

plays
play_idVARCHARPKuser_idBIGINTFKvideo_idBIGINTFKstarted_atTIMESTAMP

Product wants pauses, seeks and shares tracked, with more actions to come. How do you change the model?

Both strong choices in that story left existing rows untouched. A clickstream model ages well when each new requirement can be met by adding rows or map keys, or by naming a new event, and ages badly when it demands edits to what was already recorded.

Handling Late-Arriving Data

Daily Life
Interviews

Every event has 2 times that matter. occurred_at is when the action happened, stamped by the device or service that saw it. received_at is when your platform accepted the row. On a healthy connection they sit a second apart. On a phone in a subway tunnel they can sit hours or days apart, because the app queues its events and sends them when the signal returns.

One night, 5 events

event_idevent_nameoccurred_atreceived_atlag
e1product_viewed3 Nov 23:41:103 Nov 23:41:111 s
e2cart_item_added3 Nov 23:52:304 Nov 00:06:0213 min 32 s
e3checkout_started3 Nov 23:58:444 Nov 00:06:027 min 18 s
e4order_completed4 Nov 00:01:154 Nov 00:01:161 s
e5product_viewed3 Nov 21:15:005 Nov 08:20:0035 h 5 min

Sorted by received_at, the order is e1, e4, e2, e3, e5. Sorted by occurred_at, it is e5, e1, e2, e3, e4. Arrival order and real-world order differ, and the table records both. Events e2 and e3 came from one phone that lost signal and sent its queue in a single batch at 00:06. Event e5 sat on a tablet in airplane mode for a day and a half.

Which day owns a late event?

A report of activity on 3 November should count the 4 events that happened that day: e1 through e3, plus e5. Filtering on received_at instead counts only e1, the one event that arrived before midnight. So reports group by event time. Loading works the other way round. A nightly job has to ask what is new since its last run, and only arrival time answers that, because a row arriving tomorrow can carry any occurred_at at all.

Keep both clocks on every row
  • ▸occurred_at says when it happened. Reports and state rebuilds read it.
  • ▸received_at says when you learned of it. Loading jobs and lateness checks read it.
  • ▸The gap between the 2 is the event's lateness, measurable row by row.

The count for a day keeps moving

Run the 3 November report at 00:05 on 4 November and it counts 1 event. Run it at 01:00 and it counts 3. Run it on 6 November and it counts 4. Each number was correct for what had arrived. The design decision is how long a day stays open, and it trades freshness against completeness.
StrategyHow it worksWhat it costs
WaitPublish a day only after a fixed delay, such as 3 hours past midnightSlower reports, and anything later than the delay is missed
Reprocess a trailing windowEvery night, recompute the last 3 event dates from the logAbout 3x the compute, and published numbers move for 3 days
Rebuild what changedFind the event dates that new arrivals touched and rebuild only thoseMore logic to maintain, with no fixed cutoff
The last strategy starts by asking which event dates received new rows on a given day.
SELECT
event_date,
COUNT(*) AS new_events
FROM events
WHERE received_at >= TIMESTAMP '2026-11-05 00:00:00'
AND received_at < TIMESTAMP '2026-11-06 00:00:00'
GROUP BY event_date

Rebuilding a date can be repeated safely because of 2 properties the log already has. It is append-only, so a rebuild reads the rows it read before plus the new ones. Every event carries a producer-generated event_id, so a retried delivery counts once. Run the rebuild twice and the result matches running it once.

Late events and derived state

Lateness reaches state too. A projection that applies events in arrival order applies e4 before e2 and e3, although they happened first. For a wallet, a debit applied ahead of the credit that funded it shows a negative balance that never existed. A projection whose result depends on order sorts by occurred_at or a per-entity seq before folding, and accepts that a late event can change a state it already computed.

Multiple Choice

A FreshCart job runs at 02:00 each night and loads the rows whose received_at falls in the previous calendar day. The daily report groups by event_date, the date of occurred_at. Event e5 happened on 3 November and arrived on 5 November at 08:20. What happens to it?

Late data is a property of the world your events describe. A model that stores both clocks can always say what it knew and when it knew it. Decide per report how long a day stays open, write that number beside the report, and let the log absorb whatever arrives afterwards.
PUTTING IT ALL TOGETHER

> A storm cuts mobile coverage across one city from 19:00 on Saturday until 01:00 on Sunday, FreshCart's busiest window. Phones keep queuing taps and orders. When coverage returns, 6 hours of events arrive within minutes, some sent twice, and a payment service that retried during the outage has recorded the wrong amount for 40 orders. On Monday, finance wants Saturday's revenue, growth wants Saturday's funnel, and support wants every affected wallet's balance as of 21:00 on Saturday.

Event-driven architecture: checkout published order_placed once per order, so inventory and fraud scoring caught up from the log at their own pace when the flood arrived, as did the warehouse, with no change to checkout.
Append-only logs: the 40 wrong amounts are repaired with payment_corrected events and the duplicate deliveries collapse on event_id, so no row is edited and every reader sees the same history.
Event sourcing: support answers the 21:00 question by folding each wallet's events up to that time in seq order, even though wallet_balances has moved on since.
Clickstream modeling: growth's funnel counts anonymous_id across consistently named events, so customers who browsed logged out during the storm are still in it.
Late-arriving data: the storm's rows carry occurred_at values from Saturday evening and the first hour of Sunday, and Sunday's received_at. Reports group by the first and the load job selects by the second. Once the late rows land, both Saturday and Sunday are rebuilt.
KEY TAKEAWAYS
An event states a fact in the past tense, with an id from its producer, the time it happened, and the key of the thing it is about.
A log only appends. A mistake is repaired by a new event, because readers that already passed a row never see an edit to it.
State is a fold over events. Tables of current values are projections that can be dropped and rebuilt, including as of any past moment.
A clickstream needs a naming convention and a typed envelope with a properties map beside it. It also needs an identity table that links anonymous and known ids without rewriting rows.
Store both occurred_at and received_at. Report by the first, load by the second, and decide how long each day stays open.

Model what happened as facts that never change, then derive every table you need from them.

Category
Data Modeling
Difficulty
intermediate
Duration
27 minutes
Challenges
12 hands-on challenges

Topics covered: Event-Driven Architecture, Immutable Append-Only Logs, Event Sourcing, Clickstream Modeling, Handling Late-Arriving Data

Lesson Sections

  1. Event-Driven Architecture

    FreshCart is a grocery delivery app. When a customer checks out, 4 things must happen: stock is reserved, a receipt is emailed, the fraud model scores the order, and the sales warehouse records the purchase. The first version of checkout does all of this itself, calling each system directly, one after another. When every system calls every other With direct calls, the checkout code itself names each downstream system it notifies, the email provider included. To add a loyalty-points service, some

  2. Immutable Append-Only Logs

    Why an edit in place misleads readers The append-only repair writes a second event that states the correction. Every reader, whatever position it has reached, meets the correction as a new row and can react to it. The row at position 1043 carries the difference, 45.00. Summing the payment rows for order 88142 gives 94.00. The history still shows that 49.00 was recorded first and stood for 8 minutes, so an auditor can read the mistake and its repair in order. Designing the log table The same even

  3. Event Sourcing

    Most tables store current state: a wallet row says the balance is 30.00. Event sourcing stores the events that produced the state and treats the state itself as something you compute. The log is the system of record, and every table of current values is derived from it. State is a fold over events FreshCart gives each customer a wallet for credits and refunds. Wallet 5071 has 4 events. Read them top to bottom, apply each one to a running balance, and you have the state after every step. That pro

  4. Clickstream Modeling

    Name events as object, then action Teams write the convention down in a tracking plan: one entry per event, stating when it fires and which properties it must carry. One envelope, flexible properties Who is this visitor? The query this model exists for A funnel asks how many visitors reached each step. With one events table and consistent names, it is a single scan. Both strong choices in that story left existing rows untouched. A clickstream model ages well when each new requirement can be met

  5. Handling Late-Arriving Data

    One night, 5 events Which day owns a late event? The count for a day keeps moving Run the 3 November report at 00:05 on 4 November and it counts 1 event. Run it at 01:00 and it counts 3. Run it on 6 November and it counts 4. Each number was correct for what had arrived. The design decision is how long a day stays open, and it trades freshness against completeness. The last strategy starts by asking which event dates received new rows on a given day. Late events and derived state Late data is a p