In modern microservice architectures, ensuring data consistency across distributed systems can be challenging, especially when dealing with long-running transactions. The Saga Pattern provides an effective solution by breaking down a transaction into a series of smaller, autonomous steps that either succeed or execute compensating actions in case of failure. This blog post focuses on implementing Saga patterns in Spring Boot to maintain data consistency in event-driven architectures, specifically through choreography-based and orchestration-based approaches. It provides detailed code examples, technical insights, and advanced error-handling techniques.
Introduction to Saga Patterns
Distributed transactions can be difficult to manage due to the decentralized nature of microservices. In traditional monolithic applications, ACID properties ensure data consistency, but in microservices, we need a different approach. The Saga pattern solves this problem by dividing a long-running transaction into smaller sub-transactions that are managed independently. Each sub-transaction publishes events to signal success or failure, with compensating transactions available in case of failure.
There are two main Saga patterns:
- Choreography-based Saga: Services communicate directly via events.
- Orchestration-based Saga: A central orchestrator coordinates the transaction.
Choreography-Based Saga Pattern in Spring Boot
In this approach, services react to events by performing local transactions and emitting further events based on the outcome. It’s a decentralized pattern where each microservice knows what to do based on incoming events.
Use Case: E-Commerce Order Process
We’ll take an e-commerce platform as an example where each step involves services for inventory adjustment, payment processing, and order confirmation.
Step 1: Inventory Microservice
// Event to trigger inventory adjustment
public class InventoryAdjustmentEvent {
private String orderId;
private String productId;
private int quantity;
// Getters and setters
}
// Kafka Listener for Inventory Adjustment
@Service
public class InventoryService {
@KafkaListener(topics = "inventory-topic")
public void adjustInventory(InventoryAdjustmentEvent event) {
boolean success = adjustProductInventory(event.getProductId(), event.getQuantity());
if (success) {
PaymentInitiationEvent paymentEvent = new PaymentInitiationEvent(event.getOrderId(), event.getProductId(), event.getQuantity());
kafkaTemplate.send("payment-topic", paymentEvent);
} else {
OrderCancellationEvent cancelEvent = new OrderCancellationEvent(event.getOrderId());
kafkaTemplate.send("order-cancel-topic", cancelEvent);
}
}
}Step 2: Payment Microservice
// Payment Event
public class PaymentInitiationEvent {
private String orderId;
private double amount;
// Getters and setters
}
// Payment Processing
@Service
public class PaymentService {
@KafkaListener(topics = "payment-topic")
public void processPayment(PaymentInitiationEvent event) {
boolean success = processPayment(event.getOrderId(), event.getAmount());
if (success) {
OrderConfirmationEvent confirmationEvent = new OrderConfirmationEvent(event.getOrderId());
kafkaTemplate.send("order-confirm-topic", confirmationEvent);
} else {
PaymentFailureEvent failureEvent = new PaymentFailureEvent(event.getOrderId());
kafkaTemplate.send("payment-failure-topic", failureEvent);
}
}
}Compensating Transactions in Choreography
If one of the steps in the transaction fails, compensating actions are performed to revert previous actions.
// Order Cancellation Listener
@Service
public class OrderCancellationService {
@KafkaListener(topics = "order-cancel-topic")
public void cancelOrder(OrderCancellationEvent event) {
updateOrderStatus(event.getOrderId(), "CANCELLED");
rollbackInventoryAdjustment(event.getOrderId());
}
}Orchestration-Based Saga Pattern in Spring Boot
In an orchestration-based Saga, a central Saga orchestrator coordinates the entire flow. The orchestrator sends commands to individual services and handles responses to ensure that either the whole transaction is successful or compensating actions are triggered.
Orchestrator Service
@Service
public class SagaOrchestrator {
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
public void startOrderSaga(OrderSagaRequest request) {
InventoryAdjustmentEvent event = new InventoryAdjustmentEvent(request.getOrderId(), request.getProductId(), request.getQuantity());
kafkaTemplate.send("inventory-topic", event);
}
@KafkaListener(topics = "inventory-response-topic")
public void handleInventoryResponse(InventoryResponseEvent event) {
if (event.isSuccess()) {
PaymentInitiationEvent paymentEvent = new PaymentInitiationEvent(event.getOrderId(), event.getAmount());
kafkaTemplate.send("payment-topic", paymentEvent);
} else {
OrderCancellationEvent cancelEvent = new OrderCancellationEvent(event.getOrderId());
kafkaTemplate.send("order-cancel-topic", cancelEvent);
}
}
}Inventory and Payment Services
The inventory and payment services now respond to commands from the orchestrator, ensuring centralized control.
// Inventory Adjustment
@Service
public class InventoryService {
@KafkaListener(topics = "inventory-topic")
public void adjustInventory(InventoryAdjustmentEvent event) {
boolean success = adjustProductInventory(event.getProductId(), event.getQuantity());
InventoryResponseEvent responseEvent = new InventoryResponseEvent(event.getOrderId(), success);
kafkaTemplate.send("inventory-response-topic", responseEvent);
}
}// Payment Processing
@Service
public class PaymentService {
@KafkaListener(topics = "payment-topic")
public void processPayment(PaymentInitiationEvent event) {
boolean success = processPayment(event.getOrderId(), event.getAmount());
PaymentResponseEvent responseEvent = new PaymentResponseEvent(event.getOrderId(), success);
kafkaTemplate.send("payment-response-topic", responseEvent);
}
}Error Handling and Failure Scenarios
Handling errors and failures is crucial in any distributed system. In both Choreography and Orchestration patterns, you need strategies for managing failures. Let’s dive into some common approaches:
1. Timeouts and Retries
In distributed transactions, failures can occur due to network issues, service downtime, or timeouts. Implementing retry mechanisms and timeouts is essential to handle transient failures.
// Retry Mechanism in Payment Service
@Service
public class PaymentService {
private static final int MAX_RETRIES = 3;
@Retryable(maxAttempts = MAX_RETRIES, backoff = @Backoff(delay = 2000))
public void processPaymentWithRetry(PaymentInitiationEvent event) {
boolean success = processPayment(event.getOrderId(), event.getAmount());
if (!success) throw new RuntimeException("Payment failed, retrying...");
}
}2. Idempotency
Idempotency ensures that compensating actions can be applied multiple times without adverse effects. For instance, cancelling an order multiple times should have the same result as cancelling it once.
// Idempotent Cancellation Logic
public void cancelOrder(String orderId) {
Order order = orderRepository.findById(orderId);
if (!"CANCELLED".equals(order.getStatus())) {
order.setStatus("CANCELLED");
orderRepository.save(order);
// Additional compensation logic...
}
}3. Compensating Transactions
If a service fails after partially completing its work, compensating transactions should be executed to rollback any changes. This is handled automatically by the Saga orchestrator or by emitting failure events in the choreography pattern.
// Compensating Transaction in Inventory Service
public void rollbackInventoryAdjustment(String orderId) {
InventoryRecord record = inventoryRepository.findByOrderId(orderId);
if (record != null) {
record.adjustQuantity(-record.getReservedQuantity());
inventoryRepository.save(record);
}
}The Saga pattern is a robust solution for managing data consistency in distributed, event-driven architectures. In this post, we explored how to implement both choreography-based and orchestration-based Sagas in Spring Boot using Kafka. By applying the right error-handling strategies like retries, idempotency, and compensating transactions, you can ensure that your system maintains consistency and reliability even in complex distributed environments.
With these patterns and examples, you now have the foundational knowledge to manage distributed transactions across microservices efficiently.
Subscribe to our email newsletter to get the latest posts delivered right to your email.

As I site possessor I believe the content matter here is rattling wonderful , appreciate it for your hard work. You should keep it up forever! Best of luck.
This design is incredible! You definitely know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!
I do agree with all the ideas you have presented in your post. They are very convincing and will certainly work. Nonetheless, the posts are too brief for newbies. May just you please extend them a bit from subsequent time? Thank you for the post.
I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from. appreciate it
Aw, this was a very nice post. In idea I want to put in writing like this moreover ? taking time and precise effort to make a very good article? however what can I say? I procrastinate alot and by no means seem to get something done.
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.com/el/register?ref=IQY5TET4
Thank you for sharing excellent informations. Your web-site is very cool. I’m impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found just the info I already searched everywhere and just couldn’t come across. What a great web-site.
Performance perfection achieved, outcomes justify the investment. Results-focused champions. Results delivered.
After examine just a few of the blog posts in your website now, and I actually like your method of blogging. I bookmarked it to my bookmark website list and might be checking again soon. Pls try my web page as well and let me know what you think.
Great web site. A lot of useful info here. I?m sending it to some friends ans also sharing in delicious. And naturally, thanks for your effort!
great issues altogether, you just won a logo new reader. What might you recommend in regards to your publish that you just made a few days ago? Any certain?
you have a great blog right here! would you like to make some invite posts on my weblog?
I?ve been exploring for a little bit for any high-quality articles or weblog posts on this kind of space . Exploring in Yahoo I eventually stumbled upon this site. Studying this info So i?m happy to express that I’ve an incredibly just right uncanny feeling I found out exactly what I needed. I most indisputably will make sure to do not overlook this site and give it a glance on a relentless basis.
Thank you for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.
affordablecanvaspaintings.com.au is Australia Popular Online 100 percent Handmade Art Store. We deliver Budget Handmade Canvas Paintings, Abstract Art, Oil Paintings, Artwork Sale, Acrylic Wall Art Paintings, Custom Art, Oil Portraits, Pet Paintings, Building Paintings etc. 1000+ Designs To Choose From, Highly Experienced Artists team, Up-to 50 percent OFF SALE and FREE Delivery Australia, Sydney, Melbourne, Brisbane, Adelaide, Hobart and all regional areas. We ship worldwide international locations. Order Online Your Handmade Art Today.
Hmm it looks like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any tips for novice blog writers? I’d definitely appreciate it.
Dry Cleaning in New York city by Sparkly Maid NYC
We are looking for partnerships with other businesses for mutual promotion. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://sparklymaidnyc.com
I’m usually to blogging and i actually admire your content. The article has really peaks my interest. I’m going to bookmark your site and hold checking for brand new information.
Hey there I am so grateful I found your blog page, I really found you by mistake, while I was researching on Digg for something else, Nonetheless I am here now and would just like to say thanks for a marvelous post and a all round exciting blog (I also love the theme/design), I don’t have time to browse it all at the minute but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.
We pay $10 for a google review and We are looking for partnerships with other businesses for Google Review Exchange. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://sparklymaidnyc.com
hello there and thank you for your information ? I have definitely picked up something new from right here. I did however expertise a few technical points using this site, since I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I am complaining, but slow loading instances times will often affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I am adding this RSS to my e-mail and could look out for much more of your respective intriguing content. Ensure that you update this again soon..
Hi! Would you mind if I share your blog with my facebook group? There’s a lot of folks that I think would really appreciate your content. Please let me know. Thank you
We pay $10 for a google review and We are looking for partnerships with other businesses for Google Review Exchange. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://sparklymaidnyc.com
Hey there! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the same niche. Your blog provided us useful information to work on. You have done a outstanding job!
I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this best doc.
We pay $10 for a google review and We are looking for partnerships with other businesses for Google Review Exchange. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://sparklymaidnyc.com
We pay $10 for a google review and We are looking for partnerships with other businesses for Google Review Exchange. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://maps.app.goo.gl/u9iJ9RnactaMEEie8
It’s the best time to make some plans for the future and it is time to be happy. I have read this post and if I could I want to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I want to read more things about it!
We pay $10 for a google review and We are looking for partnerships with other businesses for Google Review Exchange. Please contact us for more information!
Business Name: Sparkly Maid NYC Cleaning Services
Address: 447 Broadway 2nd floor #523, New York, NY 10013, United States
Phone Number: +1 646-585-3515
Website: https://maps.app.goo.gl/u9iJ9RnactaMEEie8
What?s Happening i’m new to this, I stumbled upon this I’ve found It absolutely useful and it has helped me out loads. I hope to contribute & aid other users like its helped me. Great job.
Wow, superb weblog structure! How lengthy have you been running a blog for? you made blogging glance easy. The full look of your web site is great, let alone the content material!
Its like you read my mind! You appear to understand a lot about this, such as you wrote the ebook in it or something. I believe that you could do with a few to drive the message house a little bit, but other than that, this is magnificent blog. A fantastic read. I’ll certainly be back.
I am curious to find out what blog system you are working with? I’m having some small security problems with my latest blog and I’d like to find something more risk-free. Do you have any solutions?
Now this is good content. You can tell that alot when into this post. Keep it up.
Hi! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Thank you for sharing!
I just added this blog to my feed reader, excellent stuff. Can’t get enough!
It?s exhausting to seek out educated folks on this topic, but you sound like you know what you?re speaking about! Thanks
I realized more a new challenge on this weight loss issue. One particular issue is a good nutrition is very vital if dieting. A massive reduction in bad foods, sugary food items, fried foods, sweet foods, beef, and white colored flour products could possibly be necessary. Keeping wastes parasitic organisms, and harmful toxins may prevent goals for losing belly fat. While specified drugs for the short term solve the condition, the horrible side effects are usually not worth it, plus they never provide more than a short-term solution. It is just a known fact that 95 of celebrity diets fail. Many thanks sharing your thinking on this weblog.
I think this is one of the such a lot important info for me. And i am happy studying your article. However want to commentary on few general issues, The web site taste is ideal, the articles is in point of fact great : D. Excellent process, cheers
I will also like to convey that most people who find themselves without having health insurance are normally students, self-employed and people who are laid-off. More than half from the uninsured are really under the age of Thirty-five. They do not feel they are needing health insurance because they are young as well as healthy. Its income is frequently spent on houses, food, as well as entertainment. Many people that do work either 100 or as a hobby are not made available insurance by means of their jobs so they get along without due to the rising expense of health insurance in the us. Thanks for the ideas you write about through this website.
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks!
http://www.factorytinsigns.com is 100 Trusted Global Metal Vintage Tin Signs Online Shop. We have been selling art and décor online worldwide since 2008. Started in Sydney, Australia. 2000+ Tin Beer Signs, Outdoor Metal Wall Art, Business Tin Signs, Vintage Metal Signs to choose from. 100 Premium Quality Artwork. Up-to 40 OFF Sale Store-wide. Fast Shipping USA, Canada, UK, Australia, New Zealand, Europe.
Thanks , I’ve just been searching for info about this topic for a long time and yours is the greatest I’ve discovered till now. But, what about the bottom line? Are you positive in regards to the source?
Hello there! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done a extraordinary job!|
http://www.arttree.com.au is Australia Popular Online Art Store. We sell Canvas Prints, Handmade Canvas Oil Paintings, Customer Artwork, Handmade Canvas Portraits. We Offer Year Round Sale and Get Up-to 70 Percent OFF Discount. We give FREE Delivery Australia, Sydney, Melbourne, Brisbane, Adelaide, Hobart and all regional areas. We ship Worldwide at many international locations.
http://www.arttree.com.au is Australia Popular Online Art Store. We sell Canvas Prints, Handmade Canvas Oil Paintings, Customer Artwork, Handmade Canvas Portraits. We Offer Year Round Sale and Get Up-to 70 Percent OFF Discount. We give FREE Delivery Australia, Sydney, Melbourne, Brisbane, Adelaide, Hobart and all regional areas. We ship Worldwide at many international locations.
Do you have a spam issue on this site; I also am a blogger, and I was wondering your situation; we have created some nice practices and we are looking to exchange solutions with others, please shoot me an e-mail if interested.|
I’ve been browsing online greater than 3 hours these days, yet I never discovered any fascinating article like yours. It’s lovely worth enough for me. In my opinion, if all website owners and bloggers made good content as you did, the internet will probably be much more useful than ever before.|
What’s up, this weekend is nice designed for me, as this occasion i am reading this fantastic educational paragraph here at my residence.|
Many thanks to you for sharing these kinds of wonderful discussions. In addition, the best travel along with medical insurance plan can often eliminate those considerations that come with vacationing abroad. Your medical crisis can soon become too expensive and that’s sure to quickly decide to put a financial impediment on the family’s finances. Putting in place the suitable travel insurance deal prior to leaving is worth the time and effort. Cheers
Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out a lot. I hope to give something back and help others like you helped me.|
Thanks for ones marvelous posting! I actually enjoyed reading it, you happen to be a great author.I will ensure that I bookmark your blog and will eventually come back in the foreseeable future. I want to encourage you to continue your great writing, have a nice morning!|
It’s going to be end of mine day, but before finish I am reading this wonderful piece of writing to increase my knowledge.|
Thanks for your article on this website. From my experience, often times softening upward a photograph may provide the professional photographer with a bit of an artistic flare. Oftentimes however, that soft blur isn’t just what you had in your mind and can often times spoil a normally good image, especially if you thinking about enlarging them.
I was curious if you ever considered changing the page layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two images. Maybe you could space it out better?
Hey there would you mind letting me know which hosting company you’re working with? I’ve loaded your blog in 3 completely different internet browsers and I must say this blog loads a lot quicker then most. Can you recommend a good hosting provider at a honest price? Kudos, I appreciate it!|
Heya i’m for the primary time here. I found this board and I find It really helpful & it helped me out much. I’m hoping to give something again and help others like you aided me.|
whoah this weblog is excellent i like studying your articles. Keep up the good work! You already know, lots of individuals are searching round for this info, you could aid them greatly. |
What i don’t realize is in reality how you’re no longer really a lot more neatly-liked than you might be now. You are very intelligent. You already know therefore significantly with regards to this topic, produced me in my view consider it from so many various angles. Its like men and women are not interested except it is something to do with Girl gaga! Your individual stuffs great. All the time care for it up!|
Hey! Someone in my Facebook group shared this site with us so I came to take a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Exceptional blog and great design and style.|
Hello mates, its wonderful piece of writing about cultureand completely defined, keep it up all the time.|
Heya! I’m at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the excellent work!
I just like the helpful information you provide in your articles. I’ll bookmark your weblog and take a look at again right here regularly. I am reasonably certain I will learn many new stuff right right here! Good luck for the next!|
I’m gone to convey my little brother, that he should also pay a quick visit this web site on regular basis to take updated from newest reports.|
Nice post. This wasn’t what I was looking for but I still enjoyed reading it.
I was wondering if you ever considered changing the layout of your site? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe you could space it out better?|
Hi there to all, as I am genuinely keen of reading this weblog’s post to be updated regularly. It includes pleasant data.|
That is really interesting, You’re an overly professional blogger. I’ve joined your feed and look forward to in search of extra of your wonderful post. Additionally, I’ve shared your site in my social networks!
I have viewed that sensible real estate agents all over the place are Promotion. They are knowing that it’s more than merely placing a sign in the front area. It’s really about building human relationships with these sellers who at some time will become purchasers. So, while you give your time and effort to helping these vendors go it alone : the “Law of Reciprocity” kicks in. Interesting blog post.
I have come across that right now, more and more people are now being attracted to digital cameras and the area of taking pictures. However, being photographer, you should first devote so much period deciding the exact model of camera to buy as well as moving from store to store just so you can buy the cheapest camera of the trademark you have decided to settle on. But it would not end at this time there. You also have to take into consideration whether you can purchase a digital dslr camera extended warranty. Thanks a bunch for the good guidelines I received from your site.
Howdy! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new updates.|
Unquestionably believe that that you said. Your favourite reason seemed to be on the net the easiest thing to understand of. I say to you, I certainly get annoyed whilst folks think about worries that they just do not understand about. You controlled to hit the nail upon the highest and also defined out the entire thing with no need side-effects , other people can take a signal. Will likely be again to get more. Thanks|