Sessions, locks and handlers

Hii there,

I am always trying to improve the performance of my website and came across a point where I found out that by default, PHP sessions are locking (meaning that request B will “stall” while request A is still going).
This is done to prevent data inconsistency when modifying certain session variables between requests.

Now this creates a new question: how much does this lock affect CakePHP’s performance (specifically 3.9.x as I still need to upgrade s00n™) and would switching the handler to something like a database session (using MySQL) or a cache session (using something like APCu) be of any benefit in the case that CakePHP’s performance is affected by said lock?

First to say: I cannot answer your question directly.
But I can say the following:

  • Writing/Reading to/from disk is always (much) slower then in-memory technologies

That is why I prefer using memcached or redis for storing the sessions. The configuration is very easy:

Example configuration (app.php):

'Session' => [
            'defaults' => 'cache',
            'timeout' => 1200,
            'handler' => [
                    'config' => 'default',

'Cache' => [
            'default' => [
                    'className' => 'Cake\Cache\Engine\MemcachedEngine',
                    'duration' => '+1 hour',
                    'prefix' => 'myprefix_',

Of course, you can store other cake-caches (_cake_core, etc) on memcached or redis as well.

Note: additional php-memcached/redis packages are required on the system as well as a running memcached/redis instance

Thanks for your reply, so as far as you know, just sheer reads/writes are at play here, which would benefit applications with a decent amount of traffic a lot.
Interesting… I’ll have a look at using APCu (since I use APCu a lot in my app anyways) to see whether it’ll give me any performance increases.
Are you aware of any data inconsistencies occurring when using an in-memory engine for it?

Tested using APCu to store sessions and it indeed did shave off some measurable (7ms per request) time :slight_smile:
Time will tell whether data-inconsistencies will occur.

I haven’t had any problem regarding data inconsistency yet.
This depends more on how the engine is used and the engine itself and cannot be answered in general I think.

As far as I know, those problems mostly occur when 2 or more programs modify the same data at the same time. If that may happen in your use case you need to rely on locking mechanisms again.
This should, however, be faster when using in memory stores like redis/memcached :slight_smile:

1 Like