PHP Web Development – Parallel Requests and Session Stability

PHPweb-development

I've experienced a lot of issues that were the result of the nature of PHP living within the bounds of a stateless HTTP request, especially considering the asynchronous environment expected of modern web applications.

Namely, regeneration of session handles can cause session self-destructs if parallel requests are occurring. Additionally, unless a request locks the session for its duration, session updates on parallel requests are at risk of conflicting and being overwritten by the other. If they do lock the session, it forces serialization of the requests.

What did you find to be the most effective response to this problem?

Do you just live with it and implement workarounds? Did you ultimately migrate to a different platform that didn't have this flaw? Or is there a PHP solution to this problem I'm not aware of?

Best Answer

The simple solution would be to call session_start() just before you actually need $_SESSION (and not at the head of the script) and session_write_close() just after you finished with it. That's a bit awkward, but it works fairly well.

The not so simple solution would be to write a custom database backed session handler (see: SessionHandler for PHP 5.4), fined tuned locking is a bit easier with a database. For example for MySQL/InnoDB you could have locking reads with "SELECT ... FOR UPDATE". If InnoDB sounds too resource hungry for you, you could go for a Memory table, but locking will be a bit more complicated.

That said, what you really need to ask yourself is whether you're relying on $_SESSION a bit too much, especially the default file based flavour. Have you considered Memcached? As a session backend and as an alternative persistence mechanism.

There are a lot other, perhaps more exotic choices, I'm currently exploring Amazon's DynamoDB as a session backend. Here's a brief outline of Dynamo backed sessions, written by our CTO, who couldn't resist calling me out:

Do not use session variables as a replacement for caching. For example, we have seen developers saving whole HTML blocks in the session array.

Related Topic