Idempotency in microsserviços and REST APIs
Applications based on the Devprime platform already have an automatic idempotency feature, protecting services to avoid duplicate inclusions.
In this scenario, we’ll use an encryption key sent by the application 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 in Devprime and enable the Devprime CLI.
- Launch the containers from docker (MongoDB, RabbitMQ, and Redis)
- Create the orderevents queue in RabbitMQ.
- Create a new order microservice.
Starting the idempotency setup
Setting idempotency on the “Devprime_App” switch
Change the Idempotency setting to “Enabled” to “true” and the “Flow” to “frontend”. We changed the “key” to “my-idempotency-key”. With this configuration, the API will require the idempotency key in Headar.
code .\src\app\appsettings.json
|
|
Include a second persistence in the “Devprime_State” key
In this example, we’ll 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 configuration. Before you start the microservice, make sure that you have enabled the containers and created the queue in RabbitMQ.
Run the application and 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
`
A sample json code for use in the API. Modify in your tests.
|
|
In the first test, we won’t pass the idempotency key in POST, as in the example in Postman.
When looking at the return of the API we will have a negative request due to the absence of the key that in the configuration with the “Flow” of 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 developed with the Devprime platform.
You have at your disposal additional settings such as “Action” which configured as “Manual” requires you to activate in a specific method and/or “Scope” which can limit the action on an Adapter such as “Web” or “Stream”
More articles on idempotency
Implementing idempotency in microservices
Building an idempotent event-driven microservices