๐๐ฒ๐๐ถ๐ด๐ป๐ถ๐ป๐ด ๐๐ฑ๐ฒ๐บ๐ฝ๐ผ๐๐ฒ๐ป๐ ๐๐ฃ๐๐
A user gets charged twice. This happens when your API lacks idempotency. Idempotency means the same request always produces the same result.
Use an idempotency key. The client sends a unique key in the header. Your server checks this key. If the server saw this key before, it returns the old response. It does not run the operation again.
Implementation tips:
- Store keys in a database.
- Use a unique constraint.
- Set a TTL.
- A 24 hour window works for most retries.
Choose your methods:
- GET, PUT, and DELETE are idempotent.
- POST needs a key.
- Use PUT for updates.
- Use version numbers for PATCH.
Handle retries on your server:
- Return a 409 Conflict or 429 Too Many Requests if processing is not finished.
- Tell clients to use exponential backoff.
Test your system:
- Simulate network retries.
- Test duplicate requests.
- Test concurrent requests.
- These tests stop data corruption.
Document the contract. Tell users which endpoints are idempotent. Explain how to make keys. List the response codes.
Source: https://dev.to/therizwansaleem/designing-idempotent-apis-why-it-matters-and-how-to-do-it-right-gf4