Event Streaming LabPython · Bytewax

Chapter 16 · Real Bytewax

Keep state by key

Two shops. Two running totals.

Prerequisite Correct a late result.

What you’ll learn

Explain how keyed state differs from a single running total.

The question

North and South need separate sales totals. Adding every order into one number gives the company total, but answers neither shop’s question.

A key tells Bytewax which records share a running total. key_on uses the shop name as the key. stateful_map passes the previous total for that shop to add, or None if this is the first record. The function returns the new total to keep and the record to emit.

The key selects a separate retained history
Incoming ordersKey by shopRoute an event to its own accumulator.
  1. NorthNorth running totalA South record does not update this state.
  2. SouthSouth running totalA North record does not update this state.

Conceptual diagram. These are parallel keyed histories in one worker. Distributed ownership and rescaling require additional mechanisms.

Predict the result

The editor imports the five bicycle-shop orders. Each order supplies an amount and a shop. The key function selects which running total to update.

What will North’s total be after its third order? Will South’s orders change it?

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.

Ctrl+Enter or ⌘+Enter runs the code.

Edits are saved in this browser when storage is available.

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.

[
  {
    "arrival": "a",
    "shop": "North",
    "total": 12
  },
  {
    "arrival": "b",
    "shop": "South",
    "total": 8
  },
  {
    "arrival": "c",
    "shop": "North",
    "total": 17
  },
  {
    "arrival": "d",
    "shop": "North",
    "total": 24
  },
  {
    "arrival": "e",
    "shop": "South",
    "total": 17
  }
]

Read the result

Read shop and total for each arrival. North reaches £24 while South reaches £17. The callback keeps separate accumulators for the two shop keys.

Change the experiment

Replace lambda order: order['shop'] with lambda order: 'all' in the editor. Select Run again. Read the total values after each arrival. Why does the last total combine both shops even though the output still prints each order’s shop?

Return to the editor
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.

Change cardinality, not only volume

If twice as many orders still go to two shops, the operator does twice as many updates and keeps two totals. If each order uses a different shop, the operator needs one total per order. A fair performance investigation varies event count, key count and key frequency independently.

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.

QuestionMechanism and boundary
WorkOne keyed state callback per order. Per-event routing/storage costs depend on Bytewax’s implementation and key/hash behavior; the accumulator update itself is O(1).
StateO(k) scalar totals for k shops, plus O(n) collected output and an O(n log n) presentation sort. No expiry is configured.
MovementOne local worker; key routing is real engine work but no cross-machine network shuffle is measured.
Progressstateful_map emits after each update. The final sort is presentation only and does not establish cross-key delivery order.
RecoveryThis lesson has no recovery config. The recovery chapter coordinates source positions and operator state in SQLite.

Think it through

What happens to memory if a never-ending stream introduces a new key on every event?

Show hints
  1. Hint 1

    Think about how many groups remain reachable.

  2. Hint 2

    A group needs somewhere to keep its accumulator.

  3. Hint 3

    This example does not expire idle keys.

Show explanation

State can grow with the number of distinct keys. A real long-running design needs key expiry, bounded cardinality, or a state backend with an explicit retention policy. A window is one way to bound the time span of an aggregate.

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.

  • Key ownership and callback state

    Read the keyed stream contract and the callback’s (updated_state, emitted_value) result.

  • Graph construction and input interfaces

    Read these signatures for the graph and finite test input constructed in the editor. The course collection helper attaches an output and starts execution.

  • 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

One Bytewax worker holds the totals in memory. Each run starts a new Python process with empty totals. The recovery chapter shows how to restore state from a checkpoint within a run.

Primary reference →
Reading marks track what you’ve read independently of your runs.