What is Idempotence and its usages in Microservices
In this tutorial, we are going to learn about Idempotence and its usages in Microservices.
Idempotence in Microservices
-
It is not a design pattern, Idempotence means that your function or service or microservice has to produce the same output for the same input.
- For example, if you write a function that gets two numbers and returns the sum of those two numbers and every time you pass 2,2 to that function, and it returns 4 but not 5 which means it is idempotent.
-
It is used to make microservices more resilient. So it’s related to the topic of resiliency in the microservices. And the reason we need it is that sometimes microservices are triggered by receiving messages from a message broker such as active MQ or Rabbit MQ or if you use AWS, you may have lambda microservices that are triggered by an SNS topic.
- So in that case, sometimes you receive a message twice. Especially if you have a lambda microservice in Amazon Web Services that received messages from SQS or Simple Queue service to make sure that we handle the duplicate message.
- Message broker may send a message more than once, and the microservice has to be programmed to handle duplicate messages, and the handling of duplicate messages is called Idempotence.
Idempotence Use Case in Microservices
This is important because, if you have a microservice that is responsible for charging the credit card bill of the user and the user receives the bill twice, then you are going to charge the credit card of that poor customer twice.
-
So we have to make sure that we handle the messages only once, and this is done by doing two things, i.e.,
- Every message must have a unique identifier so that you can find that message and update it as “handled this before”, or “not handled this before”.
- You can use something like Order ID as the unique identifier, or you can just produce a unique identifier every time you produce a message.
- Then you store that message in a database, normally in a NoSQL database.