DEV Community

ritaCosta93
ritaCosta93

Posted on

The Saga Pattern in Microservices

What are Microservices?

Micrososervices is a way to design software as a suite of independently deployable services.

Usually around a business capability.

Monolit

  • A single application when you have different modules that can do different things.
  • Everything in a single system storing to a common database.

Microservices

  • Each module is a different service.
  • Each module has a different database.
  • An action triggers on service at the time

Example

Buying something

Buy(UI) → Payment → Inventory → Shipping → Recommendation

The Saga Pattern

ACID Transaction

Atomic Consistent Isolated Durable

In the saga pattern, you have execute a kind of transaction in difference services, each service executes one transaction to make it look like it's only one transaction.

Transaction 1

Transaction 2

Transaction 3

Service 1

Service 2

Service 3

Db 1

Db 2

Db 3

And if there is a failure in a transaction, you try to compensate it with another action.

  • Orchestration
    • You have a central service that takes care of calling all the different services in the right order, and makes sure if there is a failure it knows how to compensate an action between the servers that are already called.
    • When you call a server, you expect a response, before calling the next one
    • This can be optimized using asyncronous communication
    • It always needs the confirmation from the central service
    • Implementing this method is recommended when you have complex workflows
  • Coreography
    • A central server that makes sure that all the things connect together, but the communication between services happens via events, it would react to the events and decides what to do if it works or if it doesn't work.
    • Just the server that subscribed to the event, will decided what to do
    • Not expecting a response, just send an event and someone else will consume that event
    • And if another server needs to do compensation actions, it will read from that event and execute it
    • Implementing this method is recommended when you have simple workflows

Discussion (0)