Categories

PHP is off to the races

It appears that I have something in common with The Chipmunk Ninja.

Yesterday, to my great horror, data was seemingly vanishing from my application, returning to inaccurate states, and generally behaving badly.

What’s worse, the error was intermittent and seemingly random. Like a quantum state phenomenon, when I looked closely at the error, it vanished. After a full day of throwing code against the wall and generally beating my head against the same wall, I discovered that one of my AJAX requests was finishing late and flushing its session data to disk after another request had been called, overwriting the later data.

In programming terminology, this is called a race condition. It occurs in situations where two threads access one area of shared memory. Unless the two threads are externally synchronized (with a Semaphore for example) there is no way of predicting which thread will reach the memory first, hence: a race.

In an AJAX application, XMLHttpRequests work a lot like threads, and session data works quite a bit like shared memory. The problem with synchronization is that it really takes the A out of AJAX, leaving you with SJAX, which isn’t that impressive. The only real solution that I’ve seen basically boils down to “don’t do that again” Conditions where a race could exist should be sequenced by the client-side interface if the race exists on the client, ie. number your XML/JSON responses with sequence numbers so the client can make sense of it all. On the server-side, don’t share session variables between two racing “threads”. It’s really this simple, don’t trust session data when using AJAX.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>