Understanding Good Practices

Idempotency Memories

Introduction

I wrote this post because i spend a lot times fixing my own script issues installing, deploying and in some apps code. The problem always was bad practices.

An idempotency operation is an action that gives the same result no matter how many times you repeat it. This is useful in many areas of programing and system design.

SQL Queries

In SQL, you can make your queries idempotent by first checking if the data you want to check alerady exist. For example, before updating a record, verify if it’s there. This way, running the same query multiple times won’t cause errors or unwanted changes.

Simple Example - Create a table:

1
2
3
4
5
6
CREATE TABLE IF NOT EXISTS person (
  id integer NOT NULL,
  person_name character varying(40) NOT NULL,
  updated_date date,
  CONSTRAINT person_pkey PRIMARY KEY (id)
);

Bash

When working with distributed system(vm machines, creating automated scripts), operations may not always happpen instantly. Sometimes the same request migth be sent multiple times. To execute idempotent commands you have to read more in detail.

Simple example - Create a table:

1
2
3
4
5
6
7
8
9
#Creating a symbolic link

ln -s source target
ln -sf source target

#Removing a file

rm example.txt
rm -f example.txt

Docker

When writing a Dockerfile. It’s good practice to make sure all commands are idempotent. This means running the build process multiple times won’t create unexpected issues with our app.

1
2
3
4
5
6
7
# wrong way
FROM node:latest
RUN yarn install <sompackage>

# right way
FROM node:11
RUN yarn install <sompackage>

I hope this blog has been a bit helpful, I’ll give a talk this week and it makes me nervous and writing relaxes me.

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy