DEV Community

spO0q
spO0q

Posted on

Idempotency and API design

It's easy to build REST APIs that break the principle of idempotency.

It happens when identical requests produce different outcomes.

Let's explain it with simple words and concrete examples.

When does idempotency make sense?

Idempotency does not make sense for create (HTTP POST) requests, as the idea is to create new resource every time.

Likewise, if your API increments a counter, then it's logic to modify the result beyond the initial operation.

However, if you update some field (e.g., user infos), your request will modify the resource, but further identical requests should not alter the result of the first one.

HTTP DELETE requests are idempotent by definition. Once the resource is deleted, identical requests will result in 404 errors.

Idempotent API design and retry strategies

It's not uncommon to implement retry mechanisms when consuming APIs.

In such case, it's critical that the same operation does not occur twice, especially when it involves payments, but not only.

As we saw earlier, it's quite easy to understand why some HTTP verbs are said to be idempotent or non-idempotent, but some operations can be very tricky.

Failures and edge case happen all the time (e.g., network failures). How do you ensure an operation is invoked exactly once?

For example, you don't want customers to be charge twice accidentally.

Worse, if your API design is flawed, the code that consumes your API, and ultimately the end-user, might not even know what's happening until the user gets actually charged.

The user might also think the payment succeeded while it failed.

Both situations are terrible for the business.

Stripe uses specific headers and strategies to address this problem.

Wrap this up

Idempotency is a critical concept for your API.

This concept is a common concern in computer science you need to know as a developer.

Useful links

Top comments (0)