0
0
MicroservicesConceptIntermediate · 4 min read

What Is Distributed Transaction in Microservices: Explained Simply

A distributed transaction is a process that ensures multiple separate systems or services complete a set of operations together as one unit. It guarantees that either all parts succeed or all fail, keeping data consistent across different microservices.
⚙️

How It Works

Imagine you want to buy a product online. One service handles your payment, another updates the stock, and a third sends the shipping details. A distributed transaction makes sure all these steps happen together. If payment succeeds but stock update fails, the system rolls back the payment to avoid errors.

This works by coordinating all involved services to either commit their changes or undo them. Common methods include a two-phase commit, where a coordinator asks each service if it can commit, then tells all to commit or rollback based on responses. This coordination keeps data consistent even though services run independently.

💻

Example

This example shows a simple two-phase commit simulation using Python to coordinate two services updating their state together.
python
class Service:
    def __init__(self, name):
        self.name = name
        self.prepared = False
        self.committed = False

    def prepare(self):
        print(f"{self.name}: Preparing transaction")
        self.prepared = True
        return True

    def commit(self):
        if self.prepared:
            print(f"{self.name}: Committing transaction")
            self.committed = True
        else:
            print(f"{self.name}: Cannot commit, not prepared")

    def rollback(self):
        print(f"{self.name}: Rolling back transaction")
        self.prepared = False
        self.committed = False

class Coordinator:
    def __init__(self, services):
        self.services = services

    def execute_transaction(self):
        # Phase 1: Prepare
        for service in self.services:
            if not service.prepare():
                self.rollback_all()
                return
        # Phase 2: Commit
        for service in self.services:
            service.commit()

    def rollback_all(self):
        for service in self.services:
            service.rollback()

# Usage
service1 = Service("PaymentService")
service2 = Service("InventoryService")
coordinator = Coordinator([service1, service2])
coordinator.execute_transaction()
Output
PaymentService: Preparing transaction InventoryService: Preparing transaction PaymentService: Committing transaction InventoryService: Committing transaction
🎯

When to Use

Use distributed transactions when you need strong consistency across multiple microservices that each manage their own data. For example, in banking systems where money transfer involves debiting one account and crediting another, or in e-commerce where payment and inventory updates must both succeed.

However, distributed transactions can add complexity and slow down systems. For many microservices, eventual consistency with compensation patterns is preferred unless strict atomicity is required.

Key Points

  • Distributed transactions coordinate multiple services to act as one unit.
  • They use protocols like two-phase commit to ensure all-or-nothing changes.
  • They help keep data consistent across microservices.
  • They add complexity and can impact performance.
  • Use them only when strong consistency is essential.

Key Takeaways

Distributed transactions ensure multiple services succeed or fail together to keep data consistent.
They use coordination protocols like two-phase commit to manage changes across services.
Use distributed transactions when strong atomicity is critical, such as in financial or inventory systems.
They add complexity and can slow down your system, so consider alternatives if possible.
Understanding when and how to use distributed transactions helps design reliable microservices.