Skip to main content

Three Important Patterns for Building Microservices

 In this post, we will look at three important patterns that can help you create microservices.

Event Sourcing

Event sourcing tries to solve the problem around atomically updating the database and also publishing an event.

What this means is that when you do something on a Domain Entity, it can be treated like a Domain Event. And the state of the Domain Entity is stored as a sequence of these Domain Events. In other words, a new event is created whenever a new record is inserted or something is updated on an existing record. An event store keeps track of all the events occuring on the entity.

Now, let's assume the following transactions occur on a particular account:

  • Creation of the account with an initial balance of $100 USD.
  • Account set to ACTIVE status.
  • A friend paid some money back for sharing a meal. Deposit of $55 USD in the account.
  • You bought ice cream for your significant other. Withdrawal of $20 USD.
  • Your significant other didn't like the ice cream and so you had to buy another one. Withdrawal of $50 USD.
  • You forgot to pay the rent. Your landlord imposed a penalty. Withdrawal of $100 USD.
  • Account set to HOLD status because of a negative balance.
  • Deposit $100 USD to the account. Breath a sigh of relief.
  • Account set to ACTIVE status.

Below is how it will be stored in an event sourcing way:

Aggregate_IdEventEvent Payload
ABCD567823AccountActivatedEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823AccountHeldEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823AccountActivatedEvent{…}
ABCD567823AccountBalanceUpdatedEvent{…}
ABCD567823

AccountCreatedEvent    

Whenever there is a request for the current state of the domain object, the events are replayed and the state is constructed.

Event Sourcing implementation can be done using a combination of standard Java frameworks such as Spring Boot and Axon.

CQRS 

CQRS stands for Command-Query Responsibility Segregation. Often, CQRS is implemented in conjunction with Event Sourcing.

The main use of CQRS is to get around the problem arising from API Composition.

In a typical Event Sourcing and CQRS setup, a CQRS application listens to domain events from multiple applications. Using these updates, it creates and maintains a query database. Depending on the business case, this query database can aggregate complex queries and serve them whenever a request for such queries comes up in the application.

Saga Pattern

Saga Pattern is a direct solution to implementing distributed transactions in a microservices architecture. 

Typically, in a microservice based application, each microservice will have its own database. However, certain business processes will require communication between multiple microservices. That's where Saga Pattern comes in. A typical Saga implementation can be seen as a sequence of local transactions where each transaction does a small part of the overall work of the Saga. In other words, a Saga Pattern is pretty much a necessity in a microservices architecture.

Let's see a simple example in a typical food delivery app flow.

When a user places an order, the sequence of actions that could happen are:

  • The food ordering service creates an order. At this point, the order is in a PENDING state. A saga manages the chain of events.
  • The saga contacts the restaurant via the restaurant service.
  • The restaurant service attempts to place the order with the chosen restaurant. After getting a confirmation, it sends back a reply.
  • The saga receives the reply. And, depending on the reply, it can approve the order or reject the order.
  • The food order service then changes the state of the order. If the order was approved, it would inform the customer and provide any necessary details. If rejected, it will also inform the customer with an apology message.

Sagas can also be of different types such as choreography-based or orchestration-based. An orchestration-based Saga can be implemented by using the Spring Boot and Axon frameworks.

Comments

Popular posts from this blog

Apache Spark Discretized Streams (DStreams) with Pyspark

Apache Spark Discretized Streams (DStreams) with Pyspark SPARK STREAMING What is Streaming ? Try to imagine this; in every single second , nearly 9,000 tweets are sent , 1000 photos are uploaded on instagram, over 2,000,000 emails are sent and again nearly 80,000 searches are performed according to Internet Live Stats. So many data is generated without stopping from many sources and sent to another sources simultaneously in small packages. Many applications also generate consistently-updated data like sensors used in robotics, vehicles and many other industrial and electronical devices stream data for monitoring the progress and the performance. That’s why great numbers of generated data in every second have to be processed and analyzed rapidly in real time which means “ Streaming ”. DStreams Spark DStream (Discretized Stream) is the basic concept of Spark Streaming. DStream is a continuous stream of data.The data stream receives input from different kind of sources like Kafka, Kinesis...

6 Rules of Thumb for MongoDB Schema Design

“I have lots of experience with SQL and normalized databases, but I’m just a beginner with MongoDB. How do I model a one-to-N relationship?” This is one of the more common questions I get from users attending MongoDB office hours. I don’t have a short answer to this question, because there isn’t just one way, there’s a whole rainbow’s worth of ways. MongoDB has a rich and nuanced vocabulary for expressing what, in SQL, gets flattened into the term “One-to-N.” Let me take you on a tour of your choices in modeling One-to-N relationships. There’s so much to talk about here, In this post, I’ll talk about the three basic ways to model One-to-N relationships. I’ll also cover more sophisticated schema designs, including denormalization and two-way referencing. And I’ll review the entire rainbow of choices, and give you some suggestions for choosing among the thousands (really, thousands) of choices that you may consider when modeling a single One-to-N relationship. Jump the end of the post ...

Khác nhau giữa các chế độ triển khai giữa Local, Standalone và YARN trong Spark

Trong Apache Spark, có ba chế độ triển khai chính: Local, Standalone và YARN. Dưới đây là sự khác biệt giữa chúng: Chế độ triển khai Local: Chế độ triển khai Local là chế độ đơn giản nhất và được sử dụng cho môi trường phát triển và kiểm thử. Khi chạy trong chế độ Local, Spark sẽ chạy trên một máy tính duy nhất bằng cách sử dụng tất cả các luồng CPU có sẵn trên máy đó. Đây là chế độ phù hợp cho các tác vụ nhỏ và không yêu cầu phân tán dữ liệu. Chế độ triển khai Standalone: Chế độ triển khai Standalone cho phép bạn triển khai một cụm Spark độc lập bao gồm nhiều máy tính. Trong chế độ này, một máy tính được chọn làm "Spark Master" và các máy tính khác được kết nối với Spark Master như là "Spark Workers". Spark Master quản lý việc phân phối công việc và quản lý tài nguyên giữa các Spark Workers. Chế độ Standalone phù hợp cho triển khai Spark trên các cụm máy tính riêng lẻ mà không có hệ thống quản lý cụm chuyên dụng. Chế độ triển khai YARN: YARN (Yet Another Resource N...