PHP Session Locks – How to Prevent Blocking Requests
Many people are aware that modern browsers limit the number of concurrent connections to a specific domain to between 4 or 6. This means that if your web page loads dozens of asset files (js, images, css) from the same domain they will be queued up to not exceed this limit. This same problem can happen, but even worse, when your page needs to make several requests to PHP scripts that use sessions.
Problem
PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.
The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.
Solution
The session file remains locked until the script completes or the session is manually closed. To prevent multiple PHP requests (that need $_SESSION data) from blocking, you can start the session and then close the session. This will unlock the session file and allow the remaining requests to continue running, even before the initial request has completed.
To close the session, call:
session_write_close();
This technique works great if you do not need to write to the session after your long-running process is complete. Fortunately, the $_SESSION data is still available to be read, but since the session is closed you may not write to it.
Example
<?php // start the session session_start(); // I can read/write to session $_SESSION['latestRequestTime'] = time(); // close the session session_write_close(); // now do my long-running code. // still able to read from session, but not write $twitterId = $_SESSION['twitterId']; // dang Twitter can be slow, good thing my other Ajax calls // aren't waiting for this to complete $twitterFeed = fetchTwitterFeed($twitterId); echo json_encode($twitterFeed); ?>
Thanks I honestly in 7 years of PHP never knew this.
I just had one of those “ohhhhhhh” moments. I never understood what was causing pages to lock up and always wrote it off as being Apache. The session file makes so much sense.
Thank you, I’ve been trying to figure this out for months since writing my own login system. It’s so simple, yet so helpful!
It seems that calling start_session() followed by session_write_close(), each time the PHPSESSID is added to the cookie. Doing this -many- times, your client could crash due to -huge- cookies. I have posted this problem against your solution here: http://bugs.php.net/bug.php?id=38104
@vdklah – There should be no reason to restart the session after closing it. The proper use-case for this technique would be to session_write_close() when you have no more data to write to the session. Also, I cannot think of a use-case where you’d need to open two different sessions in one request.
We have multi-threaded client applications. One thread is requests an export service that keeps running for a few minutes. Another thread is polling for progress information in the meantime to draw a progress bar. Both are running within the same session. One is writing progress info while the other is reading. We need to start- and close the session quickly to avoid blocking each other.
@vdklah – you should really consider using a non-locking session storage such as a database. Or not use the session for the progress indicator storage.
Of-course I can do all the hard work myself and write my own session cache manager. But that would be just because PHP is totally letting me down. Surprisingly, because PHP is dedicated to web technology and so you may have high expectations on session management. Invoking a database to implement caching implies the need for -two- connections to serve -one- client, which is expensive and heavy. I rather use something feather light weighted. Nevertheless, I was already thinking moving away from PHP sessions since it does not support dispatching over multiple application servers. Maybe I’m gonna have a closer look at Memcache, but that complicates installation of our product since we support many DB- and OS flavors. Thanks for sharing your ideas though!
Can I write to the session in the middle of the long-running operation like this:
<?php
session_start();
…
session_write_close();
// long-running operation begins
…
// need to write to the session
session_start();
$_SESSION['variable'] = value;
session_write_close();
// long-running operation continues
…
I was having the same problem for a FTP file download progress indicator and solved it with session_write_close(). However I was thinking if this session issue does really impose such a big impact on AJAX calls. Do we need to call session_write_close() everytime during AJAX calls when we are finished writing to the session?
It’s because session_start() effectively makes all AJAX requests synchronous if you don’t explicitly close it ….
@henkka
Are Henkka’s usage of the session_start and session_write_close functions valid???
I am trying to do the same thing as Henkka, and it seems to work okay… Is there anything wrong with this method?
Thank you so much.
Actually I was facing this problem when I wanted to display % of uploading file on server. So uploading request was taking so much time .. and in between I wanted to get size of file through ajax request. In session I was updating file information
….but without session_write_close() function I was always getting old request file information in session !!! but this saved my day.
Thank you so much
Ashok.
Thank you so much! you just saved me!!
Thanks so much. The main problem we were having is that if a long-running script is cancelled or fails for some reason, the session file seems to remain locked indefinitely, causing all pages to be completely inaccessible.
Now going to do an audit of all session access in our site and close the session as early as possible.
In all of my AJAX applications, I use a database session manager rather than the PHP version for a couple of reasons:
1) Sending multiple, simultaneous requests use AJAX causes the sessions to lock (as documented here)
2) If going through a bank of proxy servers (as happened at one client site) caused the session to bounce back and forth.
It’s pretty simple to write a session class, store the appropriate info in the database and that way you avoid these issue altogether. It would be nice if PHP had a configuration option for session.ajax that we could turn on so it wouldn’t file-lock the session.
My current project has 40 or so simultaneous ajax requests going out, and while I know the browser parks the bulk, removing the reliance on the phpsession keeps things flowing.
How does your database session manager handle locking? Does it have any precautions for concurrent writes overwriting each other?
You may think that database sessions solve the locking problem, but it introduces an even more significant problem. Session locking is actually a feature to prevent concurrent overwrites of session contents. For example, say you have two concurrent requests, each that modify different parts of the session data. If any time passes between reading the session data and writing the modifications you could overwrite a concurrent update.
I still maintain that closing the session for writing when you don’t need to write to it is the best solution since session locking can prevent some pretty major unintended consequences. Match that with only starting the session when you actually need it and PHP’s default file-based sessions is fail-proof.
Uff, I was not aware of such SESSION behaviour even after 10+ yrs of PHP experience… very nice, thanx!
nice code..
thanks
I love you and I wanna make you love.
Not really ^_^ but thanks from the deep of my heart
thx a lot. That solved my blocking problems :)
i faced this problem with a comet implementation and your post was helpfull ! thank you :D
This was really helpful. I am making low latency web application with some heavily blocking pages and couldn’t figure out what was causing it to block other pages much. I thought I might need to check all database interactions and transactions and whatnot, but the problem it seems was a thing you take for granted and never bother to think how it really works.. This info really should be posted on related php.net page. THANKS.
Just wanted to say this saved me a whole headache of frustration!
I had a download.php?fileid=### to dump binary of a file. I required access to the session variables but not writing them.
You’re a lifesaver! Or at least a braincell saver, I burned too many of them trying to figure out what the hell was happening with my webapp slowing down to slug pace
Thank you!
Hazard: The unit can overheat, posing a fire hazard to consumers.
Now all that is left is to wait and see who comes out the lucky winner.
It allows you time to test your market and evaluate your price
point.
Thank You!
Great and simple solution for a maddening problem
i use jquery ajsax to get data form datatbase through php script it is a real time application
i apply a code when new row come then table new row highlight and a popup is come as a alert but when new row is come then popcome many time it look very bad how i solve it….
Thanks !!!. Helped me a lot
Presenting hilarious conversation and graphics, might-ups, and
dozens of entertaining shape chains of duplicate
symbols to creation by invading and subjugating China, narrowly averting a time paradox.
some examples of mobster Game are such can be played on your computing device.
They Feature dent tickets where you can but what can you
Require with the downright total of Release game to be played?
With more than bloon types and more than levels to they oft get into the stocky of things themselves, but all heroes have several powerful ability options.
Nice article. Thank you so much !!!
Thank you very much !!!!!