Event Streaming LabPython · Bytewax

Chapter 28 · Real Bytewax

Forget state deliberately

A smaller state store changes the answers you can defend.

Prerequisite Replay without double counting.

What you’ll learn

Observe actual Bytewax state deletion and explain why forgetting an identity reopens its duplicate window.

The question

Remembering every event ID forever eventually becomes a storage problem. Forgetting IDs solves that resource problem by weakening which future duplicates can still be recognized. Both consequences belong in the design.

Bytewax stateful_map receives None when a key has no saved state. Returning None as the next state deletes that key’s operator state. This fixture sends an explicit expire control record, then delivers the identity again. The control is authored input, not an automatic processing-time or event-time timer.

Expiry changes what a future duplicate means
  1. First identity aAccept and rememberRetain keyed identity state.
  2. Repeat aDuplicateThe identity is still retained.
  3. Expiry controlDelete stateThe authored control returns None.
  4. Later aAccepted againThe previous history is no longer present.

Conceptual diagram. The control record is authored; returning None really deletes Bytewax state. No automatic TTL timer is implied.

Predict the result

Event a, duplicate a, expire a, event a again. The trace records whether the engine supplied previous state to the callback.

After expiry, will the final a be recognized as a duplicate? What change in accepted count should disabling expiry cause?

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.

{
  "accepted": 2,
  "duplicates": 1,
  "trace": [
    {
      "id": "a",
      "action": "accepted",
      "had_state": false
    },
    {
      "id": "a",
      "action": "duplicate",
      "had_state": true
    },
    {
      "id": "a",
      "action": "expired"
    },
    {
      "id": "a",
      "action": "accepted",
      "had_state": false
    }
  ],
  "boundary": "Expiry is an authored control record; returning None really deletes Bytewax keyed state. No automatic clock timer is implemented."
}

Read the result

Compare accepted and duplicates. In the last trace row, check had_state. Returning None on the explicit expiry action removes the earlier Bytewax state.

Change the experiment

Replace expire=True with expire=False in the editor. Select Run again. Compare accepted and duplicates and had_state in the last trace row. Which replay still sees the state? What delay would your own deduplication policy have to tolerate?

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 forget_state(expire=True):
    actions=[('event','a'),('event','a'),('expire','a'),('event','a')]
    flow=Dataflow('forget_identity')
    source=op.input('controls',flow,TestingSource(actions,batch_size=1))
    keyed=op.key_on('identity',source,lambda row:row[1])
    def remember(state,row):
        kind,identity=row
        if kind=='expire':
            return (None if expire else state),{'id':identity,'action':'expired' if expire else 'expiry ignored'}
        action='accepted' if state is None else 'duplicate'
        return True,{'id':identity,'action':action,'had_state':state is not None}
    rows=[row for _,row in collect(flow,op.stateful_map('remember',keyed,remember))]
    return {'accepted':sum(r['action']=='accepted' for r in rows),
            'duplicates':sum(r['action']=='duplicate' for r in rows),'trace':rows,
            'boundary':'Expiry is an authored control record; returning None really deletes Bytewax keyed state. No automatic clock timer is implemented.'}

Logical expiry and physical reclamation

An application can decide that state is no longer usable before a backend has reclaimed every physical byte. Conversely, retaining a small tombstone can be necessary even after a visible value is gone. Ask separately about query semantics, checkpoint contents and storage reclamation.

Choose the expiry clock

Processing-time TTL bounds inactivity as observed by a running system. Event-time cleanup follows input progress and can stall behind idle data. Restart, late arrivals and clock skew change the cases each policy must handle. The timer/retention reading develops those distinctions.

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
WorkA real keyed callback processes every control and delivery. Deletion removes the logical state entry; backend reclamation cost is implementation-specific.
StateOne boolean for the active identity in this fixture. Bounded retention needs cleanup of all eligible keys, not only an age check when a key happens to return.
MovementNo network/state-backend I/O is measured. A distributed backend or checkpoint store can retain additional physical history.
ProgressThe expire control is explicit input. It is not evidence that a wall-clock or watermark timer fired automatically.
RecoveryForgetting identity metadata changes recovery behavior: a sufficiently old replay may be accepted again unless another boundary prevents duplicates.

Think it through

Is a one-hour deduplication horizon sufficient if an operator can restore a checkpoint and replay two hours of input?

Show hints
  1. Hint 1

    A forgotten ID cannot distinguish a replay from a new event with the same ID.

  2. Hint 2

    Recovery and backfill may extend beyond ordinary delivery delay.

  3. Hint 3

    Sink idempotency can provide a different protection boundary.

Show explanation

Not by itself. Match identity retention to possible redelivery, recovery and backfill horizons, or rely on an independently idempotent sink/authority. State deletion is a business-contract decision. A production TTL also needs an actual clock, cleanup scheduler and late-return policy, none of which this control-record fixture silently supplies.

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.

  • State retention policy

    The helper uses logical timestamps and returns None to discard state. It does not configure a background TTL service.

  • 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

Actual keyed-state deletion, driven by explicit fixture controls. No wall-clock TTL scheduler, retained-byte measurement or production state-backend compaction is implemented.

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