Race Conditions, AJAX and Sessions

Via Jeff’s bookmarks, Race Conditions with Ajax and PHP Sessions by Andy “thwarted” Bakun is an outstanding anaylsis of a problem that’s come up before on this blog here.

In fact the title is almost misleading – the first half looks at “parallel processing” in Javascript with some valuable insight – i.e. you want to read this even if you’re not using PHP.

The second half explores building a custom PHP session handler (PHP’s default session handler does not suffer from race conditions but can become problematic the moment you start handling serious traffic), leading up to a very cunning strategy that allows you to lock a single session variable (rather than the entire session) via overloading the $_SESSION variable using SPL – effectively an alternative to using session_set_save_handler() – let’s hope this becomes recognised as a feature that needs supporting.

And it’s refresshing it is to see something like this in PHP-related content…

the built-in [PHP] session handler uses the flock(2) system call [...] This can be verified by using strace to list all the system calls being made by a process. Here’s the important bit:

open("/var/lib/php/session/sess_XXXXXXXXXXXXXXXXXXXXXXXXXX", O_RDWR|O_CREAT, 0600) = 18
flock(18, LOCK_EX)                      = 0
fcntl64(18, F_SETFD, FD_CLOEXEC)        = 0
fstat64(18, {st_mode=S_IFREG|0600, st_size=11, ...}) = 0
pread64(18, "count|i:17;", 11, 0)       = 11
. . . .
pwrite64(18, "count|i:18;", 11, 0)      = 11
close(18)                               = 0

Side note – find myself agreeing with much of Andy’s Problems with PHP – much closer to the mark than the sort of gripes you typically find on the PHP sucks web ring.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://gnuix.com/ammar ammar_ibrahim

    A highly trafficked site should always override the session handler. Basicly a database based solution is very simple, it shouldn’t have a race condition.
    I don’t think this is a big issue, the default option is a simple one for simple sites, you always need to have a very good understanding of whatever technology you use if you want to go for something bigger. And most well written open source PHP projects that I’ve seen, have a custom session handler.

  • Andy Bakun

    ammar, a database based session solution will have the same problem if it doesn’t properly lock the session, as the demo application written for the article shows. The chances of a solution, database based or not, having a problem is increased if it the solution is merely “simple” and doesn’t take into account the way the system ultimately ends up being used.