I’ve been looking at how Microsoft Fabric Eventhouse could fit into an event-sourcing architecture. Not just as somewhere to send events for a dashboard, but somewhere we can use those events to reconstruct an entity’s state and then ask questions across its history.
Parcel tracking makes a useful example. “Delivered” answers the question on the tracking page, but it doesn’t tell us why the first delivery failed, or which address the driver had at the time.
Let’s start with the architecture, then use Kusto Query Language (KQL) to rebuild a parcel, rewind its journey, and explore where deliveries are failing.
To follow along, download the sample bundle. It contains the CSV dataset, KQL setup script, and numbered example queries. We’ll look at the important logic, then use the script’s stored functions for the rest of the walkthrough.
Table of contents
Background
Keeping facts instead of rows
In a typical application, we’d keep a parcel row and update it as things happen. Change the status when it reaches a hub, replace the address when the customer requests a change, and mark it delivered at the end.
Nothing wrong with that. But unless we separately preserve the changes, the row tells us where we ended up, not how we got there.
Event sourcing reverses that relationship. The authoritative record is an ordered history of accepted business events, such as PackageAccepted, DeliveryAttemptFailed, and DeliveryAddressChanged. The current parcel state is calculated by applying those events in order.
That calculated state is a projection – a view of the history shaped for a particular purpose. A tracking page needs the current status and address. A delivery report might need the number of failed attempts. Both can come from the same events.
This is more than keeping an audit trail next to the parcel row. The history must contain enough information to rebuild the state without depending on that row. It also isn’t the same as publishing messages: an event-driven application doesn’t necessarily retain a complete, authoritative history that it can replay.
Why try Eventhouse?
Eventhouse is designed to store and analyze event data, with KQL for querying that data. That makes it an interesting place to explore the read side of an event-sourced system.
It also gives us a practical way to surface the results. Fabric’s Real-Time Dashboards can query Eventhouse to show delivery progress and failed attempts in near real time, as events become available and the visuals refresh. KQL’s geospatial functions let us calculate distances, check delivery-zone boundaries, and group attempts into geographic cells. We can put those results on a map instead of stopping at a table of parcel IDs.
The usual starting point is analytics: send the committed events to Eventhouse, count failures, and build a dashboard. Useful, but I wanted to take the example a little further. Could we also reconstruct the parcel itself in KQL, rather than calculating its state in application code and sending Eventhouse another finished row?
That would let us work with the same history at different levels. Rebuild 1 parcel to answer a support question, inspect its state before an address change, then look across parcels for geographic patterns. A new question could mean a new query, rather than a change to the event producer.
The important distinction is between selecting the latest event and applying the events. If every event contains a complete replacement state, selecting the latest version is straightforward. But a failed-attempt event and an address-change event each tell us only part of the story.
For those, we need a reducer: logic that takes the previous state and applies the next event. KQL’s scan operator lets us express that ordered, stateful calculation inside the query. The reducer still exists; it just isn’t application code.
Where it fits
For this sample, the architecture is:
Delivery application
-> Transactional event store (authoritative committed events)
-> Eventhouse / KQL database (retained event history)
-> KQL replay, tracking views, and geographic analysisThe application validates commands, and its event store durably commits the accepted changes with concurrency control. Those committed events are then ingested into Eventhouse. We aren’t implementing the command side or its transport here.
So this isn’t an attempt to replace a transactional event store just because both systems store events. It’s an experiment in using Eventhouse for reconstruction and analysis within an event-sourcing architecture. Its query results reflect the events available there, which may lag behind the source.
With that boundary in place, let’s see what we can rebuild without a complete-state event.
The tracking row hides the journey
Here’s the journey of parcel P1:
| Version | Event | What changed |
|---|---|---|
| 1 | PackageAccepted | Initial address, destination coordinates, and delivery promise |
| 2 | ArrivedAtHub | Status and physical location |
| 3 | OutForDelivery | Status and physical location |
| 4 | DeliveryAttemptFailed | Status, physical location, and failed-attempt count |
| 5 | DeliveryAddressChanged | Address and destination coordinates |
| 6 | OutForDelivery | Status and physical location |
| 7 | Delivered | Status and physical location |
The final tracking row says “Delivered to 20 New Street.” That’s correct, but it doesn’t explain the failed attempt at the previous address.
More importantly, the final event doesn’t contain that address, the delivery promise, or the failed-attempt count. To recover those, we have to apply the earlier events.
This is the reconstruction we want to demonstrate: the final tracking row depends on several business facts, not just the last event.
A small event history
Open a KQL queryset connected to a KQL database in your Eventhouse. This inline datatable illustrates the event contract without creating a table. The later stored-function examples use the persisted ParcelEvents table, loaded through the setup steps below.
I’ve added 2 more parcels so the geographic queries have something to group. Everything here is synthetic, including the addresses and delivery outcomes. The coordinates are around London.
let Events = datatable(
EventId:string, ParcelId:string, Version:long,
OccurredAt:datetime, EventType:string, SchemaVersion:int, Payload:dynamic
)
[
"p1-7", "P1", 7, datetime(2026-11-16T11:30:00Z), "Delivered", 1, dynamic({"lon":-0.10,"lat":51.52}),
"p1-1", "P1", 1, datetime(2026-11-16T08:00:00Z), "PackageAccepted", 1, dynamic({"address":"10 Old Street","promise":"2026-11-16T18:00:00Z","destLon":-0.12,"destLat":51.51}),
"p1-3", "P1", 3, datetime(2026-11-16T10:00:00Z), "OutForDelivery", 1, dynamic({"lon":-0.13,"lat":51.505}),
"p1-2", "P1", 2, datetime(2026-11-16T09:00:00Z), "ArrivedAtHub", 1, dynamic({"lon":-0.20,"lat":51.50}),
"p1-4", "P1", 4, datetime(2026-11-16T10:30:00Z), "DeliveryAttemptFailed", 1, dynamic({"lon":-0.121,"lat":51.509}),
"p1-5", "P1", 5, datetime(2026-11-16T10:40:00Z), "DeliveryAddressChanged", 1, dynamic({"address":"20 New Street","destLon":-0.10,"destLat":51.52}),
"p1-4", "P1", 4, datetime(2026-11-16T10:30:00Z), "DeliveryAttemptFailed", 1, dynamic({"lon":-0.121,"lat":51.509}),
"p1-6", "P1", 6, datetime(2026-11-16T11:00:00Z), "OutForDelivery", 1, dynamic({"lon":-0.11,"lat":51.515}),
"p2-1", "P2", 1, datetime(2026-11-16T08:05:00Z), "PackageAccepted", 1, dynamic({"address":"30 East Street","promise":"2026-11-16T18:00:00Z","destLon":-0.08,"destLat":51.52}),
"p2-2", "P2", 2, datetime(2026-11-16T09:05:00Z), "ArrivedAtHub", 1, dynamic({"lon":-0.20,"lat":51.50}),
"p2-3", "P2", 3, datetime(2026-11-16T10:05:00Z), "OutForDelivery", 1, dynamic({"lon":-0.09,"lat":51.515}),
"p2-4", "P2", 4, datetime(2026-11-16T11:05:00Z), "Delivered", 1, dynamic({"lon":-0.08,"lat":51.52}),
"p3-1", "P3", 1, datetime(2026-11-16T08:10:00Z), "PackageAccepted", 1, dynamic({"address":"40 West Street","promise":"2026-11-16T18:00:00Z","destLon":-0.121,"destLat":51.509}),
"p3-2", "P3", 2, datetime(2026-11-16T08:50:00Z), "ArrivedAtHub", 1, dynamic({"lon":-0.20,"lat":51.50}),
"p3-3", "P3", 3, datetime(2026-11-16T09:20:00Z), "OutForDelivery", 1, dynamic({"lon":-0.13,"lat":51.505}),
"p3-4", "P3", 4, datetime(2026-11-16T09:50:00Z), "DeliveryAttemptFailed", 1, dynamic({"lon":-0.1208,"lat":51.5092}),
"p3-5", "P3", 5, datetime(2026-11-16T10:30:00Z), "OutForDelivery", 1, dynamic({"lon":-0.125,"lat":51.507}),
"p3-6", "P3", 6, datetime(2026-11-16T11:00:00Z), "DeliveryAttemptFailed", 1, dynamic({"lon":-0.1209,"lat":51.5091})
];Version is assigned by the source, independently for each parcel. SchemaVersion identifies the payload contract, not the parcel’s position in its history.
I’ve deliberately shuffled P1‘s rows and repeated its failed-attempt event. Arrival order isn’t business order, and a retry shouldn’t become another failed delivery.
A larger playground
The inline example is small enough to follow by hand. For something more interesting to put on a map, I’ve also included a sample data ZIP (about 2.7 MB). The file contains 25,000 parcels and 111,798 event rows across October 18 to November 16, 2026. That includes 109,542 unique events and 2,256 exact retry copies. The original P1, P2, and P3 histories are included unchanged.
There are first-attempt successes, repeat failures, address changes, late deliveries, and parcels still in transit. I’ve deliberately given different synthetic location profiles different failure probabilities, so there are geographic patterns to find. These are invented patterns, not evidence about real London deliveries.
Rows are shuffled, and each parcel has a complete version prefix starting at 1. An unfinished parcel isn’t a broken history: its next event simply isn’t in this snapshot. There are no deliberately corrupt schemas, conflicting identities, or missing middle versions in this file.
To load it, extract the ZIP and first run the setup commands described below. Then use your KQL database’s Get data > Local file flow. Select the existing ParcelEvents table, select CSV, and configure the first row as column headings rather than an event. Check that the inferred mapping agrees with these types:
| Columns | KQL type |
|---|---|
| EventId, ParcelId, EventType | string |
| Payload | dynamic |
| Version | long |
| OccurredAt | datetime |
| SchemaVersion | int |
Use dynamic for Payload so its properties are directly queryable. CSV itself has no column types: the file contains standard quoted JSON objects, and the Eventhouse table schema and ingestion mapping give that field its dynamic type. Don’t put KQL’s dynamic(...) wrapper into the CSV.
After loading the file once, this should return 111,798 rows and 25,000 parcels, with PayloadKinds containing only "dictionary" (not "string"):
ParcelEvents
| summarize RawRows = count(), Parcels = count_distinct(ParcelId),
PayloadKinds = make_set(gettype(Payload))The stored functions let us select P1 for the step-by-step examples and use the full dataset for geographic exploration. There’s no need to keep replacing a local Events definition. This is a fixed historical dataset, so use its explicit dates rather than a moving filter such as ago(1d).
The ZIP also contains a Python generator and a summary with exact counts, KQL column types, ingestion settings, and a CSV checksum. The generator uses only the Python standard library (Python 3.10 or later), with a fixed seed so you can reproduce the CSV. For a bigger file, run this from the extracted directory:
py .\generate-parcel-events.py --parcels 100000 --output-dir .\larger-sampleThis is a static snapshot, not a live feed. You can use it in a Real-Time Dashboard, but new events won’t appear unless you ingest more data.
Reproducing the setup
The ZIP also includes setup commands, an optional tiny seed, and numbered example queries.
Run the setup commands individually, in order, in a dedicated demo database. They create the ParcelEvents table, its ParcelEventsCsv ingestion mapping, a 365-day retention policy, validation and replay functions, geographic helpers, and the ParcelIngestionCounts materialized view. If you’ve already created a string-typed payload column, use a fresh demo database; the script doesn’t silently migrate its type.
Then either upload the CSV (skip its header row and use the provided mapping if ingesting through an SDK), or run the tiny seed once. Don’t do both. The seed contains the same 3 parcels and retry as the inline example.
Before replay, use the validation function from the script:
ParcelValidationIssues()
| sort by ParcelId asc, Version ascThis must return no rows. Resolve every issue before continuing. It’s an explicit validation step, not an atomic gate against concurrent writes. The function checks the sample’s payload contract, identity/version conflicts, missing prefixes, event-time ordering, and lifecycle transitions.
The example-query script follows the same sequence as the rest of this post and includes fixed expected-state checks for the original parcels. We’ll also query the ingestion-count MV near the end; it doesn’t replace ordered replay.
Rebuilding the parcel in KQL
KQL’s scan walks ordered rows while carrying state forward. That’s what we need: apply a delta, keep the fields it didn’t change, then move to the next event.
Here’s the core reducer, written as a local function so we can inspect it alongside the inline Events dataset:
let Replay = (Input:(
EventId:string, ParcelId:string, Version:long,
OccurredAt:datetime, EventType:string, SchemaVersion:int, Payload:dynamic
))
{
Input
| summarize take_any(*) by EventId
| partition hint.strategy=native by ParcelId
(
sort by Version asc
| scan declare (
Status:string = "",
Address:string = "",
Promise:datetime = datetime(null),
Lon:real = real(null),
Lat:real = real(null),
DestLon:real = real(null),
DestLat:real = real(null),
FailedAttempts:long = 0
) with
(
step s: true =>
Status = case(
EventType == "PackageAccepted", "Accepted",
EventType == "ArrivedAtHub", "AtHub",
EventType == "OutForDelivery", "OutForDelivery",
EventType == "DeliveryAttemptFailed", "AttemptFailed",
EventType == "Delivered", "Delivered",
s.Status),
Address = iff(
EventType in ("PackageAccepted", "DeliveryAddressChanged"),
tostring(Payload.address), s.Address),
Promise = iff(
EventType == "PackageAccepted",
todatetime(Payload.promise), s.Promise),
Lon = iff(
EventType in ("ArrivedAtHub", "OutForDelivery", "DeliveryAttemptFailed", "Delivered"),
todouble(Payload.lon), s.Lon),
Lat = iff(
EventType in ("ArrivedAtHub", "OutForDelivery", "DeliveryAttemptFailed", "Delivered"),
todouble(Payload.lat), s.Lat),
DestLon = iff(
EventType in ("PackageAccepted", "DeliveryAddressChanged"),
todouble(Payload.destLon), s.DestLon),
DestLat = iff(
EventType in ("PackageAccepted", "DeliveryAddressChanged"),
todouble(Payload.destLat), s.DestLat),
FailedAttempts = s.FailedAttempts
+ iff(EventType == "DeliveryAttemptFailed", 1, 0);
)
)
};
let History = Replay(Events);
History
| where ParcelId == "P1"
| project Version, EventType, Status, Address, FailedAttempts,
Lon, Lat, DestLon, DestLat, Promise
| sort by Version ascYou can run the inline dataset and this block together to inspect the mechanism. The setup script persists this reducer as ParcelReplayValidated(Input). Its ParcelHistory wrapper selects a parcel’s retained event prefix and invokes that reducer.
The fixture has known event types, valid payloads, and complete histories. This reducer assumes those conditions; it isn’t a production validation layer. In particular, the s.Status fallback means an address change preserves status, not that unknown event types are safe to ignore. We’ll return to that distinction.
There are 3 important details here:
summarize take_any(*) by EventIdkeeps 1 copy of each validated event identity before it can increment the counter.partitiongives each parcel its own replay state.sort by Version ascestablishes source order inside each parcel’s partition.
The partition documentation describes native and shuffle strategies. The inline illustration uses native; the stored reducer uses shuffle for the larger dataset. Neither choice is a substitute for measuring replay cost.
Now that we’ve seen the logic, let’s use the stored function. From this point on, the examples query the loaded ParcelEvents table – they don’t depend on the local Events, Replay, or History definitions:
ParcelHistory("P1")
| project Version, EventType, Status, Address, FailedAttempts,
Lon, Lat, DestLon, DestLat, Promise
| sort by Version ascFor P1, this returns all 7 versions, with the columns in the same order as the query. The physical coordinates start as null because acceptance records a destination, not an observed parcel location.
| Version | EventType | Status | Address | FailedAttempts | Lon | Lat | DestLon | DestLat | Promise |
|---|---|---|---|---|---|---|---|---|---|
| 1 | PackageAccepted | Accepted | 10 Old Street | 0 | null | null | -0.12 | 51.51 | 2026-11-16T18:00:00Z |
| 2 | ArrivedAtHub | AtHub | 10 Old Street | 0 | -0.20 | 51.50 | -0.12 | 51.51 | 2026-11-16T18:00:00Z |
| 3 | OutForDelivery | OutForDelivery | 10 Old Street | 0 | -0.13 | 51.505 | -0.12 | 51.51 | 2026-11-16T18:00:00Z |
| 4 | DeliveryAttemptFailed | AttemptFailed | 10 Old Street | 1 | -0.121 | 51.509 | -0.12 | 51.51 | 2026-11-16T18:00:00Z |
| 5 | DeliveryAddressChanged | AttemptFailed | 20 New Street | 1 | -0.121 | 51.509 | -0.10 | 51.52 | 2026-11-16T18:00:00Z |
| 6 | OutForDelivery | OutForDelivery | 20 New Street | 1 | -0.11 | 51.515 | -0.10 | 51.52 | 2026-11-16T18:00:00Z |
| 7 | Delivered | Delivered | 20 New Street | 1 | -0.10 | 51.52 | -0.10 | 51.52 | 2026-11-16T18:00:00Z |
At version 5, the destination changes, but the parcel doesn’t teleport. The failed-attempt count stays at 1, and the original delivery promise survives.
Nothing too fancy. But a latest-row query over the raw events wouldn’t recover any of that.
Rewinding and rebuilding
The script’s ParcelCurrent function selects the highest version after replay. Its optional second argument limits the replay to a source version, while retaining the whole prefix needed to reconstruct it.
To see the state just after the address changed:
ParcelCurrent("P1", 5)
| project ParcelId, Version, Status, Address, Promise,
FailedAttempts, Lon, Lat, DestLon, DestLatThis returns AttemptFailed, the new address, 1 failed attempt, and the physical location recorded by version 4. The destination is now (-0.10, 51.52), while the promise is still 2026-11-16 18:00:00 UTC.
Inside ParcelCurrent, ParcelHistory("P1", 5) replays versions 1 through 5, then arg_max(Version, *) selects the last reconstructed row. Filtering raw events down to version 5 alone would leave us with an address change and none of the state it depends on.
Omit that version argument for the latest available state. Here’s the current tracking view for the original 3 parcels:
union ParcelCurrent("P1"), ParcelCurrent("P2"), ParcelCurrent("P3")
| project ParcelId, Version, Status, Address, FailedAttempts,
Promise, Lon, Lat, DestLon, DestLat
| sort by ParcelId ascWe should get P1 delivered with 1 failure, P2 delivered with no failures, and P3 still in AttemptFailed with 2 failures.
Each function call starts replay from empty state and reconstructs the same view from retained events; it doesn’t read a previous tracking row.
That’s our rebuild. This sample doesn’t create a physical tracking table, so there’s no table to delete. In a system that persists the projection, rebuilding means reading the retained history into a new projection, validating it at a known source watermark, and publishing that replacement.
Also, version-time and wall-clock time aren’t interchangeable. This example answers “what was the state through source version 5?” Answering “what did our tracking page know at 10:40?” additionally needs historical arrival or visibility information. OccurredAt alone can’t answer that when events arrive late.
Putting the journey on a map
There are 2 different locations in the reconstructed state:
LonandLat: the last observed physical location.DestLonandDestLat: the destination at that version.
They’re both geographic points, but they don’t mean the same thing. Mixing them would make an address change look suspiciously like a very fast delivery.
Distance and delivery zones
The script’s ParcelDeliveryZone() function returns a small, fixed GeoJSON polygon. ParcelGeoHistory starts with replayed history, adds geo_distance_2points for the current destination, and calls geo_point_in_polygon separately for the physical location and destination.
Let’s use that helper to inspect versions 5 and 7:
ParcelGeoHistory("P1")
| where Version in (5, 7)
| project Version, Status, Address, DistanceToDestinationM,
PhysicalLocationInsideZone, DestinationInsideZone
| sort by Version ascThe expected result:
| Version | Status | DistanceToDestinationM | PhysicalLocationInsideZone | DestinationInsideZone |
|---|---|---|---|---|
| 5 | AttemptFailed | 1899.4 | false | true |
| 7 | Delivered | 0 | true | true |
geo_distance_2points returns the shortest geographic distance in meters. This isn’t road distance, a routing calculation, or an ETA.
geo_point_in_polygon checks membership in a GeoJSON polygon. Coordinates are longitude first, latitude second (the sort of detail I’d otherwise get wrong while wondering why the map looks strange).
Our polygon has a closed, counterclockwise outer ring. Both functions can return null for invalid input; null doesn’t mean “outside the zone.”
The zone is fixed in this sample. If delivery boundaries change, retain their versions or effective periods too. Otherwise, a historical parcel joined to today’s zones answers a different question.
Showing the observations
For a map, return only events that actually observed a physical location:
ParcelHistory("P1")
| where EventType in (
"ArrivedAtHub", "OutForDelivery", "DeliveryAttemptFailed", "Delivered")
| project ParcelId, Version, OccurredAt, EventType,
Longitude = Lon, Latitude = Lat
| sort by Version ascUse this query in a Fabric Real-Time Dashboard tile, select the Map visual, and set Define location by to Latitude and longitude. Map the 2 numeric columns explicitly. Microsoft’s dashboard customization guide covers those settings.

Power BI is another option. Load the same query through the KQL Database connector, then use the Azure Maps visual. Assign Longitude and Latitude to the corresponding fields.
This gives us observation markers, not a GPS trace. An address-change event isn’t another physical observation, and lines between these markers wouldn’t prove which roads the driver took.
Zooming out with H3
Where are deliveries failing across parcels? H3 divides the map into cells, so we can group nearby attempts rather than plot every event. The script uses geo_point_to_h3cell at resolution 8 to assign each attempt’s physical location to a cell.
In our event contract, a completed attempt is either a Delivered or DeliveryAttemptFailed event. ParcelFailureHotspots replays the histories and groups those outcomes by cell:
ParcelFailureHotspots(datetime(2026-10-18), datetime(2026-11-17), 20)
| sort by Failures desc, Attempts desc
| take 100The last argument requires at least 20 completed attempts per cell; use 1 for the tiny seed. Each row includes Attempts, Failures, FailureRatePct, and the cell center’s Longitude and Latitude – not an individual delivery address.
Plot those centers in a Real-Time Dashboard or Power BI map. Size the markers by Failures and include Attempts and FailureRatePct in the tooltips. More failures can simply mean more deliveries, so compare rates and sample sizes before calling an area a problem.
The helper filters by outcome time after replay. Earlier acceptance and address-change events still contribute to each attempt’s reconstructed state.
A few boundaries
Replay assumes valid events and a complete history in source-version order. Run ParcelValidationIssues() before using the sample’s replay functions; deduplication doesn’t resolve conflicting events. Retain the history needed for your replay window, and don’t filter away earlier events that establish the state you’re rebuilding.
These queries reconstruct state; they don’t accept delivery commands or enforce optimistic concurrency. The command side still owns validation, concurrency, and durable commitment. Replaying a delivery event mustn’t trigger another delivery or resend a notification.
Saving the ordered scan query as a function doesn’t make it an incremental materialized view. It replays the selected history when queried, so measure the cost before applying it to larger workloads.
This is a synthetic reconstruction sample, not a deployed parcel system or a production-scale benchmark. The downloadable scripts retain the detailed validation checks and a separate ingestion-monitoring MV example.
Summary
I’ve used 1 event history for a tracking view, historical reconstruction, delivery-zone checks, and geographic analysis. The address-change event didn’t need to repeat the parcel’s complete state, and adding the H3 query didn’t require changing the producer.
That’s the useful part for me: keeping the business facts lets us ask another question later, without hoping the latest tracking row remembered the answer.