Event Streams
When every system calls every other
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.
| Message | Kind | Addressed to | Can it be refused? |
|---|---|---|---|
| reserve_stock | Command | The inventory system | Yes |
| send_receipt | Command | The email system | Yes |
| order_placed | Event | Whoever subscribes | No, it already happened |
| payment_captured | Event | Whoever subscribes | No, it already happened |
What goes inside one event
- 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?
- 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
- 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.
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?
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.
| position | event_id | event_type | order_id | amount | occurred_at |
|---|---|---|---|---|---|
| 1041 | a17e | payment_captured | 88142 | 49.00 | 18:42:09 |
| 1042 | b902 | order_packed | 88142 | NULL | 18:47:30 |
| 1043 | c3d5 | payment_corrected | 88142 | 45.00 | 18:50:12 |
Designing the log table
- 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.
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.
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?
State is a fold over events
| seq | event_type | amount | occurred_at | balance after |
|---|---|---|---|---|
| 1 | wallet_credited | 50.00 | 1 Nov 09:15 | 50.00 |
| 2 | wallet_debited | 12.50 | 2 Nov 18:42 | 37.50 |
| 3 | wallet_debited | 20.00 | 5 Nov 12:03 | 17.50 |
| 4 | wallet_refunded | 12.50 | 6 Nov 08:30 | 30.00 |
Any past moment is one filter away
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_id | seq | event_type | amount |
|---|---|---|---|
| 5071 | 1 | wallet_credited | 50.00 |
| 5071 | 2 | wallet_debited | 12.50 |
| 5071 | 3 | wallet_debited | 20.00 |
| 5071 | 4 | wallet_refunded | 12.50 |
| wallet_id | balance | last_seq |
|---|---|---|
| 5071 | 30.00 | 4 |
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.
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.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?
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.
| event_name | Fires when | Required properties |
|---|---|---|
| product_viewed | A product page finishes loading | product_id, price |
| search_submitted | The customer submits a query | query, result_count |
| cart_item_added | An item enters the cart | product_id, quantity, price |
| order_completed | Payment succeeds | order_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.
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_at | event_name | anonymous_id | user_id | session_id |
|---|---|---|---|---|
| 18:36:02 | product_viewed | anon-7c2 | NULL | s-901 |
| 18:38:40 | cart_item_added | anon-7c2 | NULL | s-901 |
| 18:40:12 | account_signed_in | anon-7c2 | 5071 | s-901 |
| 18:42:10 | order_completed | anon-7c2 | 5071 | s-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
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.
| play_idVARCHARPK | user_idBIGINTFK | video_idBIGINTFK | started_atTIMESTAMP |
|---|
Product wants pauses, seeks and shares tracked, with more actions to come. How do you change the model?
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_id | event_name | occurred_at | received_at | lag |
|---|---|---|---|---|
| e1 | product_viewed | 3 Nov 23:41:10 | 3 Nov 23:41:11 | 1 s |
| e2 | cart_item_added | 3 Nov 23:52:30 | 4 Nov 00:06:02 | 13 min 32 s |
| e3 | checkout_started | 3 Nov 23:58:44 | 4 Nov 00:06:02 | 7 min 18 s |
| e4 | order_completed | 4 Nov 00:01:15 | 4 Nov 00:01:16 | 1 s |
| e5 | product_viewed | 3 Nov 21:15:00 | 5 Nov 08:20:00 | 35 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.
- ▸
occurred_atsays when it happened. Reports and state rebuilds read it. - ▸
received_atsays 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
| Strategy | How it works | What it costs |
|---|---|---|
| Wait | Publish a day only after a fixed delay, such as 3 hours past midnight | Slower reports, and anything later than the delay is missed |
| Reprocess a trailing window | Every night, recompute the last 3 event dates from the log | About 3x the compute, and published numbers move for 3 days |
| Rebuild what changed | Find the event dates that new arrivals touched and rebuild only those | More logic to maintain, with no fixed cutoff |
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.
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?
> 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.
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.payment_corrected events and the duplicate deliveries collapse on event_id, so no row is edited and every reader sees the same history.seq order, even though wallet_balances has moved on since.anonymous_id across consistently named events, so customers who browsed logged out during the storm are still in it.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.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
- 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
- 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
- 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
- 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
- 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