Event Streaming LabPython · Bytewax

Chapter 9 · Real Bytewax

Expand and re-key a stream

One cart becomes several independently identified lines.

Prerequisite Route and quarantine events.

What you’ll learn

Use flat_map and a new key to explain fan-out, output amplification and aggregate ownership.

The question

The shop sells carts containing several products. Sales wants totals per product code (SKU), so grouping by the original cart ID will not answer the question. The stream first needs a new record shape and a new ownership key.

map returns one output per input; flat_map returns an iterable containing zero, one or many outputs. Each line gets a composite line ID derived from copy, cart and line position. key_on then assigns SKU ownership, and fold_final emits the final sum when input ends (EOF). A line identity and an aggregation key serve different purposes.

One cart becomes several independently identified lines
  1. Cart inputOne orderContains multiple product lines.
  2. flat_mapZero, one or many linesOutput cardinality can exceed input cardinality.
  3. key_onSKU ownershipLine identity and aggregation key differ.
  4. fold_finalTotals at EOFA live stream needs an emission policy.

Conceptual diagram. The actual Bytewax graph implements these transformations. Fan-out and retained key count are separate budgets.

Predict the result

Two carts contain four lines: two wheels at £5 and one light at £3; one wheel at £5 and one bell at £4. copies repeats the fixture with distinct composite IDs.

How many output lines and SKU totals will two carts produce? If copies doubles, which quantities double and which stay fixed?

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.

{
  "input_carts": 2,
  "output_lines": 4,
  "lines": [
    {
      "line_id": "0/a/0",
      "sku": "wheel",
      "units": 2,
      "pounds": 10
    },
    {
      "line_id": "0/a/1",
      "sku": "light",
      "units": 1,
      "pounds": 3
    },
    {
      "line_id": "0/b/0",
      "sku": "wheel",
      "units": 1,
      "pounds": 5
    },
    {
      "line_id": "0/b/1",
      "sku": "bell",
      "units": 1,
      "pounds": 4
    }
  ],
  "totals": {
    "bell": 4,
    "light": 3,
    "wheel": 15
  }
}

Read the result

Compare input_carts and output_lines and count the product codes in totals. The two carts contain four line items across wheel, light and bell.

Change the experiment

Replace copies=1 with copies=2 in the editor. Select Run again. Compare input_carts, output_lines, and totals with the first run. Do the number of line items and the number of product codes grow together?

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.

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 expand_orders(copies=1):
    if not 1<=copies<=10: raise ValueError('copies must be 1..10')
    carts=[('a',[('wheel',2,5),('light',1,3)]),('b',[('wheel',1,5),('bell',1,4)])]
    source_rows=[(f'{c}/{order}',items) for c in range(copies) for order,items in carts]
    flow=Dataflow('expand_carts')
    source=op.input('carts',flow,TestingSource(source_rows))
    def lines(cart):
        order,items=cart
        return [{'line_id':f'{order}/{i}','sku':sku,'units':units,'pounds':units*price}
                for i,(sku,units,price) in enumerate(items)]
    expanded=op.flat_map('lines',source,lines)
    rows=[];op.output('line_evidence',expanded,TestingSink(rows))
    keyed=op.key_on('sku',expanded,lambda row:row['sku'])
    totals=op.fold_final('sum',keyed,lambda:0,lambda total,row:total+row['pounds'])
    result=collect(flow,totals)
    return {'input_carts':len(source_rows),'output_lines':len(rows),
            'lines':sorted(rows,key=lambda r:r['line_id']),'totals':dict(sorted(result))}

Budget for output, not only input

With n carts and z lines, downstream work and network volume depend on z. A single pathological cart can create a burst even at a low cart arrival rate. Bound list size, output bytes and per-record work before claiming that a map-like stage is cheap.

Know when a total exists

fold_final emits at EOF. A never-ending stream needs incremental state or an explicit window/emission policy. A correct bounded answer cannot be used to infer when a live dashboard would become visible.

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
WorkExpansion is O(n+z) for n carts and z constant-sized lines; aggregate work also depends on z and the selected key implementation.
StateThree scalar SKU accumulators here, plus all collected line/output evidence. More copies increase volume without increasing the SKU set.
MovementFan-out increases records and bytes sent downstream. Re-keying in a distributed engine can also introduce a network exchange.
ProgressEach expanded line can flow immediately; fold_final waits for EOF. Infinite input does not provide a final aggregate automatically.
RecoveryStable composite IDs are necessary for replay policy. Changing line ordering or key construction can change identity and ownership across runs.

Think it through

If an order is replayed, is deduplicating only by SKU a correct way to prevent repeated line contributions?

Show hints
  1. Hint 1

    Different legitimate lines can share one SKU.

  2. Hint 2

    An aggregation key decides shared state, not event identity.

  3. Hint 3

    A replay needs the same stable line identity as the original delivery.

Show explanation

No. Deduplicating by SKU discards legitimate purchases. Use a stable line identity for first-delivery policy, then aggregate the accepted lines by SKU. In production, line-position identities also require stable ordering or a source-assigned line ID when carts can be edited.

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.

  • Change cardinality, then choose a key

    Read how flat_map emits several items per input and how key_on defines the accumulator’s ownership.

  • 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 flat_map, key_on and fold_final over finite carts. The result collects line evidence and final totals; no live emission trigger, broker delivery or external sink is configured.

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