A Saga is a sequence of local transactions.A Saga is a sequence of local transactions.

A Practical Guide to the Saga Pattern in Spring Boot Microservices

Modern microservices are small, autonomous, and independently deployable — but this also creates a huge problem.

Typical pharmacy prescription management - payments, banking, logistics, supply-chain, or booking systems perform operations across multiple microservices

  • Create Order
  • Reserve Inventory
  • Process Payment
  • Create Shipment
  • Update Loyalty Points

Each runs in its own database, service, and network boundary.

If one operation fails halfway, the entire business flow should not leave the system in an inconsistent state.

This is where the Saga Pattern becomes essential.

What is a Saga? Why Not Use ACID?

A Saga is a sequence of local transactions. \n Each local transaction updates data within one service and publishes an event to trigger the next step.

If a failure occurs:

  • The Saga triggers compensation actions to undo previously completed steps.

Why does ACID (2PC) not work in microservices?

| Problem | Explanation | |:---:|:---:| | 2PC is blocking | If the coordinator crashes, everything hangs. | | Microservices have independent DBs | No shared commit log across distributed DBs. | | Scales poorly | Locks span distributed systems. | | Cloud services do not support XA transactions | DynamoDB, S3, Mongo, Kafka, RDS, etc. |

A Saga avoids these issues with event-driven or orchestrated compensation logic.

Saga Architecture Diagram:

\ Architecture

1. Use Case: Pharmacy Prescription Order Processing

Scenario

Imagine a Pharmacy Prescription Online platform where a customer places an order for a product.

The system involves three independent services:

  1. Order Service – Creates the order record.
  2. Inventory Service – Reserves the product in stock.
  3. Payment Service – Charges the customer.

Problem Without Saga

If one of these steps fails (e.g., payment fails), the previous steps might leave the system in an inconsistent state:

  • Order created
  • Inventory reserved
  • Payment failed
  • Result: Inventory stuck, order incomplete, manual intervention required.

This is unacceptable in enterprise systems, especially when multiple microservices interact.

Solution With Saga

Using a Saga Orchestration Pattern, each service executes its local transaction, and in case of failure, compensation actions roll back previous steps

  • Step 1: Order Service creates an order.
  • Step 2: Inventory Service reserves stock.
  • Step 3: The payment service charges the customer.
  • Failure Handling: If payment fails, the orchestrator calls the Inventory Service to release stock.

This ensures business-level consistency across services.

2. Why We Need the Saga Pattern

  1. Distributed Microservices: Traditional ACID transactions cannot span multiple microservices.
  2. Eventual Consistency: Ensures consistent outcomes without requiring global resource locking.
  3. Fault Tolerance: Automatically rolls back previous steps if a later step fails.
  4. Cloud-Native: Works seamlessly with scalable services in cloud environments.

Loose Coupling: Each service remains independent, communicating only through APIs.

3. Advantages of Using Saga

  • Reliability: Compensating transactions prevent data inconsistencies.
  • Scalability: Each service can scale independently; orchestration is centralized.
  • Resilience: Handles partial failures gracefully.
  • Business-Level Consistency: Focuses on correct business outcomes, not strict database consistency.
  • Monitoring and Debugging: The central orchestrator provides clear logs of each transaction step.

4. Step-by-Step Explanation of the Script

Below is a detailed walkthrough of the key script components from your Spring Boot Saga project.

4.1 Order Model (Order.java)

\

package com.example.orderservice; public class Order {     private Long id;     private String product;     private String status;     public Order() {         // default constructor (required for Jackson)     }     public Order(Long id, String product, String status) {         this.id = id;         this.product = product;         this.status = status;     }     public Long getId() {         return id;     }     public void setId(Long id) {         this.id = id;     }     public String getProduct() {         return product;     }     public void setProduct(String product) {         this.product = product;     }     public String getStatus() {         return status;     }     public void setStatus(String status) {         this.status = status;     } }

  • Purpose: Represents an order.

  • Business Logic: Stores the product name, order ID, and status (CREATED, CANCELLED, COMPLETED).

    4.2 Order Controller (OrderController.java)

    \

package com.example.orderservice; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/orders") public class OrderController {     @PostMapping     public Order create(@RequestParam("product") String product) {         return new Order(1L, product, "CREATED");     }     @PostMapping("/cancel")     public String cancel() {         return "ORDER_CANCELLED";     }     @PostMapping("/complete")     public String complete() {         return "ORDER_COMPLETED";     } }

\

  • Endpoints

  • POST /orders → Creates an order.

  • POST /orders/cancel → Cancels an order (used for compensation).

  • POST /orders/complete → Marks order completed.

  • Why it works with Saga: Endpoints are simple, predictable, and return either the object or a status string for orchestration.

    4.3 Inventory Controller (InventoryController.java)

    \

package com.example.inventoryservice; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/inventory") public class InventoryController {     @PostMapping("/reserve")     public boolean reserve(@RequestParam("product") String product) {         return !"FAIL".equals(product);     }     @PostMapping("/release")     public void release(@RequestParam("product") String product) {} }

\

  • Purpose: Reserves product in stock, releases it if payment fails.

  • Logic: Simulates success/failure. In enterprise systems, this would check actual stock in a database.

    \ 4.4. Payment Controller (PaymentController.java)

    \

package com.example.paymentservice; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/payments") public class PaymentController {     @PostMapping("/pay")     public boolean pay(@RequestParam("amount") double amount) {         return amount <= 5000;     }     @PostMapping("/refund")     public void refund(@RequestParam double amount) {} }

\

  • Purpose: Processes payment and simulates failure for testing.

  • Why it works in Saga: Returns a Boolean indicating success/failure, allowing the orchestrator to trigger compensations.

    4.5. Saga Orchestrator (SagaController.java)

    \

package com.example.sagaorchestrator; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/saga") public class SagaController {     private final RestTemplate rest = new RestTemplate();     @PostMapping("/order")     public String place(@RequestParam("product") String product, @RequestParam("amount") double amount) {         Object order = rest.postForObject(                 "http://localhost:8081/orders?product=" + product,                 null,                 Object.class         );                  if (order == null) {             return "Order creation failed";         }         Boolean inventory = rest.postForObject(             "http://localhost:8082/inventory/reserve?product=" + product,             null,             Boolean.class         );         if (inventory == null || !inventory) {             return "Inventory failed";         }         Boolean payment = rest.postForObject(             "http://localhost:8083/payments/pay?amount=" + amount,             null,             Boolean.class         );         if (payment == null || !payment) {             rest.postForObject(                     "http://localhost:8082/inventory/release?product=" + product,                     null,                     Void.class             );             return "Payment failed, compensated";         }         return "Order completed successfully";     } }

\

  • Flow Explained
  1. Order creation → First step, must succeed to proceed.
  2. Inventory reservation → If it fails, the saga stops.
  3. Payment processing → If it fails, the orchestrator triggers inventory release (compensation).
  4. Success → Returns a success message.

Enterprise Ready: Demonstrates clear orchestration, compensation, and business-level consistency.

\ 4.6 Verification of Outputs

\

  1. Success Case

\

  1. Payment Failure Case

\ Postman

\

  1. Inventory Failure Case:

\ ** Postman

5. Advantages Highlighted

  • Fault-Tolerant: Automatically compensates failed transactions.
  • Business Consistency: Ensures the order state and inventory are always consistent.
  • Scalable: Each service runs independently.
  • Cloud-Native Ready: Can run on Kubernetes or any cloud environment.
  • Enterprise Applicable: Matches real-world systems in healthcare, banking, and data platforms.

6. Why Enterprises Need This Pattern

  • In distributed systems, manual rollback is error-prone.
  • Saga ensures automatic recovery, reducing downtime.
  • Prevents inconsistent data in multi-service workflows.
  • Supports asynchronous processing, improving performance and scalability.

\

Market Opportunity
SAGA Logo
SAGA Price(SAGA)
$0.05856
$0.05856$0.05856
-1.66%
USD
SAGA (SAGA) Live Price Chart
Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Uniswap stemt in met token burn van 100 miljoen UNI

Uniswap stemt in met token burn van 100 miljoen UNI

Uniswap (UNI) heeft een belangrijke stap gezet in de verdere ontwikkeling van zijn tokenomics. In een recente governance-stemming hebben houders van het UNI-token
Share
Coinstats2025/12/26 21:47
Which Crypto to Buy Today for Long-Term Growth? One DeFi Crypto Stands Out

Which Crypto to Buy Today for Long-Term Growth? One DeFi Crypto Stands Out

The post Which Crypto to Buy Today for Long-Term Growth? One DeFi Crypto Stands Out appeared on BitcoinEthereumNews.com. Crypto Projects Investors searching for
Share
BitcoinEthereumNews2025/12/26 22:32
Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550

Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550

Connect met Like-minded Crypto Enthusiasts! Connect op Discord! Check onze Discord   Ethereum laat op de uurgrafiek twee opeenvolgende TD Sequential koopsignalen zien. Deze indicator meet uitputting in een trend en geeft vaak een signaal dat de verkoopdruk kan afnemen. Dit dubbele signaal verschijnt rond het niveau van $4.516, waar de ETH prijs kortstondig steun vindt. Dit type formatie komt zelden voor en wordt daarom extra nauwlettend gevolgd. Wat gaat de Ethereum koers hiermee doen? Ethereum koers test steun rond $4.516 De scherpe daling van de Ethereum koers vanaf de prijszone rond $4.800 bracht de ETH prijs in korte tijd naar ongeveer $4.516. Op dit niveau trad duidelijke koopactiviteit op, waardoor de neerwaartse beweging tijdelijk werd gestopt. Het dubbele signaal dat door de TD Sequential indicator is gegenereerd, viel precies samen met dit prijspunt. De TD Sequential is opgebouwd uit negen candles die een trend meetellen. Wanneer de negende candle verschijnt, kan dit duiden op een trendomslag. In dit geval verschenen zelfs twee signalen kort na elkaar, wat aangeeft dat de verkoopdruk mogelijk uitgeput is. Het feit dat dit gebeurde in een zone waar ETH kopers actief bleven, maakt het patroon extra opvallend. TD Sequential just flashed two buy signals for Ethereum $ETH! pic.twitter.com/JPO8EhiEPi — Ali (@ali_charts) September 16, 2025 Welke crypto nu kopen?Lees onze uitgebreide gids en leer welke crypto nu kopen verstandig kan zijn! Welke crypto nu kopen? Fed-voorzitter Jerome Powell heeft aangekondigd dat de rentes binnenkort zomaar eens omlaag zouden kunnen gaan, en tegelijkertijd blijft BlackRock volop crypto kopen, en dus lijkt de markt klaar om te gaan stijgen. Eén vraag komt telkens terug: welke crypto moet je nu kopen? In dit artikel bespreken we de munten die… Continue reading Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550 document.addEventListener('DOMContentLoaded', function() { var screenWidth = window.innerWidth; var excerpts = document.querySelectorAll('.lees-ook-description'); excerpts.forEach(function(description) { var excerpt = description.getAttribute('data-description'); var wordLimit = screenWidth wordLimit) { var trimmedDescription = excerpt.split(' ').slice(0, wordLimit).join(' ') + '...'; description.textContent = trimmedDescription; } }); }); Technische indicatoren schetsen herstelkans voor ETH Naast de dubbele koopsignalen verstrekken ook andere indicatoren belangrijke aanwijzingen. Tijdens de daling van de ETH koers waren grote rode candles zichtbaar, maar na de test van $4.516 stabiliseerde de Ethereum koers. Dit wijst op een mogelijke verschuiving in het evenwicht tussen de bears en bulls. Als deze opwaartse beweging doorzet, liggen de eerste weerstanden rond $4.550. Daarboven wacht een sterkere zone rond $4.650. Deze niveaus zijn in eerdere Ethereum sessies al meerdere keren getest. Een doorbraak zou ruimte openen richting de all-time high van ETH rond $4.953. Wanneer de prijs toch opnieuw onder $4.516 zakt, liggen er zones rond $4.500 en $4.450 waar grotere kooporders worden verwacht. Deze niveaus kunnen als een vangnet fungeren, mocht de druk opnieuw toenemen. Marktdynamiek bevestigt technische indicatoren De huidige situatie volgt op een bredere correctie in de cryptomarkt. Verschillende vooraanstaande crypto tokens zagen scherpe koersdalingen, waarna traders op zoek gingen naar signalen voor een mogelijke ommekeer. Dat juist Ethereum nu een dubbel TD Sequential signaal toont, versterkt de interesse in dit scenario. Fundamenteel blijft Ethereum sterk. Het aantal ETH tokens dat via staking is vastgezet, blijft groeien. Dat verkleint de vrije circulatie en vermindert verkoopdruk. Tegelijk blijft het netwerk intensief gebruikt voor DeFi, NFT’s en stablecoins. Deze activiteiten zorgen voor een stabiele vraag naar ETH, ook wanneer de prijs tijdelijk onder druk staat. Fundamentele drijfveren achter de Ethereum koers De Ethereum koers wordt echter niet alleen bepaald door candles en patronen, maar ook door bredere factoren. Een stijgend percentage van de totale ETH supply staat vast in staking contracten. Hierdoor neemt de liquiditeit op exchanges af. Dit kan prijsschommelingen versterken wanneer er plotseling meer koopdruk ontstaat. Daarnaast is Ethereum nog steeds het grootste smart contract platform. Nieuwe standaarden zoals ERC-8004 en ontwikkelingen rond layer-2 oplossingen houden de activiteit hoog. Deze technologische vooruitgang kan de waardepropositie ondersteunen en zo indirect bijdragen aan een ETH prijsherstel. Het belang van de korte termijn dynamiek De komende handelsdagen zullen duidelijk maken of de bulls genoeg kracht hebben om door de weerstandszone rond $4.550 te breken. Voor de bears ligt de focus juist op het verdedigen van de prijsregio rond $4.516. De whales, die met grote handelsorders opereren, kunnen hierin een beslissende rol spelen. Het dubbele TD Sequential signaal blijft hoe dan ook een zeldzame gebeurtenis. Voor cryptoanalisten vormt het een objectief aanknopingspunt om de kracht van de huidige Ethereum trend te toetsen. Vooruitblik op de ETH koers Ethereum liet twee opeenvolgende TD Sequential signalen zien op de uurgrafiek, iets wat zelden voorkomt. Deze formatie viel samen met steun rond $4.516, waar de bulls actief werden. Als de Ethereum koers boven dit niveau blijft, kan er ruimte ontstaan richting $4.550 en mogelijk $4.650. Zakt de prijs toch opnieuw onder $4.516, dan komen $4.500 en $4.450 in beeld als nieuwe steunzones. De combinatie van zeldzame indicatoren en een sterke fundamentele basis maakt Ethereum interessant voor zowel technische als fundamentele analyses. Of de bulls het momentum echt kunnen overnemen, zal blijken zodra de Ethereum koers de eerstvolgende weerstanden opnieuw test. Koop je crypto via Best Wallet Best wallet is een topklasse crypto wallet waarmee je anoniem crypto kan kopen. Met meer dan 60 chains gesupport kan je al je main crypto coins aanschaffen via Best Wallet. Best wallet - betrouwbare en anonieme wallet Best wallet - betrouwbare en anonieme wallet Meer dan 60 chains beschikbaar voor alle crypto Vroege toegang tot nieuwe projecten Hoge staking belongingen Lage transactiekosten Best wallet review Koop nu via Best Wallet Let op: cryptocurrency is een zeer volatiele en ongereguleerde investering. Doe je eigen onderzoek. Het bericht Ethereum koers toont zeldzaam dubbel koopsignaal en richt zich op $4.550 is geschreven door Dirk van Haaster en verscheen als eerst op Bitcoinmagazine.nl.
Share
Coinstats2025/09/17 23:31