Idempotency in microservices and REST APIs
Applications on the DevPrime platform already have an automatic Idempotency feature protecting services so that duplicate inclusions do not occur.
In this scenario we will use an obritatory 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 the DevPrime and activate the DevPrime CLI.
- Start containers through Docker (MongoDB, RabbitMQ and Redis)
- Create the orderevents queue in RabbitMQ.
- Create a new microservice “order”.
Starting Idempotency setup
Setting the idempotency in the “DevPrime_App” key
Change the Idempotency setting in the “Enabled” option to “true” and “Flow” to “frontend”. We changed the “key” to “my-idempotency-key”. With this setting the API will require the Idempotency key in Headar.
Include a second persistence in the “DevPrime_State” key
In this example we will use a local Redis with a default password
Initiating automatic Idempotency in the microservice
Now it’s time to test the configuration. Before starting the microservice make sure that you have activated the containers and created the queue in RabbitMQ.
Run the app and post the Order API
We need to pass this scenario the Idempotency key by Head so you need to consume the API using curl, podtman, insomnia and many others.
Starting the microservice configured to use an Idempotency key
A sample json code for use in the API. Modify your tests.
In the first test we will not pass the idempotência key in the POST as an example performed in Postman.
When looking at the API returns we will have a request negative by the absence of the key that in the configuration with the “Flow” type “Backend” is mandatory and must be passed by header.
Now let’s add our “my-idempotency-key” key and a guid value.
After confirming the post in the previous step the Log already records success in the idempotência process.
When you try to perform 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 additional settings such as “Action” that configured as “manual” require you to activate on a specific method and/or “Scope” that can limit the performance on an Adapter such as “Web” or “Stream”