Mental model
When a single user request must update state across multiple independent databases or external SaaS providers—for instance, creating an order in PostgreSQL, charging a credit card via Stripe, and provisioning a tenant GPU quota—a single database ACID transaction cannot span network boundaries without crippling availability. The Saga Pattern replaces blocking distributed locks (Two-Phase Commit / 2PC) with a sequence of local ACID transactions coordinated forward by events or an explicit orchestrator, paired with deterministic Compensating Transactions that semantically undo earlier completed steps (refund, release_quota, mark_cancelled) whenever a downstream step fails—and backed by a Transactional Outbox so database state and emitted messages never drift apart on crashes.
Theory
Microservice architects weigh immediate isolation (2PC) against high-availability eventual consistency (Sagas):
| Coordination Model | Consistency & Locking | Failure Handling Mechanism | Best Operational Boundary |
|---|---|---|---|
| Two-Phase Commit (2PC / XA) | Strict atomic commit across locks (PREPARE + COMMIT) | Coordinator blocks holding locks across all participants if node stalls | Legacy monoliths sharing XA-compliant databases on reliable LANs only |
| Orchestrated Saga | Eventual consistency (local ACID commits per step) | Central state machine persists step_state and executes explicit reverse compensations | Complex multi-step checkout, LLM billing + quota provisioning (4–12 steps) |
| Choreographed Saga | Eventual consistency without central coordinator | Services react independently to domain events on RabbitMQ/Kafka | Loosely coupled 2–3 step reactions (OrderCreated -> SendReceipt) |
The Dual-Write Problem, Transactional Outbox, and Lack of Isolation (ACD vs ACID)
Calling await db.commit() and then await broker.publish(event) introduces a classic Dual-Write race: if the FastAPI process crashes or the message broker times out right after COMMIT, downstream services never receive the event, leaving permanent data corruption! Solve this cleanly with the Transactional Outbox Pattern: inside the exact same local PostgreSQL transaction, insert both the business mutation (INSERT INTO orders ...) and the outbound event row (INSERT INTO outbox_events ...). A reliable relay worker (polling FOR UPDATE SKIP LOCKED or tailing WAL via Debezium CDC) publishes outbox rows with idempotency keys (event_id).
Crucially too, Sagas provide Atomicity, Consistency, and Durability (ACD)—NOT Isolation (I): intermediate dirty states (like an order stuck in PENDING_PAYMENT while inventory is reserved) are briefly visible to other concurrent queries! Defend against lost updates or concurrent double-spending via Semantic Locks (status = 'PENDING_RESERVATION', reserved_until), Pivot Transactions (the irreversible step after which forward retries replace rollbacks, e.g., capturing payment), and Commutative / Idempotent Compensations.
pythonfrom datetime import UTC, datetimeimport uuidfrom fastapi import HTTPExceptionfrom sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSessionasync def start_order_checkout_with_outbox(db: AsyncSession,order_id: str,user_id: str,amount_cents: int,idempotency_key: str,) -> dict[str, str]:"""Forward + Semantic Lock + Transactional Outbox in ONE atomic local PostgreSQL transaction.Zero dual-write risk between Postgres commit and broker dispatch."""event_id = str(uuid.uuid4())async with db.begin():inserted = await db.execute(text("""INSERT INTO orders (id, user_id, amount_cents, status, idempotency_key)VALUES (:id, :user_id, :amount_cents, 'PENDING_RESERVATION', :ikey)ON CONFLICT (idempotency_key) DO NOTHINGRETURNING id"""),{"id": order_id, "user_id": user_id, "amount_cents": amount_cents, "ikey": idempotency_key},)if not inserted.scalar_one_or_none():# Idempotent replay returns existing workflow cleanly without duplicate Saga startreturn {"order_id": order_id, "status": "ALREADY_STARTED"}# Atomic outbox event persisted alongside order row (never lost even if RabbitMQ is briefly down)await db.execute(text("""INSERT INTO outbox_events (id, aggregate_type, aggregate_id, event_type, payload, created_at)VALUES (:eid, 'order', :oid, 'OrderPendingRequested', :payload::jsonb, :ts)"""),{"eid": event_id,"oid": order_id,"payload": f'{{"order_id": "{order_id}", "amount_cents": {amount_cents}}}',"ts": datetime.now(UTC),},)return {"order_id": order_id, "status": "PENDING_RESERVATION"}
Remember: Compensating actions must also be idempotent and retryable (you cannot rollback a crash mid-compensation cleanly unless refund_payment(order_id) checks whether it already refunded once before calling Stripe again!).
Alternatives and trade-offs
- Saga + Transactional Outbox (
PostgreSQL+RabbitMQ/Temporal): Survives single-service crashes and external SaaS unavailability cleanly while preserving microservice independence; forces explicit domain modeling ofPENDING_*states, compensations, and eventual UI updates. - Modular Monolith (Single PostgreSQL Schema): If two features live inside the same organization and database scaling fits cleanly on one PostgreSQL primary, keeping both tables inside a single local
BEGIN...COMMITACID transaction avoids distributed Sagas completely (zero compensating code, full Isolation!). Never split services across DBs prematurely. - Durable Execution Engines (Temporal / Restate): Persists workflow call stacks automatically as event-sourced steps with deterministic timers, heartbeats, and retry/compensation orchestration—removing custom
outboxstate-machine boilerplate at the cost of running an external workflow server.
Failure modes and misconceptions
- Dual-Write State Drift (
db.commit()Followed byrabbitmq.publish()): Broker timeouts, pod OOMs, or network blips between DB commit and message publish strand orders permanently in limbo. Always use Transactional Outbox or WAL CDC instead of uncoordinated dual writes. - Non-Idempotent Forward Steps or Non-Idempotent Compensations: Retrying a failed network step (
charge_card) or retrying an interrupted rollback (release_inventory) without an immutableidempotency_keydouble-charges users or inflates inventory counts past real stock. Enforce uniqueidempotency_keyconstraints on every step and every compensation! - Splitting Services Prematurely Before Needing Independent Scaling: Introducing Sagas across internal tables that could have lived cleanly inside one PostgreSQL database exchanges a 3-line ACID transaction for months of Saga debugging, UI loading states, and outbox monitoring.
- Assuming Sagas Roll Back Like SQL
ROLLBACK: Compensations leave permanent audit history (OrderCreatedfollowed byOrderCancelled/PaymentRefunded), and intermediate states remain visible to concurrent readers until the Saga settles unless Semantic Locks reject conflicting mutations explicitly.
Decision scenario
Your AI cloud billing flow spans a fast PostgreSQL orders ledger, Stripe billing captures (external HTTP API), and an isolated GPU cluster quota allocator across separate microservices—where holding 2PC database locks across an external Stripe API call would exhaust connection pools immediately. Model the checkout workflow as an Orchestrated Saga backed by a PostgreSQL Transactional Outbox: commit the initial PENDING_PROVISIONING semantic lock row plus outbox trigger atomically in one local transaction, invoke Stripe and GPU allocation asynchronously with deterministic order_id idempotency keys, treat Stripe capture as the non-reversible Pivot Transaction (so quota timeouts retry forward or notify ops rather than silently cancelling paid orders), and mark reverse compensations strictly idempotent and alertable if permanent exhaustion occurs.
Learning outcomes
- Contrast Two-Phase Commit (2PC) lock availability hazards against Saga local-transaction + compensation workflows.
- Eliminate dual-write divergence between PostgreSQL commits and RabbitMQ/Kafka brokers using the Transactional Outbox pattern.
- Design around the missing Isolation (
I) property in Sagas using semantic status locks, pivot steps, and idempotent compensations. - Choose cleanly between Choreography events, Orchestrated state machines, and staying within a single modular ACID monolith.
Trade-offs
Sagas paired with Transactional Outboxes preserve high availability across independent databases and external SaaS APIs without distributed locks, at the complexity cost of explicit pending-state visibility, outbox relays, and idempotent compensating handlers.