Tuesday, 28 November 2017

Idempotency and Idempotent Methods

Idempotence is the property of certain operations in mathematics and computer science that can be applied multiple times without changing the result beyond the initial application.

The term was introduced by Benjamin Peirce in the context of elements of algebras that remain invariant when raised to a positive integer power and literally means "(the quality of having) the same power", from idem + potence (same + power).

From a RESTful service standpoint, for an operation (or service call) to be idempotent, clients can make that same call repeatedly while producing the same result.

Idempotent Methods in Rest Service
GET, PUT, DELETE

Note: POST is not an idempotent method.

Two main categories of HTTP Methods
1. Safe
2. Idempotent.

Safe Methods in HTTP
These are HTTP methods which don't change the resource on the server side i.e. READ ONLY methods.

Example: GET or a HEAD are safe methods, however, POST (POST /books/), PUT (PUT /books/123), or DELETE are non-safe.

Idempotent Methods in HTTP
These are methods which are safe from multiple calls i.e. they produce the same result for multiple calls. They change the resource in Server every time you call them but the end result is always same.

Again, this only applies to the result, not the resource itself. This still can be manipulated (like an update-timestamp, provided this information is not shared in the (current) resource representation.

Example
int x = 10;
This assignment operation is idempotent, no matter how many times you execute this statement, x will always be 10

++x; It is not idempotent because every time it will return the different value of i. Since both examples are changing the value of i, both are non-safe methods.

HTTP Method
Idempotent
Safe
OPTIONS
yes
yes
GET
yes
yes
HEAD
yes
yes
PUT
yes
no
POST
no
no
DELETE
yes
no
PATCH
no
no

Idempotency is one of the important reasons to prefer the PUT method over POST to update any resource in REST service.

The problem with the POST method
Suppose a client wants to update a resource through POST. Since POST is not an idempotent method, calling it multiple times may result in incorrect updates.

Let us suppose that our POST request may timeout, what will happen to the resource that. Is the resource actually updated or does the timeout happen during sending the request to the server, or the response to the client? Can we safely retry again, or do we need to figure out first what has happened to the resource?

By using idempotent methods like PUT, you don't have to answer this question, but we can safely resend the request until we actually get a response back from the server.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...