Ensuring your mint and redeem requests are only executed once

In the world of APIs, ensuring data integrity and consistency is paramount. When it comes to making requests that modify or create resources, developers often face a challenge: how to handle situations where requests are retried, leading to unintended duplicate operations. This is where the concept of idempotent requests and the Idempotency-Key header come into play.

What are Idempotent Requests?

An idempotent request is an operation that can be repeated multiple times without changing the result after the first successful execution. In other words, no matter how many times you send the same request, the outcome remains consistent. Idempotent requests are crucial for maintaining data accuracy, especially in scenarios where network issues or timeouts can cause clients to send duplicate requests inadvertently.

The Idempotency-Key Header

To facilitate idempotent requests, APIs often rely on the Idempotency-Key header. When making a request that modifies or creates a resource, developers must include a unique key in the Idempotency-Key header. This key serves as a token to identify the specific operation. Brale's implementation follows the IETF draft, which includes some of the following:

  • All POST requests require a Idempotency-Key HTTP header
    • A 400 BadRequest error will be returned otherwise
  • Idempotency-Key value must be unique and must not be reused
    • Concurrent requests with the same value will return a 409 Conflict error
    • Sequential requests with the same value, but different bodies will return a 422 UnprocessableEntity error
  • First-time requests must be processed normally, and the response cached
  • Duplicate requests must return the cached response, including status code
  • The cached responses expire after 24 hours

Including the Header

Before sending the request, generate a unique identifier for the operation. This could be a UUID, a timestamp, or any other unique string that can be used to identify the request.

Add the generated key to the Idempotency-Key header in the HTTP request.

curl --request POST \
  --url https://api.brale.xyz/deployments/:id/mints \
  --header 'Content-Type: application/vnd.api+json' \
  --header 'Idempotency-Key: 097ed2a8-fc45-45a5-9c9c-00a7a99a10fa' \
  --data '{...}'