Chapter 33 · Bytewax + service-failure fixture
Retry with a budget
Transient failure is a scheduling decision, not an infinite loop.
Prerequisite Exactly once—at which boundary?.
Classify failures, enforce an attempt budget and account for retry amplification without confusing planned delays with measured latency.
The question
A dependency sometimes fails temporarily. Another request is permanently invalid. Sending both back immediately and forever turns a small error population into a new source of overload.
The real Bytewax map applies an authored retry policy to a deterministic service-failure fixture. Request a succeeds immediately, b needs three attempts, c is permanently rejected and d never succeeds within the budget. Exponential delays with seeded jitter are recorded as planned values; the operator does not sleep and no external service is called.
Predict the result
a has zero transient failures, b has two, c is permanent, d has more transient failures than any allowed budget. The seed makes delay plans repeatable, not cryptographically random.
How many total service attempts do four records generate? Should c receive three attempts merely because the budget allows them?
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.
A saved draft is open. Select Restore code to see the published example. Recover draft brings back your draft.
Ctrl+Enter or ⌘+Enter runs the code.
Edits are saved in this browser when storage is available.
Technical error details
Your result
Console output
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.
{
"success": [
"a",
"b"
],
"quarantine": [
"c",
"d"
],
"total_attempts": 8,
"trace": [
{
"id": "a",
"status": "success",
"attempts": 1,
"planned_delays_ms": []
},
{
"id": "b",
"status": "success",
"attempts": 3,
"planned_delays_ms": [
105,
209
]
},
{
"id": "c",
"status": "quarantine",
"attempts": 1,
"reason": "permanent",
"planned_delays_ms": []
},
{
"id": "d",
"status": "quarantine",
"attempts": 3,
"reason": "budget exhausted",
"planned_delays_ms": [
102,
207
]
}
],
"boundary": "Real Bytewax map; authored service-failure fixture. Delays are planned values, not sleeps or observed latency; no external service is called."
}Read the result
Find the successes for a and b and the quarantine outcomes for c and d. Compare total_attempts with the four source requests. The model’s planned delays are policy values in milliseconds.
Change the experiment
Replace max_attempts=3 with max_attempts=2 in the editor. Select Run again. Compare success, quarantine, and total_attempts. What happens to b when it cannot make a third attempt? Why might a larger retry budget leave less capacity for new work?
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 retry_events(max_attempts=3):
if not 1<=max_attempts<=5: raise ValueError('max_attempts must be 1..5')
events=[{'id':'a','failures':0},{'id':'b','failures':2},
{'id':'c','permanent':True},{'id':'d','failures':99}]
flow=Dataflow('retry_budget')
source=op.input('requests',flow,TestingSource(events))
def request(event):
delays=[];rng=random.Random(sum(map(ord,event['id'])))
for attempt in range(1,max_attempts+1):
if event.get('permanent'):
return {'id':event['id'],'status':'quarantine','attempts':attempt,'reason':'permanent','planned_delays_ms':delays}
if attempt>event.get('failures',0):
return {'id':event['id'],'status':'success','attempts':attempt,'planned_delays_ms':delays}
if attempt<max_attempts:delays.append(100*2**(attempt-1)+rng.randrange(10))
return {'id':event['id'],'status':'quarantine','attempts':max_attempts,'reason':'budget exhausted','planned_delays_ms':delays}
handled=op.map('bounded_policy',source,request)
rows=sorted(collect(flow,handled),key=lambda r:r['id'])
return {'success':[r['id'] for r in rows if r['status']=='success'],
'quarantine':[r['id'] for r in rows if r['status']=='quarantine'],
'total_attempts':sum(r['attempts'] for r in rows),'trace':rows,
'boundary':'Real Bytewax map; authored service-failure fixture. Delays are planned values, not sleeps or observed latency; no external service is called.'}Do not block the worker with backoff
Sleeping inside a synchronous map blocks that worker’s other records. A production design needs a bounded asynchronous facility, scheduled retry stream or separate worker queue, with preserved per-key ordering where required. A delay plan in this lab is not an implementation of those facilities.
Use one retry budget across layers
If a client, operator and downstream service each independently retry three times, one logical request can create many more attempts. Budget total attempts, elapsed age and queued bytes. Add jitter to reduce synchronized retry bursts, and keep permanent failures out of that loop.
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.
| Question | Mechanism and boundary |
|---|---|
| Work | Attempt work is proportional to the sum of attempts, not just input count. Retry amplification consumes CPU and downstream quotas even when final output is unchanged. |
| State | The fixture collects attempt evidence. A real delayed-retry system also retains payloads, identities, deadlines and scheduling state. |
| Movement | No RPC occurs here. Production retries repeat serialization, network traffic and potentially external side effects. |
| Progress | Recorded backoff values are plans only. Actual readiness, cancellation and rate limits belong to a real scheduler. |
| Recovery | A timeout may follow a completed external effect. Retrying safely requires stable identity and a sink/service contract beyond the engine checkpoint. |
Think it through
Can a side-effecting request be retried safely after its response times out?
Show hints
Hint 1
A timeout does not tell you whether the remote effect happened.
Hint 2
A request identity may need to survive every attempt.
Hint 3
Read-only retries and payment retries have different consequences.
Show explanation
Only with an appropriate remote idempotency or reconciliation contract. A timeout is an unknown outcome, not proof that no effect occurred. Preserve the same idempotency key across attempts, cap attempts and age, honor retryability/rate limits, and route exhausted or permanent failures with enough context for an owner to resolve them.
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.
A mapper can implement retry policy
The retries are authored, bounded attempts with calculated delays. They are not built-in durable retries or measured sleeping time.
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 Bytewax execution of a bounded policy fixture; no external dependency, real sleeping, asynchronous scheduler, circuit breaker or exactly-once RPC guarantee.
Primary reference →