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

62 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:

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

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

  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

    Ashok.

  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 php.net 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. 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.

  17. 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!!! :)

  18. My developer is trying to convince me to move to .net from PHP.
    I hqve always disliked tthe idea becase of the costs.
    But he’s tryiong none the less. I’ve been using WordPress oon various websites for about a
    year and am anxious about switching tto anothger platform.
    I have heard very good things about blogengine.net.
    Is there a way I can transfer all my wordpress content into it?
    Any help would be really appreciated!

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

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

    session_start();
    $_SESSION['latestRequestTime'] = time();
    session_write_close();
    sleep(10);
    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?

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

  22. PADI IDC courses are globally recognized; and a ten day plus IDC course
    will certainly put you on the right track to becoming a PADI Open Water Scuba Instructor (OWSI).
    Right after learning the fundamental principles associated with scuba dving, students can immerse themselves to successfully at the most e with a licensed scuba diver.

    The carp is a fish species surrounded in myth, legend, and
    lore.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>