FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Distributed Transactions & Saga Pattern

Two-Phase Commit (2PC) vs Saga pattern, compensating transactions, outbox pattern, and transactional messaging.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Architect Saga workflows with compensating actions
  • ✓Implement the Transactional Outbox pattern for reliable messaging
Full Technical Reference Document

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.

Local ACID Commit + Outbox Insert
Relay Publishes Step Event Idempotently
Downstream Service Applies Local TX
Failure Triggers Reverse Compensation Chain
Semantic State Converges Cleanly
Conceptual teaching model synthesized from:ddia-kleppmann,postgresql-docs,rabbitmq-docs

Theory

Microservice architects weigh immediate isolation (2PC) against high-availability eventual consistency (Sagas):

Coordination ModelConsistency & LockingFailure Handling MechanismBest Operational Boundary
Two-Phase Commit (2PC / XA)Strict atomic commit across locks (PREPARE + COMMIT)Coordinator blocks holding locks across all participants if node stallsLegacy monoliths sharing XA-compliant databases on reliable LANs only
Orchestrated SagaEventual consistency (local ACID commits per step)Central state machine persists step_state and executes explicit reverse compensationsComplex multi-step checkout, LLM billing + quota provisioning (4–12 steps)
Choreographed SagaEventual consistency without central coordinatorServices react independently to domain events on RabbitMQ/KafkaLoosely 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.

python
from datetime import UTC, datetime
import uuid
from fastapi import HTTPException
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
​
async 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 NOTHING
RETURNING 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 start
return {"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 of PENDING_* 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...COMMIT ACID 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 outbox state-machine boilerplate at the cost of running an external workflow server.

Failure modes and misconceptions

  1. Dual-Write State Drift (db.commit() Followed by rabbitmq.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.
  2. Non-Idempotent Forward Steps or Non-Idempotent Compensations: Retrying a failed network step (charge_card) or retrying an interrupted rollback (release_inventory) without an immutable idempotency_key double-charges users or inflates inventory counts past real stock. Enforce unique idempotency_key constraints on every step and every compensation!
  3. 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.
  4. Assuming Sagas Roll Back Like SQL ROLLBACK: Compensations leave permanent audit history (OrderCreated followed by OrderCancelled / PaymentRefunded), and intermediate states remain visible to concurrent readers until the Saga settles unless Semantic Locks reject conflicting mutations explicitly.
Reflect before revealing the guide

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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next