Lock semantici e saga concorrenti
Gestisca la concorrenza nelle saga usando contromisure come lock semantici, aggiornamenti commutativi e viste pessimistiche, per prevenire dirty read e aggiornamenti persi tra transazioni sovrapposte.
Lock semantici e saga concorrenti è una lezione Microservices Communication Patterns (Saga, Circuit Breaker) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Microservices Communication Patterns (Saga, Circuit Breaker), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Microservices Communication Patterns (Saga, Circuit Breaker) include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Impara Microservices Communication Patterns (Saga, Circuit Breaker) con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Lock semantici e saga concorrenti» è gratuita?
Sì — il testo completo di «Lock semantici e saga concorrenti» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Microservices Communication Patterns (Saga, Circuit Breaker), passa a CoddyKit PRO. Il corso Microservices Communication Patterns (Saga, Circuit Breaker) include 4 lezioni in totale.
Cosa imparerò in «Lock semantici e saga concorrenti»?
Gestisca la concorrenza nelle saga usando contromisure come lock semantici, aggiornamenti commutativi e viste pessimistiche, per prevenire dirty read e aggiornamenti persi tra transazioni sovrapposte. Eserciti Microservices Communication Patterns (Saga, Circuit Breaker) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Microservices Communication Patterns (Saga, Circuit Breaker)?
Non è richiesta alcuna esperienza precedente. Microservices Communication Patterns (Saga, Circuit Breaker) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Lock semantici e saga concorrenti»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Microservices Communication Patterns (Saga, Circuit Breaker)?
Sì. Ogni lezione Microservices Communication Patterns (Saga, Circuit Breaker) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Garantire l'idempotenza nelle Saga
- Strategie di retry per le Saga
- Logica di compensazione avanzata
- Lock semantici e saga concorrenti