aws / aws/aws-durable-execution-docs
Add pattern: Cleanup on completion or failure (not on suspension)
- Dominant language
- Python
- Stars
- 13
- Forks
- 13
- Avg merge
- 3d 2h
- Merged PRs (30d)
- 25
Description
## Problem
Users are running into unexpected results when using `try/finally` blocks with durable operations that suspend (e.g. `wait_for_condition`). When a durable function suspends, the Lambda invocation ends, which causes Python's `finally` block to execute as part of the function exiting scope. This means cleanup steps in `finally` run on every suspension cycle — not just on completion or failure.
Example of the problematic pattern:
```python
try:
context.step(boot_instances)
context.wait_for_condition(poll_load_test)
context.step(collect_results)
finally:
context.step(terminate_instances) # Runs on EVERY suspension!
```
This is standard language behavior — `finally` always runs when exiting the `try` scope — but it's easy to overlook in the context of durable functions where the invocation can end and restart many times as part of normal operation.
## Proposed solution
Add a pattern/recipe to the docs (e.g. under Patterns > Best Practices) showing the correct way to handle cleanup that should only run on completion or failure:
```python
# ✅ Cleanup only on success or failure
try:
context.step(boot_instances)
context.wait_for_condition(poll_load_test)
context.step(collect_results)
context.step(terminate_instances) # On success
except Exception:
context.step(terminate_instances) # On failure
raise
```
This would help users who are accustomed to `try/finally` for resource cleanup in standard applications but don't realize that durable function suspensions also trigger scope exit.
Contributor guide
Assessment
This issue has not been assessed yet.