Idempotency in microsservices and REST APIs
Applications based on the Devprime platform already have an automatic idempotency feature, protecting services from duplicate inclusions.
In this scenario we will use a mandatory key sent by the application that is using the API. To use the feature, simply change the settings in the Devprime-based microservice.
Creating a microservice to use in the example
We will use a microservice based on the Devprime platform
- Use an active account on Devprime and activate the Devprime CLI.
- Start the containers from docker (MongoDB, RabbitMQ and Redis)
- Create the orderevents queue in RabbitMQ.
- Create a new microservice “order”.
Starting the idempotency configuration
Setting the idempotency in the “Devprime_App” key
Change the Idempotency configuration to “Enabled” to “true” and “Flow” to “frontend”. We changed the “key” to “my-idempotency-key”. With this configuration, the API will require the idempotency key in the Headar.
code .\src\app\appsettings.json
|
|
Include a second persistence in the “Devprime_State” key
In this example we will use a local Redis with a default password
code .\src\app\appsettings.json
|
|
Starting automatic idempotency in the microservice
Now it’s time to test the setup. Before you start the microservice, make sure that you have activated the containers and created the queue in RabbitMQ.
Run the application and make a post via the Order API
We need to pass the idempotency key through Head in this scenario so you need to consume the API using curl, podtman, insomnia and many others.
Starting the microservice configured to use an idempotency key
`
Sample json code for use in the API. Modify it in your tests.
|
|
In the first test we will not pass the idempotency key in POST as per example performed in Postman.
When looking at the API return, we will have a denial of the request due to the absence of the key, which in the configuration with the “Flow” of the type “Backend” is mandatory and must be passed through the Header.
Now let’s add our key “my-idempotency-key” and a guid value.
After confirming the post in the previous step, the Log already registers success in the idempotency process.
When trying to make a new Post with the same previous key, the duplicate command is already automatically denied.
In this article, you noted how easy it is to implement the idempotency feature in microservices development with the Devprime platform.
You have at your disposal additional settings such as “Action” that configured as “manual” requires you to activate in a specific method and/or “Scope” that can limit the performance on an Adapter such as “Web” or “Stream”
More articles on idempotency
Implementing idempotency in microsservices
Building an idempotent event-driven microservices