Event Streaming LabPython · Bytewax

Chapter 40 · Kafka simulator + Bytewax

Run a bounded backfill

Replay a declared range into a versioned destination.

Prerequisite Budget for recovery.

What you’ll learn

Read a real partition range twice, apply a versioned transform and explain idempotent rebuild versus production cutover.

The question

A pricing conversion was wrong last week. Replaying everything directly into the live destination risks mixing old and repaired answers. The team needs a declared source range, transformation version and promotion plan.

The helper produces five records into one simulator partition and captures its next log position. A real Kafka Consumer reads the explicit half-open range [start,stop). Bytewax maps pounds to pence. Two identical replays upsert into a local projection-v2 namespace keyed by original event ID. This isolates rebuilt answers and makes repeated writes visible without duplicating the final rows.

A replay needs a range, identity and destination contract
  1. Source cutDeclared start/stop offsetsFreeze the bounded range.
  2. ReprocessVersioned transformationKeep stable logical record identities.
  3. Shadow viewprojection-v2Use an isolated destination namespace.
  4. ValidationReplayed writes, stable rowsAn upsert view can hide repeated attempts.

Conceptual diagram. The Kafka simulator reads and Bytewax map really execute. Atomic production snapshot/cutover guarantees remain separate.

Predict the result

All five original orders are explicitly placed in partition 0, giving offsets 0..4 and next position 5. The default replay reads offsets 1,2,3 twice and uses stable original IDs.

Why should two replays make six write attempts but only three visible rows? Which record is excluded by stop=4?

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.

{
  "snapshot_next_position": 5,
  "range": [
    1,
    4
  ],
  "offsets": [
    1,
    2,
    3
  ],
  "write_attempts": 6,
  "visible_rows": 3,
  "sink": {
    "projection-v2/b": 800,
    "projection-v2/c": 500,
    "projection-v2/d": 700
  },
  "boundary": "Actual Kafka simulator reads and Bytewax map; one frozen partition range, versioned local upsert view. No production snapshot isolation or atomic promotion."
}

Read the result

Compare the offsets, write_attempts, and visible_rows with the named rows in sink. The requested end offset is excluded. The transform writes to a separate named view twice so you can compare attempted writes with visible rows.

Change the experiment

Replace stop=4 with stop=3 in the editor. Select Run again. Compare offsets, sink, write_attempts, and visible_rows. Which ID drops out of the range? Why is the final row count still half the number of write attempts?

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 bounded_backfill(start=1,stop=4):
    from confluent_kafka import Producer,Consumer,TopicPartition
    producer=Producer({'test.mock.num.brokers':1,'log_level':0})
    brokers=','.join(f'{b.host}:{b.port}' for b in producer.list_topics(timeout=15).brokers.values())
    for order in ORDERS:producer.produce('backfill',value=json.dumps(order),partition=0)
    if producer.flush(15):raise RuntimeError('Backfill fixture delivery timed out')
    def read_range():
        client=Consumer({'bootstrap.servers':brokers,'group.id':'backfill','enable.auto.commit':False,'auto.offset.reset':'error'})
        try:
            low,high=client.get_watermark_offsets(TopicPartition('backfill',0),timeout=15)
            if not low<=start<=stop<=high:raise ValueError('Choose low <= start <= stop <= snapshot next position')
            client.assign([TopicPartition('backfill',0,start)])
            rows=[];deadline=time.monotonic()+30
            while len(rows)<stop-start:
                if time.monotonic()>deadline:raise TimeoutError('Bounded read timed out')
                message=client.poll(0.1)
                if message is None:continue
                if message.error():raise RuntimeError(str(message.error()))
                if message.offset()>=stop:break
                rows.append((message.offset(),json.loads(message.value())))
            return high,rows
        finally:client.close()
    sink={};attempts=0;offsets=[]
    for replay in range(2):
        high,rows=read_range()
        flow=Dataflow(f'projection_v2_{replay}')
        source=op.input('snapshot_range',flow,TestingSource(rows))
        mapped=op.map('pence_v2',source,lambda row:{'offset':row[0],'id':row[1]['id'],'pence':row[1]['amount']*100})
        processed=collect(flow,mapped)
        offsets=[r['offset'] for r in processed]
        for row in processed:attempts+=1;sink['projection-v2/'+row['id']]=row['pence']
    return {'snapshot_next_position':high,'range':[start,stop],'offsets':offsets,
            'write_attempts':attempts,'visible_rows':len(sink),'sink':dict(sorted(sink.items())),
            'boundary':'Actual Kafka simulator reads and Bytewax map; one frozen partition range, versioned local upsert view. No production snapshot isolation or atomic promotion.'}

Capture a reproducible replay manifest

Record topic/partition identity, starting and exclusive ending positions, schema and transform versions, configuration, code revision and destination namespace. An event-time date range alone may omit late arrivals or require scanning a broader retained log.

Distinguish attempts from visible effects

Six write attempts can leave three correct rows under an idempotent upsert contract. That does not mean only three requests happened or that every sink supports the same contract. Capture duplicate receipts, missing IDs and reconciliation evidence beside the final aggregate.

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
WorkRead/transform work scales with replayed records and bytes on every pass. Idempotent final state does not remove repeated processing or writes.
StateThe simulator retains the source and the local view retains one row per namespaced identity. Production retention coverage must be checked before replay.
MovementActual Kafka protocol reads occur over loopback; external snapshot export, network quotas and sink commits are outside this fixture.
ProgressA declared exclusive end offset bounds this reader. A date filter or tailing consumer alone does not necessarily establish a finite replay cut.
RecoveryVersioned namespaces and stable keys support rebuilding. Promotion and coordination with live writers still need an independent production protocol.

Think it through

Does successfully rebuilding this local view prove it is safe to replace a live production projection?

Show hints
  1. Hint 1

    The live writer may have advanced during the replay.

  2. Hint 2

    Offsets, transformation version and destination identity must define the cut.

  3. Hint 3

    Validation and atomic/fenced promotion are separate operations.

Show explanation

No. Establish the source cut and retention coverage, isolate the new view, validate counts/values/deletes, catch up changes after the cut, then promote with an appropriate atomic pointer switch or fencing protocol. Prevent old and new writers from corrupting one namespace. This fixture does not provide production snapshot isolation or a cutover transaction.

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. Confluent’s API guide is a moving reference; this lab uses confluent-kafka 2.6.1 with an in-memory broker simulator.

Experiment scope

Real Kafka simulator reads and real Bytewax mapping; one frozen partition and a local upsert view. No live concurrent writer, broker retention gap, CDC snapshot transaction or atomic promotion is verified.

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