Event Streaming LabPython · Bytewax

Chapter 8 · Real Bytewax

Route and quarantine events

Give invalid records a visible destination.

Prerequisite Choose a streaming architecture.

What you’ll learn

Decode records, branch a real dataflow and account for every accepted or quarantined input.

The question

One malformed payload should not silently disappear or keep crashing an otherwise useful stream. The shop needs normal orders to proceed and failed records to remain inspectable without treating every failure as retryable.

A decoder turns bytes into a record or an explicit error envelope. Bytewax map executes that decoder; branch splits its outputs into true and false streams. Both branches have sinks. Our authored validation rejects malformed JSON, non-integer amounts and negative amounts. Quarantine preserves the original bytes as base64, which is an encoding, not encryption.

Account for both validation outcomes
Raw payloadDecode and validatePreserve identity and failure provenance.
  1. Valid branchAccepted eventContinue normal processing.
  2. Invalid branchQuarantine envelopeRetain original failed bytes and a reason.

Conceptual diagram. The branches are mutually exclusive. A bounded local quarantine list does not establish durable retention or repair.

Predict the result

Four byte payloads: a valid £12 order, invalid JSON, a negative amount, and a valid £5 order. The decoder retains arrival position and original failed bytes. An optional extra string adds one more payload.

How many inputs reach each branch? Should an invalid amount be retried unchanged until it succeeds?

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_records": 4,
  "accepted": [
    {
      "id": "a",
      "amount": 12
    },
    {
      "id": "d",
      "amount": 5
    }
  ],
  "quarantine": [
    {
      "arrival": 1,
      "ok": false,
      "reason": "invalid JSON",
      "original_b64": "bm90LWpzb24="
    },
    {
      "arrival": 2,
      "ok": false,
      "reason": "invalid amount",
      "original_b64": "eyJpZCI6ImMiLCJhbW91bnQiOi0xfQ=="
    }
  ],
  "accounted_for": 4
}

Read the result

Find a and d in accepted and compare the reason fields in quarantine. Check input_records and accounted_for to see whether every input reached a branch. The result presents each branch in arrival order for this fixture.

Change the experiment

Replace route_events() with route_events(extra='{"id":"z","amount":true}') in the editor. Select Run again. Find z’s payload in quarantine by its position and reason. Then replace "amount":true with "amount":0 and select Run again. Find z in accepted. Why does a Python boolean from JSON true fail an integer-only amount check while zero passes?

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 route_events(extra=None):
    raw=[b'{"id":"a","amount":12}',b'not-json',b'{"id":"c","amount":-1}',b'{"id":"d","amount":5}']
    if extra is not None: raw.append(extra.encode('utf-8'))
    flow=Dataflow('route_and_quarantine')
    source=op.input('bytes',flow,TestingSource(list(enumerate(raw)),batch_size=1))
    def decode(row):
        arrival,payload=row
        try:
            event=json.loads(payload)
            if not isinstance(event,dict) or not isinstance(event.get('id'),str): raise ValueError('invalid envelope')
            if type(event.get('amount')) is not int or event['amount']<0: raise ValueError('invalid amount')
            return {'arrival':arrival,'ok':True,'event':event}
        except (ValueError,UnicodeDecodeError) as error:
            return {'arrival':arrival,'ok':False,'reason':'invalid JSON' if isinstance(error,json.JSONDecodeError) else str(error),
                    'original_b64':base64.b64encode(payload).decode()}
    decoded=op.map('decode',source,decode)
    routed=op.branch('valid',decoded,lambda row:row['ok'])
    good,bad=[],[]
    op.output('accepted',routed.trues,TestingSink(good));op.output('quarantine',routed.falses,TestingSink(bad))
    run_main(flow,epoch_interval=timedelta(0))
    good.sort(key=lambda r:r['arrival']);bad.sort(key=lambda r:r['arrival'])
    return {'input_records':len(raw),'accepted':[r['event'] for r in good],
            'quarantine':bad,'accounted_for':len(good)+len(bad)}

Separate rejection from irrelevance

Malformed data, a permanent business rejection and a valid record that a filter does not need are different outcomes. Do not send all three through an unbounded retry loop. Count each population separately so a small success count does not hide a large rejected input stream.

Operate the quarantine

Set an owner, a size/age budget and an alert on growth. A repair should record what changed and why, then replay into a controlled destination with stable identities. Quarantine payloads can contain personal data; base64 does not make them safe to expose in logs.

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 decode/validation per input, then one branch predicate. Parsing work grows with payload bytes and nested structure, not merely record count.
StateThis fixture collects both branches in O(n) output memory. Production buffers and quarantine retention need independent limits.
MovementThe branches are real local engine paths. Shipping a DLQ to another system adds serialization, transport and acknowledgement work.
ProgressA permanent decoding failure can be routed immediately. Retrying the identical invalid payload does not advance it toward success.
RecoveryQuarantine and replay need source identity and sink contracts. This local list does not establish durable retention or exactly-once repair.

Think it through

Does calling a destination a dead-letter queue guarantee that someone can safely replay its contents later?

Show hints
  1. Hint 1

    Retaining bytes is only one part of a replay contract.

  2. Hint 2

    You also need schema/version context, original identity and an approved repair.

  3. Hint 3

    A replay can reproduce a bad side effect unless its sink is idempotent.

Show explanation

No. Define ownership, access, retention, error classification, repair/version metadata and a replay procedure. Preserve source identity and distinguish original from repaired data. An unattended error stream is another backlog. Here the quarantine sink is a bounded local list, not a durable production queue.

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.

  • Separate good and invalid records

    The decoding callback labels the result; branch splits records according to a predicate.

  • 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 map/branch operators and two sinks; authored decoding/validation policy. The quarantine is local and volatile. No durable DLQ, schema registry or automatic retry service is implemented.

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