Back
+30 XP
Concept

Async Context Manager with Rollback Hook

Distributed systems lack automatic two-phase commit transactions. An async context manager with rollback hooks records compensating actions as steps complete. If an exception occurs inside the async with block, registered rollbacks fire in reverse order.

python
class AsyncTransaction:
    def __init__(self):
        self.rollbacks = []
    async def __aexit__(self, exc_type, exc, tb):
        if exc_type is not None:
            for hook in reversed(self.rollbacks):
                await hook()

# Async Context Manager with Rollback Hook When your backend reserves credit card funds, decrements warehouse inventory, and issues an API token across three distinct microservices, a failure at step 3 leaves steps 1 and 2 dangling in inconsistent states. ⚡🛡️ The **Saga / Compensating Transaction** pattern solves this. By implementing an asynchronous context manager (`__aenter__` and `__aexit__`), you can register undo callbacks after each success. If any subsequent step fails, all registered rollbacks execute in reverse order (LIFO), restoring pristine state. ```python class AsyncTransaction: def __init__(self): self._rollbacks = [] def on_rollback(self, coro, *args): self._rollbacks.append((coro, args)) async def __aexit__(self, exc_type, exc, tb): if exc_type is not None: for coro, args in reversed(self._rollbacks): await coro(*args) return False # Propagate original exception ``` ## Pop Quiz Why must compensating rollback hooks execute in reverse (LIFO) order of their original execution? - [ ] To safely undo dependent state mutations in the exact inverse sequence they were applied. - [ ] Because Python coroutine stacks can only unwind in chronological order. - [ ] To prevent SQLite journal files from exceeding the operating system block size. - [ ] Because forward rollback execution causes memory fragmentation in the asyncio event loop. ## Real-World Challenge Construct an `AsyncTransaction` context manager. It must expose `on_rollback(coro_fn, *args, **kwargs)` and `on_commit(coro_fn, *args, **kwargs)`. When an exception bubbles out of the `async with` block, fire rollbacks in reverse order and propagate the exception. When execution exits without errors, fire commit hooks in original order. <details> <summary>Solution</summary> ```python import asyncio class AsyncTransaction: def __init__(self): self.rollback_hooks = [] self.commit_hooks = [] def on_rollback(self, coro_fn, *args, **kwargs): self.rollback_hooks.append((coro_fn, args, kwargs)) def on_commit(self, coro_fn, *args, **kwargs): self.commit_hooks.append((coro_fn, args, kwargs)) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: for fn, args, kwargs in reversed(self.rollback_hooks): await fn(*args, **kwargs) return False else: for fn, args, kwargs in self.commit_hooks: await fn(*args, **kwargs) # Verification async def run_test(): audit_log = [] async def refund(amount): audit_log.append(f"refunded_{amount}") async def restock(sku): audit_log.append(f"restocked_{sku}") try: async with AsyncTransaction() as tx: audit_log.append("charged_50") tx.on_rollback(refund, 50) audit_log.append("reserved_item_A") tx.on_rollback(restock, "item_A") raise ConnectionError("Inventory warehouse unreachable") except ConnectionError: pass assert audit_log == [ "charged_50", "reserved_item_A", "restocked_item_A", "refunded_50" ] asyncio.run(run_test()) ``` </details>