November 03, 2006

Idempotence? What's that?

When I'm architecting enterprise systems I often get that response when I talk about my preferred alternative to using 2 phase commits and XA.

Idempotence is not a particularly difficult concept. I define it as a behaviour that has the same outcome on the second, third, fourth etc. time of trying as it had on the first.

A lot of things in our day to day life are idempotent. Say you are going to the car with some bags. On reaching the car you put the bags down and go to unlock the car; you are then interrupted by a friend calling to you and you have a chat. When you turn back to the car you can't remember if you unlocked it or not so you go to unlock it again. If you had actually already unlocked the car, it will remain unlocked. Unlocking a car is normally idempotent - I'm not answerable for odd car designs or for people that actually lock their cars again when they do this.

This can be extremely useful when you are trying to integrate two disparate transactional systems. Lets call one system A and the other B. If we are doing something in A that needs a change to be applied in B we can make the change to B idempotent.

The process would often work like this.
  1. Open a transaction in A.
  2. Do the work in A.
  3. Open a transaction in B.
  4. Do the work in B. Idempotent
  5. Close the transaction in B.
  6. Close the transaction in A.
If a problem occurred in steps 1 to 5, systems A and B would be in a consistent state as both transactions would be rolled back. If a problem occurs at stage 6 then B would have the change while A doesn't.

When the process is re-run successfully A and B will end up in a consistent state as long as the work done at B is idempotent.

This is a much lighter weight mechanism that the 2 phase commit / XA one but it does mean that there is a window in which A and B can be inconsistent. For many systems this window may not be a problem in which case I'd recommend the use of idempotence.

No comments: