JP Antunes

Posted on

# Idempotent vs Deterministic

Since I had to look it up more than once, here's a small reminder of the differences between the two concepts.

``````//f(x) + f(x) == 2 * f(x) for all x
const addTwo = (x, y) => x + y;
``````

This is a deterministic or pure function, the same input always returns the same output

``````//f(x) == f(f(x)) for all x
let someExternalState = 'off';
const activate = () => someExternalState = 'on';
``````

This is an idempotent function, calling it once or many times in a row produces the same side effect

Nicola Apicella

It's worth pointing out that what you wrote is the math definition of idempotency, which is different from the computer science definition. In CS when someone says that a call to a server is idempotent, it means that performing the call with the same parameters multiple times will produce the same result.

Assume you have an e-commerce service and want to place an order. You call the service one time to place the order and get a successful result. Then, you call it a second time to place the same order.
If the call is idempotent (the service respects idempotency for order requests) then you will get a successful result like the first time, although the order was not placed a second time (hopefully!).
Same goes if you initially got an unsuccessful result - if you try again you get the same (unsuccessful) result and the order won't be placed.
Note also that the response you get in the first call and the one you get in the second one do not need to be completely identical - usually what's important is the status code and some parameters that depend on the application. All the other things, like headers, response id, even part or all the body might be different.

Idempotency is an important property of services because it allows the caller to safely retry the call. Getting back to the e-commerce example: say you make the call to place the order, but it times out. If the call is idempotent, you can safely retry. If it isn't, retrying the call might place a new order!

Hope it makes sense :)

JP Antunes

You know, recently I gave a pretty much word for word copy of your first paragraph as the answer to a ... pub quiz... and was informed that the math definition is the correct one and I have been using it wrong for a couple of years now :-/

Nicola Apicella

It depends on the context of the question. If you find idempotency in the documentation for a service, it does not mean f(x) = f (f (x))

What they mean instead is what happens when you call the api multiple times, for example:
docs.aws.amazon.com/AWSEC2/latest/...
docs.aws.amazon.com/amazondynamodb...
docs.aws.amazon.com/step-functions...

CS borrows terms from other disciplines, like Math, etc, for similar concepts. If someone asks you about the definition of a function, what would you answer? The math definition and the CS definition are different.