Wzorzec Saga dla transakcji rozproszonych
Dowiedz się, jak utrzymywać spójność danych między mikrousługami bez transakcji rozproszonych, wykorzystując wzorzec Saga z choreografią i orkiestracją.
Wzorzec Saga dla transakcji rozproszonych to bezpłatna lekcja System Design Basics for Backend Developers 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 System Design Basics for Backend Developers, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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) -> OrderShippedChoreography 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 reverseIdempotency 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
Często zadawane pytania
Czy lekcja „Wzorzec Saga dla transakcji rozproszonych” jest bezpłatna?
Tak — pełny tekst „Wzorzec Saga dla transakcji rozproszonych” 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 System Design Basics for Backend Developers, przejdź na CoddyKit PRO. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.
Co nauczysz się w „Wzorzec Saga dla transakcji rozproszonych”?
Dowiedz się, jak utrzymywać spójność danych między mikrousługami bez transakcji rozproszonych, wykorzystując wzorzec Saga z choreografią i orkiestracją. Ćwiczysz System Design Basics for Backend Developers 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ąć System Design Basics for Backend Developers?
Nie wymagamy żadnego doświadczenia. System Design Basics for Backend Developers 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 „Wzorzec Saga dla transakcji rozproszonych”?
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 System Design Basics for Backend Developers?
Tak. Każda lekcja System Design Basics for Backend Developers 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
- Dekompzycja monolitów
- Wykrywanie i rejestr usług
- Wzorce komunikacji między usługami
- Wzorzec Saga dla transakcji rozproszonych