What is idempotency?
If you look up idempotency on Wikipedia, it looks a lot more confusing than it really is. There is the academic mathematic definition, then there is a more practical definition when working with APIs and memory management: "An API call or operation is idempotent if it has the same result no matter how many times it is applied" (source).
A good example of an operation requiring idempotency is a PAY NOW button in a shopping website. It is basically making a POST request, a non-idempotent request type, so what happens if the user kept clicking PAY NOW? An idempotency key keeps this POST request a unique, one-time operation, no matter how many times an impatient customer mashes the PAY NOW button.
I still don't understand! What's a simple explanation of idempotency?
Think of what happens when you press an elevator button. Your button press sends a signal to the elevator's computer to dispatch the elevator to that floor- let's say, the third floor. Now, you can press the third floor button multiple times, but it won't make the elevator go faster, or cancel the request, or make the elevator visit the third floor more than once. The request "send elevator to the third floor" is idempotent.
What HTTP Requests are Idempotent?
- GET requests are idempotent, because they are just retrieving data from a server.
- POST requests are non-idempotent, because it will create a new resource as many times as you issue a POST request.
- PUT requests are idempotent, because they update a resource. Even if the same request was issued multiple times, it would PUT the same resource in the same place.
- PATCH requests are non-idempotent, because they don't have to be idempotent, though the operations themselves can be idempotent.
- DELETE requests are idempotent. When a resource is deleted, it can't be deleted again.
Idempotency requires you to think like a developer. It's not just a matter of making your application function, it's a matter of choosing the best tool for the job that will use your resources efficiently and not frustrate your customers.