What is idempotent operation

Idempotent, in programming and mathematics, is a property of some operations such that no matter how many times you execute them, you achieve the same result.

In programming, idempotent can be a property of many different code elements, including functions, methods, requests and statements. Idempotent is a language-agnostic property: It means the same thing in any programming context.

Here’s a simple demonstration of idempotent in HTTP requests:

HTTP GET requests are a method of retrieving specified data from a source, such as getting a bank account balance. GET requests are idempotent: Accessing the same data should always be consistent. On the other hand, POST requests are designed to change the target, such as adding a sum to a bank account. As such, a POST request should change the result and that means it’s not idempotent.


In computing, an idempotent operation is one that has no additional effect if it is called more than once with the same input parameters. For example, removing an item from a set can be considered an idempotent operation on the set.

In mathematics, an idempotent operation is one where f(f(x)) = f(x). For example, the abs() function is idempotent because abs(abs(x)) = abs(x) for all x.

These slightly different definitions can be reconciled by considering that x in the mathematical definition represents the state of an object, and f is an operation that may mutate that object. For example, consider the Python set and its discard method. The discard method removes an element from a set, and does nothing if the element does not exist. So:

my_set.discard(x)

has exactly the same effect as doing the same operation twice:

my_set.discard(x)

my_set.discard(x)

Idempotent operations are often used in the design of network protocols, where a request to perform an operation is guaranteed to happen at least once, but might also happen more than once. If the operation is idempotent, then there is no harm in performing the operation two or more times.


Let me give an example from a database operation perspective.

Let us say the current salary of an employee is Rs. 60,000 and it is required to set his new salary to Rs. 65,000. That means increment of Rs.5,000.

Nature Query
Idempotent update employees set salary = 65000 where employee_id = 98;
Non Idempotent update employees set salary = salary + 5000 where employee_id = 98;

It is safe to retry the first query but not second. In second case the salary will increase by 5000 every time you execute the query.

This is just an example. It is preferred to form idempotent INSERT, UPDATE and DELETE database queries so that they can be retried without additional worries.

Comments

Back To Top

Popular posts from this blog

error 18 at 0 depth lookup: self signed certificate

How to check fragmentation in MySQL tables

How to Drop or Remove or Decommission a Database in Oracle