Chapter 18 · Real Bytewax
Build a materialized view
Updates replace facts; deletes must leave enough history.
Prerequisite Where does a key live?.
Maintain a versioned projection and explain why a tombstone may still need metadata after its visible value is removed.
The question
The catalog emits corrections as well as new products. Adding every observed price into a total is meaningless. The query view should contain the newest accepted value for each product, including deletion.
A materialized view is a stored answer maintained from changes. Our real Bytewax stateful_map holds a version and optional value per product. The authored version guard ignores older or equal versions. A delete removes the visible price but retains its version as a tombstone, preventing a late older update from resurrecting the product.
- Entity updatesVersions 1, 2, 3The source defines version authority.
- Version guardReject stale updatesArrival order is not the authority.
- Current viewA is deletedRemove the visible value.
- Retained tombstoneRemember version 3Reject a later stale version 2.
Conceptual diagram. The local stateful map and upsert policy are executed. Tombstone retention still needs a replay/deletion contract.
Predict the result
A v1=10; B v1=8; A v2=12; stale A v1=9; A delete v3; stale A v2=11. Versions are assumed to increase within one entity’s history.
Should A remain absent after the final version-2 update? What information is needed to reject that update after deleting A’s visible value?
Run the experiment
The editor contains the published example. Select Run with the code unchanged.
Python prepares in the background while you read. First use can download about 84 MiB. Your code runs only when you select Run; each run starts with clean experiment state.
A saved draft is open. Select Restore code to see the published example. Recover draft brings back your draft.
Ctrl+Enter or ⌘+Enter runs the code.
Edits are saved in this browser when storage is available.
Technical error details
Your result
Console output
Troubleshooting
If Python stops responding, restart the environment and try again. Your code and last completed result are kept.
View the published result
The course build ran the published code to generate this output.
{
"view": {
"B": 8
},
"ignored": 2,
"tombstones": [
"A"
],
"trace": [
{
"arrival": 0,
"key": "A",
"version": 1,
"value": 10,
"action": "upsert"
},
{
"arrival": 1,
"key": "B",
"version": 1,
"value": 8,
"action": "upsert"
},
{
"arrival": 2,
"key": "A",
"version": 2,
"value": 12,
"action": "upsert"
},
{
"arrival": 3,
"key": "A",
"action": "ignored",
"version": 1
},
{
"arrival": 4,
"key": "A",
"version": 3,
"value": null,
"action": "delete"
},
{
"arrival": 5,
"key": "A",
"action": "ignored",
"version": 2
}
]
}Read the result
Compare view, ignored, and tombstones. Find the row for A with action set to delete in trace, then inspect the later attempt to update A to version 2.
Change the experiment
Replace reject_stale=True with reject_stale=False in the editor. Select Run again. Compare view, ignored, and tombstones and the last trace row. How can an old update bring back a deleted item?
Runtime, source code and downloads
Runtime and reset details explain what stays ready and what is isolated on each run. Download Python packages the published helpers with the code in your editor.
Browse the sources for Bytewax windows and authored models, Kafka log and group exercises, live Kafka input, checkpoint recovery and processing patterns.
Inspect the operator implementation
The editor calls this exact function. See how it connects the operators and applies the policy. Shared imports and collection helpers are in the complete patterns module and course module. Download Python includes both.
def materialized_view(reject_stale=True):
changes=[('A',1,10),('B',1,8),('A',2,12),('A',1,9),('A',3,None),('A',2,11)]
flow=Dataflow('materialized_view')
source=op.input('changes',flow,TestingSource(list(enumerate(changes)),batch_size=1))
keyed=op.key_on('entity',source,lambda row:row[1][0])
def apply(previous,row):
arrival,(key,version,value)=row
if reject_stale and previous and version<=previous['version']:
return previous,{'arrival':arrival,'key':key,'action':'ignored','version':version}
state={'version':version,'value':value}
return state,{'arrival':arrival,'key':key,'version':version,'value':value,
'action':'delete' if value is None else 'upsert'}
updated=op.stateful_map('version_guard',keyed,apply)
rows=sorted([row for _,row in collect(flow,updated)],key=lambda r:r['arrival'])
view={};deleted=set()
for row in rows:
if row['action']=='delete':view.pop(row['key'],None);deleted.add(row['key'])
elif row['action']=='upsert':view[row['key']]=row['value'];deleted.discard(row['key'])
return {'view':dict(sorted(view.items())),'ignored':sum(r['action']=='ignored' for r in rows),
'tombstones':sorted(deleted),'trace':rows}Separate event history from current state
An append-only history can contain several legitimate versions for one product. A current view intentionally compresses that history into the latest accepted fact. Audit and current-query consumers need different outputs; compaction does not preserve the same questions as a complete event log.
Version authority is part of the contract
A counter is useful only if its ordering scope is defined. Two writers cannot independently issue version 7 and expect the consumer to invent the correct winner. Include entity identity, version authority, delete semantics and conflict policy in the event contract.
Work, state and recovery costs
Where used, n counts input events, k counts retained distinct keys, r counts overlapping windows per event and z counts output matches. Bounds assume the stated algorithm. Collecting, sorting and displaying results adds work.
| Question | Mechanism and boundary |
|---|---|
| Work | One version comparison and state update per change, plus key routing. The callback is constant-sized; engine lookup and serialization have separate costs. |
| State | O(k) value/version entries for k entities, including retained tombstones. Deleting a visible row does not necessarily delete all consistency metadata. |
| Movement | Projection updates are local here. Writing an external view adds acknowledgement, retries and atomicity concerns. |
| Progress | A new accepted version can replace the current view immediately. Arrival order alone is not used as the version authority. |
| Recovery | A rebuild must preserve delete/version semantics. Replaying into a new namespace is safer than overwriting a live view without a cutover plan. |
Think it through
Can the tombstone metadata be forgotten immediately after the query view removes a product?
Show hints
Hint 1
A delayed message can arrive after the deletion.
Hint 2
You need a boundary beyond which older versions cannot be replayed.
Hint 3
Retention, source identity and rebuild strategy interact.
Show explanation
Only with a justified replay/lateness boundary or another authority that rejects stale versions. Otherwise an older event can recreate a deleted value. Define tombstone retention alongside log retention, entity-version authority and rebuild rules. A local version guard does not solve concurrent writers issuing conflicting versions.
ReferencesFunction documentation and helper source
References open in a new tab; course helpers are documented separately from library APIs. Bytewax links target the official 0.21.1 definitions and API docstrings.
Store the latest accepted revision
The callback implements revision checks and tombstones; these are authored policies over native keyed state.
Course helper implementation
These are functions written for this course, not additional library APIs. Inspect their parameters, operator calls and authored policies. The source shown is generated from the same Python files packaged with Run and Download Python.
Experiment scope
Real Bytewax keyed state with an authored version policy and a local upsert view. No external database, source transaction order, global version allocator or atomic projection cutover is established.
Primary reference →