Idempotent Coding

Idempotency refers to the behavior of a program, which even if we run multiple times, does not change the outcome.

 

For example: Puppet follows desired state definition. If any target environment is already compliant to the desired state, it does not force run the commands anymore on the same, and rather skips that environment. This behavior is known as idempotency. Example: If the instruction to puppet is to ensure that ntp service is running across all servers, then it will skip the servers where ntp is already running.

Think about difference between these two commands on linux shell:

echo “hello” > test.txt
echo “hello” >> test2.txt
If you run both commands 10 times, you will end up with a test2.txt that has the word “hello” written 10 times in it. Whereas test.txt will have “hello” written only once. So across the 10 executions, every time test2.txt got different values – 1 line of hello, 2 lines of hello, 3 lines of hello …. 10 lines of hello. But test.txt outcome always remained same – 1 line of hello – no matter how many times you run the first command. Hence, first command is idempotent, and second command is non idempotent.


Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar