语义锁与并发 Saga
使用语义锁、交换律更新和悲观视图等应对措施处理 Saga 中的并发,防止重叠事务之间出现脏读和更新丢失。
语义锁与并发 Saga 是 CoddyKit 上的免费 Microservices Communication Patterns (Saga, Circuit Breaker) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Microservices Communication Patterns (Saga, Circuit Breaker) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Concurrency Problem
Sagas relax isolation: intermediate states are visible to other transactions. When two sagas touch the same data concurrently, you risk dirty reads, lost updates, and fuzzy reads.
This lesson covers countermeasures that restore safety without full ACID isolation.
Anomaly: Lost Update
A lost update happens when one saga overwrites a change made by another that it did not see.
- Saga A reads balance 100.
- Saga B reads balance 100, subtracts 30, writes 70.
- Saga A subtracts 50 from its stale 100, writes 50.
B's deduction is lost.
Countermeasure: Semantic Lock
A semantic lock marks a record as in-progress using an application-level flag, not a database lock.
For example, set an order's status to PENDING. Other sagas see the flag and refuse to act until the saga commits or compensates.
order = {'id': 1, 'status': 'PENDING'}
def can_modify(order):
return order['status'] != 'PENDING'
print('Can modify:', can_modify(order))Releasing the Lock
The semantic lock is released by the final saga step or by the compensating transaction. The status moves to APPROVED or back to AVAILABLE.
def finalize(order, success):
order['status'] = 'APPROVED' if success else 'CANCELLED'
return order['status']
order = {'status': 'PENDING'}
print(finalize(order, True))Countermeasure: Commutative Updates
Design updates that can be applied in any order and produce the same result. Addition and subtraction on a balance are commutative; setting an absolute value is not.
Prefer balance += delta over balance = newValue.
balance = 100
# two sagas apply deltas in any order
for delta in [-30, -50]:
balance += delta
print('Final balance:', balance)Countermeasure: Pessimistic View
Reorder saga steps so that the steps most likely to fail run first, minimizing the window during which dirty data is exposed.
If a risky step succeeds early, later steps are far less likely to need compensation.
Countermeasure: Reread Value
Before writing, reread the record and verify it has not changed since you read it. If it changed, abort and retry. This is optimistic concurrency control.
def safe_write(current_version, expected_version):
if current_version != expected_version:
return 'ABORT: data changed'
return 'WRITE OK'
print(safe_write(5, 5))
print(safe_write(6, 5))Version Numbers and Optimistic Locking
Store a version column with each record. Each update increments the version and includes the expected version in the WHERE clause.
- If zero rows update, someone else changed it first.
- The saga retries with fresh data.
Countermeasure: By Value
Choose your concurrency strategy by the business risk of the data. High-value records (large payments) get strict semantic locks; low-risk records use looser, more available approaches.
Combining Countermeasures
Real systems mix several techniques: a semantic lock to mark in-progress orders, commutative updates for counters, and version checks for critical writes. The goal is to keep sagas correct while preserving availability.
Trade-offs
Every countermeasure adds complexity. Semantic locks can cause contention; rereads add round-trips. Choose the lightest mechanism that prevents the anomalies your domain actually cares about.
Quick Check
Which countermeasure marks a record as in-progress using an application-level status so other sagas refuse to act on it?
Recap
You learned countermeasures for concurrent sagas:
- Semantic locks flag in-progress records.
- Commutative updates make order-of-application irrelevant.
- Pessimistic view reorders risky steps first.
- Reread/version checks catch concurrent changes.
Together these restore safety without full ACID isolation.
用 AI 导师学习 Microservices Communication Patterns (Saga, Circuit Breaker) — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「语义锁与并发 Saga」课时是免费的吗?
是的 — 「语义锁与并发 Saga」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Microservices Communication Patterns (Saga, Circuit Breaker) 课程的其余内容,请升级到 CoddyKit PRO。 Microservices Communication Patterns (Saga, Circuit Breaker) 课程共包含 4 节课。
「语义锁与并发 Saga」这节课中我会学到什么?
使用语义锁、交换律更新和悲观视图等应对措施处理 Saga 中的并发,防止重叠事务之间出现脏读和更新丢失。 你通过在浏览器中直接运行的动手代码来练习 Microservices Communication Patterns (Saga, Circuit Breaker),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Microservices Communication Patterns (Saga, Circuit Breaker) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Microservices Communication Patterns (Saga, Circuit Breaker) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「语义锁与并发 Saga」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Microservices Communication Patterns (Saga, Circuit Breaker) 课中编写并运行代码吗?
能。每节 Microservices Communication Patterns (Saga, Circuit Breaker) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 确保 Saga 的幂等性
- Saga 的重试策略
- 高级补偿逻辑
- 语义锁与并发 Saga