惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
K
Kaspersky official blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
The Exploit Database - CXSecurity.com
Cisco Talos Blog
Cisco Talos Blog
P
Palo Alto Networks Blog
Latest news
Latest news
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
The Hacker News
The Hacker News
T
Tor Project blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Cisco Blogs
阮一峰的网络日志
阮一峰的网络日志
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园_首页
N
News and Events Feed by Topic
W
WeLiveSecurity
罗磊的独立博客
GbyAI
GbyAI
T
Troy Hunt's Blog
Y
Y Combinator Blog
Recorded Future
Recorded Future
The Cloudflare Blog
TaoSecurity Blog
TaoSecurity Blog
爱范儿
爱范儿
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Check Point Blog
Engineering at Meta
Engineering at Meta
Cyberwarzone
Cyberwarzone
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
Know Your Adversary
Know Your Adversary
AWS News Blog
AWS News Blog
D
DataBreaches.Net
Recent Announcements
Recent Announcements
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
M
MIT News - Artificial intelligence
Webroot Blog
Webroot Blog
Security Latest
Security Latest
T
Tailwind CSS Blog
V2EX - 技术
V2EX - 技术
aimingoo的专栏
aimingoo的专栏
S
Security @ Cisco Blogs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Saga Pattern Without the Drama: A Real Order Service in 200 Lines
Gabriel Anha · 2026-04-26 · via DEV Community

There is a class of bug that only appears in checkout flows on Sunday nights. The order is created. The inventory is reserved. The payment service times out, retries, and charges twice. The shipment label is printed for the second charge. The customer gets one box and an email saying their refund is on the way. Somewhere a junior engineer is googling "distributed transaction rollback Stripe."

A saga is what you build instead of pretending you can have a distributed transaction. It is a state machine. Each step does work in its own service. If a later step fails, earlier steps run a compensation. Not a rollback: you cannot rollback a charge or an email or a label that already printed. You issue a refund. You release the reservation. The shipment gets cancelled.

Chris Richardson's saga page on microservices.io has the canonical definition. Microsoft's Azure Architecture Center has the cloud-flavored version. Both agree on the same uncomfortable thing: the saga is an explicit state machine you have to write, store, and recover. Hand-waving "we'll just publish events and figure it out" is how you get the Sunday-night bug.

This post builds the canonical order saga in 200 lines of Python: place order, reserve inventory, charge payment, ship. Orchestrated, because orchestration is easier to reason about than choreography when the saga has more than three steps. Durable state, because in-memory sagas die when the pod restarts. Compensations, because that is the entire point.

Orchestration over choreography

Choreography means each service emits an event and other services react. No central coordinator. Beautiful on a slide. In production, debugging a failed order means tailing four log streams and reconstructing the order they fired in.

Orchestration means one service (the saga orchestrator) owns the state machine. It tells inventory to reserve, waits for the reply, tells payment to charge, waits for the reply, and so on. If something fails, it knows exactly which compensations to run and in what order.

Chris Richardson argues for orchestration as participant count grows, and the order saga has four. Orchestration. No drama.

The state machine

The order saga has six states a happy path can be in and three terminal states for failure cases.

PENDING -> INVENTORY_RESERVED -> PAYMENT_CHARGED
        -> SHIPPED -> COMPLETED

Failure paths (compensations in reverse):
PAYMENT_FAILED       -> COMPENSATING -> CANCELLED
SHIPPING_FAILED      -> COMPENSATING -> CANCELLED
INVENTORY_REJECTED   -> CANCELLED

Enter fullscreen mode Exit fullscreen mode

If payment fails, we release the inventory. If shipping fails, we refund the payment and release the inventory. If inventory itself rejects, there is nothing to compensate — we just mark the order cancelled.

The orchestrator in 200 lines

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable
import json
import time
import uuid


class State(str, Enum):
    PENDING = "pending"
    INVENTORY_RESERVED = "inventory_reserved"
    PAYMENT_CHARGED = "payment_charged"
    SHIPPED = "shipped"
    COMPLETED = "completed"
    COMPENSATING = "compensating"
    CANCELLED = "cancelled"


@dataclass
class SagaState:
    saga_id: str
    order_id: str
    customer_id: str
    items: list[dict]
    amount: int  # cents
    state: State = State.PENDING
    reservation_id: str | None = None
    charge_id: str | None = None
    shipment_id: str | None = None
    last_error: str | None = None
    history: list[dict] = field(default_factory=list)

    def transition(self, to: State, **meta) -> None:
        self.history.append({
            "from": self.state.value,
            "to": to.value,
            **meta,
        })
        self.state = to


class SagaStore:
    """Durable state. In production: Postgres row per saga."""
    def __init__(self, db):
        self.db = db

    def save(self, s: SagaState) -> None:
        self.db.execute(
            "INSERT INTO sagas (id, payload) VALUES (%s, %s) "
            "ON CONFLICT (id) DO UPDATE SET payload = %s",
            (s.saga_id, json.dumps(s.__dict__, default=str),
             json.dumps(s.__dict__, default=str)),
        )

    def load(self, saga_id: str) -> SagaState:
        row = self.db.fetchone(
            "SELECT payload FROM sagas WHERE id = %s",
            (saga_id,),
        )
        return SagaState(**json.loads(row["payload"]))


class OrderSaga:
    def __init__(self, store, inventory, payment, shipping, alerts):
        self.store = store
        self.inventory = inventory
        self.payment = payment
        self.shipping = shipping
        self.alerts = alerts

    def start(self, order_id, customer_id, items, amount) -> str:
        s = SagaState(
            saga_id=str(uuid.uuid4()),
            order_id=order_id,
            customer_id=customer_id,
            items=items,
            amount=amount,
        )
        self.store.save(s)
        self._reserve_inventory(s)
        return s.saga_id

    def _reserve_inventory(self, s: SagaState) -> None:
        try:
            res_id = self.inventory.reserve(
                s.order_id, s.items,
                idempotency_key=f"reserve:{s.saga_id}",
            )
            s.reservation_id = res_id
            s.transition(State.INVENTORY_RESERVED)
            self.store.save(s)
            self._charge_payment(s)
        except InventoryRejected as e:
            s.last_error = str(e)
            s.transition(State.CANCELLED, reason="inventory_rejected")
            self.store.save(s)

    def _charge_payment(self, s: SagaState) -> None:
        try:
            charge = self.payment.charge(
                s.customer_id, s.amount,
                idempotency_key=f"charge:{s.saga_id}",
            )
            s.charge_id = charge
            s.transition(State.PAYMENT_CHARGED)
            self.store.save(s)
            self._ship(s)
        except PaymentFailed as e:
            s.last_error = str(e)
            s.transition(State.COMPENSATING, step="payment")
            self.store.save(s)
            self._compensate(s)

    def _ship(self, s: SagaState) -> None:
        try:
            sid = self.shipping.create(
                s.order_id,
                idempotency_key=f"ship:{s.saga_id}",
            )
            s.shipment_id = sid
            s.transition(State.SHIPPED)
            s.transition(State.COMPLETED)
            self.store.save(s)
        except ShippingFailed as e:
            s.last_error = str(e)
            s.transition(State.COMPENSATING, step="shipping")
            self.store.save(s)
            self._compensate(s)

    def _compensate(self, s: SagaState) -> None:
        # Run compensations in reverse order of completion.
        if s.charge_id:
            self._safe(
                lambda: self.payment.refund(
                    s.charge_id,
                    idempotency_key=f"refund:{s.saga_id}",
                ),
                s, "refund",
            )
        if s.reservation_id:
            self._safe(
                lambda: self.inventory.release(
                    s.reservation_id,
                    idempotency_key=f"release:{s.saga_id}",
                ),
                s, "release",
            )
        if s.state != State.CANCELLED:
            s.transition(State.CANCELLED)
            self.store.save(s)

    def _safe(self, fn: Callable, s: SagaState, name: str) -> None:
        for attempt in range(5):
            try:
                fn()
                return
            except Exception as e:
                if attempt == 4:
                    self.alerts.page(
                        f"compensation_failed:{name}",
                        saga_id=s.saga_id,
                        error=str(e),
                    )
                    self.store.save(s)
                    return
                time.sleep(2 ** attempt)

Enter fullscreen mode Exit fullscreen mode

That is the whole thing. Around 130 lines of orchestrator plus the state and store. Add the participant clients (InventoryClient, PaymentClient, ShippingClient) as boring HTTP wrappers and you are at 200.

The details that earn their lines:

Idempotency keys on every external call. The key is derived from the saga ID and the step name. If the saga restarts mid-step, the next attempt sends the same key. (The pod may have crashed after we sent the request but before we recorded the response.) Inventory, payment, and shipping all dedupe. Microsoft's Azure saga pattern page walks through why idempotency is the only way to make sagas safe under retries.

Durable state on every transition. The orchestrator writes to the saga store before and after every external call. If the process dies, a recovery worker reads pending sagas and resumes from the last persisted state. No state in memory. No "restart from the beginning" drift.

Compensations run in reverse completion order. Refund first (it was last to succeed), then release the reservation. Each compensation is wrapped in _safe, which retries five times with exponential backoff and pages on failure.

Saga vs distributed transaction

The line that gets glossed over: a saga is not a distributed transaction. There is no rollback. There is no atomic "everything happens or nothing happens" guarantee. The window between "inventory reserved" and "payment charged" is a window in which the system is observably inconsistent (inventory shows reserved, payment shows nothing), and there is no avoiding it without two-phase commit, which you do not want.

What you get instead is eventual consistency with explicit compensation. The system reaches a consistent state, but it takes time, and the consistency you reach might be "this order was cancelled" rather than "this order was placed." The compensation is the contract. If you cannot describe a compensation for a step, that step does not belong in a saga.

This is the part Chris Richardson's saga page hammers on, and it is the part most tutorials elide. The saga is a business-level guarantee, not a technical one. "If the payment fails, we release the inventory" is a thing the business agreed to.

What if compensation fails

This is the question that separates demos from production. The demo assumes refunds always succeed. Production assumes nothing.

The pattern is the one in _safe above: retry with backoff, then alert and dead-letter the compensation to a manual queue. A human looks at it. The order is in the COMPENSATING state until either the retry succeeds or someone marks it resolved. The customer gets an email. The support team has a runbook for "your refund is in flight, here is the ticket number."

What you do not do is silently mark the saga CANCELLED when the refund fails. The state machine has to reflect reality. If the refund didn't happen, the saga didn't reach CANCELLED. It stayed in COMPENSATING. The dashboard shows COMPENSATING > 1h as a red tile. Someone is paged.

The other failure mode worth naming: the compensation succeeds but you crash before recording it. The next attempt re-invokes the refund. Hence the idempotency key on the refund call. Stripe and every reasonable payment provider recognize the duplicate and return the original result.

Oracle's lock-free reservations approach is a database-level take on the same problem: reservations as first-class objects that the engine knows how to compensate. Worth reading if you are on Oracle 23ai. The pattern is the same shape; the database does some of the bookkeeping for you.

What goes in the saga store

The minimum is: saga ID, current state, payload (the immutable inputs), step IDs from external services (reservation, charge, shipment), and the transition history. The history is non-negotiable. When a customer asks why their order is in this state, you want to read a log, not reconstruct it from three services' audit tables.

In Postgres, that is one row per saga with a JSONB payload column and an index on state so the recovery worker can query WHERE state IN ('pending', 'compensating') AND updated_at < now() - interval '5 minutes'. Anything older than five minutes that is not in a terminal state is a saga that needs a human or a retry.

The Sunday-night bug, revisited

There is no framework that does this for you correctly without you understanding it. Temporal, Camunda, AWS Step Functions all give you better primitives, but the modeling work is the same. The reason sagas feel hard is that distributed-system honesty is hard. Once you write the state machine down and stop pretending you have a transaction, the code is short and the bugs are findable.

The Sunday-night double-charge bug? It does not happen. The retry hits the payment service with the same idempotency key. The payment service returns the original charge. The saga moves on. The next failure mode worth modeling is the dual-write between the orchestrator and its message bus, and that is the outbox pattern, which is its own post.


If this was useful

The Event-Driven Architecture Pocket Guide covers sagas in production — orchestration vs choreography tradeoffs, the outbox pattern for the message-bus side, idempotency at every layer, and the failure modes you only hit after a few thousand orders. If the code above looks like a skeleton you'd want fleshed out into a real service, it is the longer version of this post.

Event-Driven Architecture Pocket Guide