Friday 21 November, 2008

Locking considered harmful.

Seriously. Locking is counterproductive to writing fast websites. Any process that meets a lock that is already locked, waits. It waits until it is free. And waiting means that the page being generated goes nowhere until the lock is free again. Locking is not good. Really. So stop using them.

The problem with locking is compounded the more processes you have. Firstly because the likelihood that someone else has the lock when I reach it is increased. If two people enter a shop at the same time the chance that they both want to ask the assistant for help at the same time is very small. But if there are twenty people it is much more likely that some of them will want the assistant's attention at the same time.

And secondly, having more processes means that the length of the queue waiting for a lock can be much longer. If two people in a shop are trying to ask the assistant for help at the same time the most they will have to wait is for the other person. But with twenty, if only a quarter want help at the same time the last person has to wait for four others.

In short, locking is terrible for performance and it deteriorates very quickly as more and more processes try to grab the one lock at the same time. This behaviour can be very easy to run into on busy web servers as multiple incoming requests are dealt with simultaneously. They are not your friend.

But locking does have a use. The assistant in the shop wouldn't cope very well if they let each customer talk to them at the same time. So it is with software. Trying to update an account's balance at the same time as another processes could mean that the first ignores the second's changes - leaving an incorrect total. A lock here prevents such problems from occurring.

Careful usage will avoid nasty performance problems and protect critical code. But my fear is that many developers haphazardly use locks in their web apps without considering their true cost. Like not unlocking a lock nor committing a database transaction as soon as possible, or liberally applying them throughout their apps. This sort of programming is bound to create problems as soon as you get some serious traffic.

If you're a developer then: please think carefully before adding another lock to your code. Usually a better design will either eliminate or reduce the need for locking. Locking decreases performance and makes things more complex than they ought, so treat it like fire - a little bit will keep you warm, but too much and you'll burn down the entire house.

Market Place
 

Techworld Australia Member Login

c