DEV Community

Pratik Ambani
Pratik Ambani

Posted on

Explain idempotency (in REST) like I'm Five

Top comments (8)

Collapse
 
andrewbenton profile image
Andrew Benton

Ask someone to turn a switch on, they do, and the switch is on.

Ask them to turn it on again and your command has no effect.

That's idempotency.

Collapse
 
kayis profile image
K

Idempotency just means, calling the same function/endpoint multiple times, with the same arguments, will result in the same state.

if you write an endpoint like /player/increaseScoreByOne it will change the state as often as you call it.

if you write an endpoint like /player/setScoreTo?value=100 it will always result in the same state.

When your request doesn't get through, you can safely make it again without worrying about an inconsistent server state.

Not for 5 year olds, but I hope it helps xD

Collapse
 
pratikaambani profile image
Pratik Ambani

First of all, thank you for answering.

Considering your reply,
Idempotent: GET, TRACE, OPTIONS
Non-Idempotent: DELETE

Where do I place DELETE and PUT, and why?

Collapse
 
kayis profile image
K • Edited

You have to think about one action when thinking about idempotency.

If you call DELETE 100 times, it will still be the same item that is deleted, you remove it from memory, the DB or set a field deleted = true or something. Same goes for PUT, you send an update to the server, but you "set" state to a new state, you don't do stuff like "increase value x", "append string to y" or "subtract 10 from z".

Sure the data will be gone for your next GET request if you issued 1 or 100 DELETEs, but the idea is that the 100 DELETEs end in the same state as the 1 DELETEs

Thread Thread
 
pratikaambani profile image
Pratik Ambani

Gotcha!! Thanks buddy :)

Collapse
 
lpasqualis profile image
Lorenzo Pasqualis

The 5-year-old explanation could be:

You can go to your parents and ask the same thing, in the same way, any number of times.
If nothing else changes, the act of asking something over and over will not change the answer. They won't even get annoyed.

:)

Collapse
 
alainvanhout profile image
Alain Van Hout

Very nice metaphor. Perhaps a small addition: You can go to your parents and ask the same thing, in the same way, any number of times. If you’re sure they were listening at least once, then you can be sure that they will take care of whatever it is you asked.

Notably, the same might also be true for non-idempotent verbs; the difference is that there you don’t have the guarantee that it will always behave idempotently.

Collapse
 
machkernel profile image
David Stancu

A great example of an idempotent function is the absolute value function. abs(-4) = 4 abs(4) = 4. Continuing to apply abs() onto itself will always yield the same result.

For those that have done some Elixir before: -4 |> abs |> abs |> ... will always yield 4