Microservices Communication Patterns (Saga, Circuit Breaker) · Lekcja

Blokady semantyczne i współbieżne sagi

Obsłużą Państwo współbieżność w sagach za pomocą środków zaradczych, takich jak blokady semantyczne, aktualizacje przemienne i pesymistyczne widoki, aby zapobiegać brudnym odczytom i utraconym aktualizacjom w nakładających się transakcjach.

Lekcja 4 z 413 kroki

Blokady semantyczne i współbieżne sagi to bezpłatna lekcja Microservices Communication Patterns (Saga, Circuit Breaker) na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Microservices Communication Patterns (Saga, Circuit Breaker), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Microservices Communication Patterns (Saga, Circuit Breaker) zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Microservices Communication Patterns (Saga, Circuit Breaker) dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Blokady semantyczne i współbieżne sagi” jest bezpłatna?

Tak — pełny tekst „Blokady semantyczne i współbieżne sagi” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Microservices Communication Patterns (Saga, Circuit Breaker), przejdź na CoddyKit PRO. Kurs Microservices Communication Patterns (Saga, Circuit Breaker) zawiera 4 lekcji w sumie.

Co nauczysz się w „Blokady semantyczne i współbieżne sagi”?

Obsłużą Państwo współbieżność w sagach za pomocą środków zaradczych, takich jak blokady semantyczne, aktualizacje przemienne i pesymistyczne widoki, aby zapobiegać brudnym odczytom i utraconym aktual… Ćwiczysz Microservices Communication Patterns (Saga, Circuit Breaker) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Microservices Communication Patterns (Saga, Circuit Breaker)?

Nie wymagamy żadnego doświadczenia. Microservices Communication Patterns (Saga, Circuit Breaker) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Blokady semantyczne i współbieżne sagi”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Microservices Communication Patterns (Saga, Circuit Breaker)?

Tak. Każda lekcja Microservices Communication Patterns (Saga, Circuit Breaker) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zapewnianie idempotencji w sagach
  2. Strategie ponawiania prób dla sag
  3. Zaawansowana logika kompensacji
  4. Blokady semantyczne i współbieżne sagi
← Powrót do Microservices Communication Patterns (Saga, Circuit Breaker)