MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

What is Saga pattern in Microservices?

The Saga pattern keeps data consistent across microservices without a distributed (two-phase commit) transaction. A business process is split into a sequence of local transactions, one per service. If one step fails, the saga runs compensating transactions that undo the steps that already succeeded.

The Saga pattern is a design pattern way to manage data consistency across microservices in distributed transaction scenarios. It is a sequence of transactions that updates each service and publishes a message or event to excess next transaction.

Saga pattern diagram showing a sequence of local transactions across microservices linked by events

Saga pattern manage distributed transactions in a event diffeerent architecture.Originally will describe be research paper Princeton University in 1987. It describe as

Long -lived transactions (LLTs)

Hours or days
same database
fine-grained trasactions
compensating operations

extended to distributed system

Centralize transaction state
Message routing
failure compensation

Saga pattern where Post Creation coordinates timeline, photo screening, advertising and payment services

Saga patter complete to use Social media platform all over World


Why microservices need sagas

In a microservice architecture each service owns its own database. A single business action, such as placing an order, touches several of them. A classic ACID transaction cannot span those databases, and two-phase commit (2PC) is rarely practical: it holds locks across services, reduces availability when any participant is down, and many databases and message brokers do not support it. A saga accepts eventual consistency instead: each step commits locally, and the system as a whole becomes consistent once the saga finishes or is compensated.

How a saga works: an order example

StepServiceLocal transactionCompensating transaction
1OrderCreate order with status PENDINGMark order REJECTED
2PaymentAuthorize the paymentRelease or refund the payment
3InventoryReserve the itemsRelease the reservation
4ShippingSchedule the deliveryCancel the delivery
5OrderMark order APPROVED(not needed: last step)

If step 3 fails because an item is out of stock, the saga runs the compensations for the completed steps in reverse order: it refunds the payment (step 2) and marks the order REJECTED (step 1). The customer sees a clear outcome and no money is kept for an order that cannot be shipped.

Choreography vs orchestration

Choreography

There is no central coordinator. Each service listens for events and publishes its own: Order publishes OrderCreated, Payment reacts and publishes PaymentAuthorized, Inventory reacts to that, and so on. Failures are signalled with events such as InventoryReservationFailed, which other services react to by compensating.

Orchestration

A dedicated orchestrator (often part of the Order service, or a workflow engine) tells each service what to do with commands and waits for replies. It holds the saga state and decides which compensations to run.

ChoreographyOrchestration
CoordinatorNone, services react to eventsOne orchestrator owns the flow
CouplingServices depend on each other’s eventsServices depend only on the orchestrator
VisibilityFlow is spread across services, harder to followFlow is in one place, easy to see and test
Best forShort sagas with 2 to 4 stepsLonger or frequently changing business processes

Designing compensating transactions

  • A compensation is a semantic undo, not a database rollback: you cannot un-send an email, but you can send a correction; you do not delete a payment, you refund it.
  • Compensations must be idempotent and retryable, because a message can be delivered more than once.
  • Identify the pivot transaction: the step after which the saga is committed to finishing. Steps before it must be compensatable; steps after it must be retriable until they succeed.
  • Put steps that are most likely to fail (such as stock checks) early, to keep compensation cheap.

Handling the missing isolation

A saga gives you atomicity, consistency and durability, but not isolation: other requests can see intermediate states. Common countermeasures:

  • Semantic lock: a status such as PENDING tells other operations the record is in the middle of a saga.
  • Commutative updates: design updates so they can be applied in any order (for example, increment and decrement a balance).
  • Reread value / version check: re-check a record before updating it and abort if it changed.

Reliable messaging with the transactional outbox

Each step must update its database and publish an event; if it does one without the other, the saga breaks. The transactional outbox pattern solves this: the service writes the event into an outbox table in the same local transaction as the business data, and a separate relay publishes it to the message broker (by polling the table or with change data capture tools such as Debezium). Consumers record the IDs of processed messages so duplicates are ignored.

Tools and frameworks

  • Workflow engines for orchestration: Temporal, Camunda (Zeebe), Netflix/Orkes Conductor, AWS Step Functions, Azure Durable Functions.
  • Libraries: Axon Framework and Eventuate Tram Sagas (Java), MassTransit and NServiceBus (.NET).

When to use the Saga pattern

  • Use it when one business transaction spans several services that each own their data.
  • Avoid it when the data can live in one service and one database: a local ACID transaction is simpler and stronger.
  • Avoid it when the business truly needs strict isolation between concurrent operations and cannot tolerate intermediate states.

Where the pattern comes from

The term comes from the 1987 paper “Sagas” by Hector Garcia-Molina and Kenneth Salem of Princeton University. It described how to break long-lived transactions (running for hours or days) inside a single database into a series of short transactions with compensating actions. The same idea was later applied to distributed systems and microservices.

Frequently asked questions

What is the difference between a saga and two-phase commit?

2PC locks all participants until everyone agrees to commit, giving full ACID guarantees at the cost of availability. A saga commits each step immediately and uses compensations on failure, giving eventual consistency with higher availability.

Is a saga ACID?

It provides atomicity (all steps complete or are compensated), consistency and durability, but not isolation. Intermediate states are visible to other operations.

What happens if a compensating transaction fails?

It is retried until it succeeds, which is why compensations must be idempotent. If it keeps failing, the saga is parked and an alert or dead-letter queue triggers manual intervention.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Wiring Image Generation Into a CI/CD-Era Product Stack: What Platform Teams Actually Have to Solve

Image generation arrived in most engineering backlogs the same way object storage once did — as somebody else’s feature request that turned out to be an infrastructure…

Read More

Ruby on Rails vs Node.js: Performance, Speed, and Scalability Compared

Choosing between Ruby on Rails and Node.js is a common decision when building modern web applications. Both frameworks power large-scale products, but they approach performance, concurrency, and…

Read More

Principal Software Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The Principal Software Engineer is a senior individual contributor (IC) engineering leader responsible for shaping and evolving the technical direction of critical product and platform areas, while materially improving engineering execution, quality, reliability, and long-term maintainability. The role operates across multiple teams and services, solving ambiguous, high-impact technical problems and setting standards that scale with organizational growth.

Read More

Principal Backend Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Principal Backend Engineer** is a senior individual contributor (IC) responsible for shaping backend architecture, engineering standards, and reliability outcomes across multiple teams or a major platform area. This role designs and evolves critical backend systems, addresses complex scalability and data-consistency problems, and creates leverage by enabling other engineers to deliver safely and quickly.

Read More

Senior Integration Consultant: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Senior Integration Consultant** designs, delivers, and governs enterprise-grade integrations that connect business applications, data platforms, and external partner systems reliably and securely. The role blends hands-on technical execution (APIs, middleware, messaging, data mapping, automation) with consulting responsibilities (discovery, requirements translation, stakeholder alignment, delivery leadership) to ensure integrations meet business outcomes and operational standards.

Read More

Principal Integration Consultant: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Principal Integration Consultant** is a senior, hands-on consulting and delivery leader responsible for designing, governing, and enabling enterprise-grade integrations across applications, data platforms, and business processes. This role translates business outcomes into integration strategies and reference architectures, then drives delivery through technical leadership, stakeholder alignment, and quality governance.

Read More