5 Transactions and queries in microservices

 

This chapter covers

  • The challenges of consistency in a distributed application
  • Synchronous and asynchronous communication
  • Using sagas to develop business logic across multiple services
  • API composition and CQRS for microservice queries

Many monolithic applications rely on transactions to guarantee consistency and isolation when changing application state. Obtaining these properties is straightforward: an application typically interacts with a single database, with strong consistency guarantees, using frameworks that provide support for starting, committing, or rolling back transactional operations. Each logical transaction might involve several distinct entities; for example, placing an order will update transactions, reserve stock positions, and charge fees.

You’re not so lucky in a microservice application. As you learned earlier, each independent service is responsible for a specific capability. Data ownership is decentralized, ensuring a single owner for each “source of truth.” This level of decoupling helps you gain autonomy, but you sacrifice some of the safety you were previously afforded, making consistency an application-level problem. Decentralized data ownership also makes retrieving data more complex. Queries that previously used database-level joins now require calls to multiple services. This is acceptable for some use cases but painful for large data sets.

5.1 Consistent transactions in distributed applications

5.1.1 Why can’t you use distributed transactions?

5.2 Event-based communication

5.2.1 Events and choreography

5.3 Sagas

5.3.1 Choreographed sagas

5.3.2 Orchestrated sagas

5.3.3 Interwoven sagas

5.3.4 Consistency patterns

5.3.5 Event sourcing

5.4 Queries in a distributed world

5.4.1 Storing copies of data

5.4.2 Separating queries and commands

5.4.3 CQRS challenges

5.4.4 Analytics and reporting

5.5 Further reading

Summary