Event Streaming LabPython · Bytewax

Chapter 21 · Real Bytewax

Join changing streams

Latest values and all combinations answer different questions.

Prerequisite Enrich a stream.

What you’ll learn

Use a Bytewax join to compare how keeping the first, latest or every value changes which pairs the join emits.

The question

Two orders and two customer-region updates share a customer key. Should an order be paired with the latest region, the first region, every observed region or the region valid at its event time? Those are different queries.

Bytewax join gathers keyed values from two actual streams. This finite example uses emit_mode=final, so output waits until both inputs end (EOF). insert_mode=last retains the latest value from each side, while product retains the values needed to emit every combination. Neither policy is automatically an event-time interval or as-of join.

Predict the result

For u1: region West, order o1, region East, order o2. A single source branches into keyed order and customer streams. Each side preserves its fixture order; the final result is sorted for presentation.

Will last emit both orders enriched with East, or only the latest order/customer pair? What should product emit?

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.

{
  "pairs": [
    {
      "order": "o2",
      "region": "East"
    }
  ],
  "insert_mode": "last",
  "emit_mode": "final",
  "boundary": "Real Bytewax join; one key, finite inputs, EOF emission. Product history can grow; this is not an event-time interval or temporal as-of join."
}

Read the result

Find the policy name in insert_mode and the selected order/region pairs in pairs. The starter keeps the last values before the bounded inputs finish.

Change the experiment

Replace insert_mode='last' with insert_mode='product' in the editor. Select Run again. Then replace insert_mode='product' with insert_mode='first' and select Run again. Compare the rows in pairs and their count. Which rule keeps more values for the same key? What would these final-emission policies have to wait for on an endless input?

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 changing_join(insert_mode='last'):
    if insert_mode not in ('first','last','product'):raise ValueError('Choose first, last or product')
    events=[('customer',{'key':'u1','region':'West'}),('order',{'key':'u1','id':'o1'}),
            ('customer',{'key':'u1','region':'East'}),('order',{'key':'u1','id':'o2'})]
    flow=Dataflow('changing_join')
    source=op.input('updates',flow,TestingSource(events,batch_size=1))
    sides=op.branch('side',source,lambda e:e[0]=='order')
    orders=op.map('orders',sides.trues,lambda e:(e[1]['key'],e[1]))
    customers=op.map('customers',sides.falses,lambda e:(e[1]['key'],e[1]))
    joined=op.join('join',orders,customers,insert_mode=insert_mode,emit_mode='final')
    rows=collect(flow,joined)
    pairs=sorted([{'order':order['id'],'region':customer['region']} for _,(order,customer) in rows],key=lambda r:(r['order'],r['region']))
    return {'pairs':pairs,'insert_mode':insert_mode,'emit_mode':'final',
            'boundary':'Real Bytewax join; one key, finite inputs, EOF emission. Product history can grow; this is not an event-time interval or temporal as-of join.'}

The output term belongs in the budget

With n retained values on one side and m on the other, a product can create n×m pairs for one key. A hot key can dominate memory and output even when total input rate looks modest. The interval-join reference counts comparisons separately from this real operator’s observed output.

Choose emission independently of storage

Storage mode decides which values are remembered. Emission mode decides when outputs become visible. A live query needs an incremental/windowed policy, not merely a different insertion setting on an EOF-only experiment.

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
WorkProduct output can require n×m emitted pairs for one key. Latest/first modes retain a different amount of history and answer different questions.
StateLast mode retains one value per side/key; product retains multiple values. The bounded collector also stores every emitted pair.
MovementReal local keyed join logic runs here. A multi-worker/machine join additionally routes bytes and coordinates state ownership.
Progressemit_mode=final waits for source completion. A never-ending stream cannot depend on this fixture’s EOF trigger.
RecoveryConsistent recovery needs both input positions and join state. Replaying with another insertion or history policy can change the answer.

Think it through

If o1 happened before the region changed, does product or last establish that its correct historical region is West?

Show hints
  1. Hint 1

    Neither insertion policy compares an order timestamp with a version-validity interval.

  2. Hint 2

    All combinations and latest values are not an as-of query.

  3. Hint 3

    A temporal contract needs versioned history and an explicit timestamp rule.

Show explanation

No. A historical lookup needs event timestamps, valid-time version history and a rule for corrections and late records. Product enumerates combinations; last chooses current values under its arrival/insertion contract. Use the temporal reference to specify the desired answer before choosing a real time-aware join and retention policy.

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.

  • Join insertion and emission modes

    Read insert_mode and emit_mode separately. This fixture chooses final emission over bounded input.

  • 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 join over one key and finite branched inputs with EOF emission. No event-time join horizon, history expiry, distributed shuffle or arbitrary cross-input ordering is established.

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