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.


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.


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:


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.


// start the session

// I can read/write to session
$_SESSION['latestRequestTime'] = time();

// close the session

// 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);

48 thoughts on “PHP Session Locks – How to Prevent Blocking Requests

  1. 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.

  2. 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!

  3. @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.

  4. 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.

  5. 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!

  6. Can I write to the session in the middle of the long-running operation like this:



    // long-running operation begins

    // need to write to the session
    $_SESSION['variable'] = value;

    // long-running operation continues

  7. 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?

  8. It’s because session_start() effectively makes all AJAX requests synchronous if you don’t explicitly close it ….

  9. @henkka

    Are Henkka’s usage of the session_start and session_write_close functions valid???

    henkka :
    Can I write to the session in the middle of the long-running operation like this:

    // long-running operation begins

    // need to write to the session
    $_SESSION[‘variable’] = value;
    // long-running operation continues

  10. 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


  11. 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.

  12. 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.

  13. 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 page. THANKS.

  14. 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.

  15. 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!

  16. I am writing load balanced FastCGI interface for a Twisted driven webserver. And this has haunted me for 2 days now. I could not understand how multiple requests would queue up execution when they were sent to multiple fast-cgi process instances of PHP. When I finally realized issue exist on IIS and Apache as well I looked elsewere, then I saw that requests that would have different session cookies did not queue and the issue were not in my code in the first place.

    Googled and found this.. Makes perfect sense and allows me to complete my work, GREAT THANKS!!! :)

  17. I wrote a WP plugin that has a long running script (like 5min).
    The whole blog was blocked until the script has finished its work. Thanks to your post now everything works like a charm.
    Thanks for sharing.

  18. Thanks manymuch, but I dont know why the code is not working for me:
    I have a page with:

    $_SESSION[‘latestRequestTime’] = time();
    echo sprintf(“Start Time: %.2f seconds\n”, microtime(true));

    If I call it from two browser tabs, the second one waits 20 seconds (so not in parallel) Am I missing something? php configuration maybe?

  19. Thanks,
    This solved a problem with long running background processes hanging the browser on ajax calls. Good information that saved some grief on my project.

  20. I spent almost 8 hours to investigate why my AJAX calls are not working as they were supposed to work and finally this article came to my way. Thank you so much for explaining

  21. i am testing a php progressbar with a long runing process.. all my pages freezed just after the progressbar started…was wondering what was going on.. thank you for saving my worked like a charm.

  22. Yes, it’s about years.
    It’s because of the word “async” i was looking for with search engines.
    I’m speaking about years, since ie6 and my first ajax app. My first blocking ajax app, with a blocking calendar, and a fast blocking gui
    Then came * to try improve connection issue.
    Then came nodejs and and apache and php to have a solution : there finaly were no solutions : as blocking as usual, but hey, so modern !
    Then came nginx, i was thinking this was an apache problem.
    Then came websocket, actually serving content in place of ajax/
    That’s ok, my App is really modern and up to date, i should say : my blocking app is really modern and up to date.

    I was doing tests on a php cli webserver, and i asked : “php request blocking”, instead of the usual “ajax asynchronous error” i used to make on google …

    Best site ever !

Leave a Reply

Your email address will not be published. Required fields are marked *