System Design Basics for Backend Developers · 课时

分布式事务的 Saga 模式

学习如何使用结合编排与协调的 Saga 模式,在不使用分布式事务的情况下维护微服务之间的数据一致性。

第 4 / 4 课13 个步骤

分布式事务的 Saga 模式 是 CoddyKit 上的免费 System Design Basics for Backend Developers 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 System Design Basics for Backend Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 System Design Basics for Backend Developers 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

The Distributed Transaction Problem

In a monolith, one database transaction can update everything atomically. In microservices, each service owns its own database, so a single classic transaction across them is impractical.

How do you keep data consistent when an operation spans multiple services?

Why Not Two-Phase Commit?

Two-phase commit (2PC) can coordinate a distributed transaction, but it locks resources across services and blocks if the coordinator fails. It scales poorly and hurts availability — usually the wrong fit for microservices.

Enter the Saga

A Saga breaks a business transaction into a sequence of local transactions, one per service. Each step publishes an event or sends a command to trigger the next.

There is no global lock — consistency is achieved over time.

Compensating Transactions

If a later step fails, the saga cannot roll back like a database. Instead it runs compensating transactions that semantically undo the earlier steps.

  • Order placed -> compensate by cancelling order
  • Payment charged -> compensate by refunding

An Order Saga

Consider placing an order: reserve inventory, charge payment, schedule shipping. If payment fails, you compensate by releasing the inventory.

steps = ['reserve_inventory', 'charge_payment', 'schedule_shipping']
compensations = ['release_inventory', 'refund_payment', 'cancel_shipping']

done = []
for i, step in enumerate(steps):
    ok = step != 'charge_payment'
    if not ok:
        print('FAILED at', step)
        for j in reversed(range(len(done))):
            print('compensate:', compensations[j])
        break
    done.append(step)
    print('ok:', step)

Choreography

In choreography, there is no central coordinator. Each service listens for events and reacts by doing its work and emitting the next event. It is decentralized and loosely coupled.

OrderCreated -> (Inventory) -> InventoryReserved
InventoryReserved -> (Payment) -> PaymentCharged
PaymentCharged -> (Shipping) -> OrderShipped

Choreography Trade-offs

Choreography is simple for short flows but the overall logic is scattered across services. With many steps it becomes hard to understand and risks cyclic event dependencies.

Orchestration

In orchestration, a central orchestrator tells each service what to do and tracks progress. The workflow lives in one place, making complex sagas easier to reason about and monitor.

Orchestrator:
  -> Inventory.reserve()
  -> Payment.charge()
  -> Shipping.schedule()
  on failure -> run compensations in reverse

Idempotency Is Mandatory

Messages can be delivered more than once, so every saga step and compensation must be idempotent. Use an idempotency key so re-processing the same message has no extra effect.

Eventual Consistency

Sagas give eventual consistency, not immediate. There is a window where the system is partially updated. Design the UI and business rules to tolerate this — for example, an order shown as PENDING until confirmed.

Choosing an Approach

Use choreography for simple flows with few participants, and orchestration when the workflow is complex or needs central visibility. Either way, make steps idempotent and define a compensation for every action.

Quick Check

Test your understanding of the Saga pattern.

Recap

You learned how microservices stay consistent without distributed transactions:

  • Sagas chain local transactions with compensations for failures
  • Choreography is decentralized; orchestration is centralized
  • Steps must be idempotent against duplicate delivery
  • The result is eventual consistency, which the design must tolerate
免费开始

用 AI 导师学习 System Design Basics for Backend Developers — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「分布式事务的 Saga 模式」课时是免费的吗?

是的 — 「分布式事务的 Saga 模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 System Design Basics for Backend Developers 课程的其余内容,请升级到 CoddyKit PRO。 System Design Basics for Backend Developers 课程共包含 4 节课。

「分布式事务的 Saga 模式」这节课中我会学到什么?

学习如何使用结合编排与协调的 Saga 模式,在不使用分布式事务的情况下维护微服务之间的数据一致性。 你通过在浏览器中直接运行的动手代码来练习 System Design Basics for Backend Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 System Design Basics for Backend Developers 需要有经验吗?

无需任何先前经验。CoddyKit 上的 System Design Basics for Backend Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「分布式事务的 Saga 模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 System Design Basics for Backend Developers 课中编写并运行代码吗?

能。每节 System Design Basics for Backend Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 拆分单体应用
  2. 服务发现与注册中心
  3. 服务间通信模式
  4. 分布式事务的 Saga 模式
← 返回 System Design Basics for Backend Developers