Home > PHP > PHP Session Locks – How to Prevent Blocking Requests

PHP Session Locks – How to Prevent Blocking Requests

December 17th, 2010

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);
?>
Be Sociable, Share!
Categories: PHP Tags: , , ,
  1. Steven
    December 17th, 2010 at 01:01 | #1

    Thanks I honestly in 7 years of PHP never knew this.

  2. December 17th, 2010 at 10:15 | #2

    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.

  3. Glenda
    January 14th, 2011 at 17:28 | #3

    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!

  4. vdklah
    February 4th, 2011 at 10:32 | #4

    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

  5. Konr Ness
    February 4th, 2011 at 15:24 | #5

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

  6. vdklah
    February 5th, 2011 at 08:43 | #6

    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.

  7. Konr Ness
    February 5th, 2011 at 14:06 | #7

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

  8. vdklah
    February 6th, 2011 at 05:58 | #8

    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!

  9. henkka
    March 30th, 2011 at 13:23 | #9

    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. Ilian Andreev
    April 4th, 2011 at 17:17 | #10

    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?

  11. Ilian Andreev
    April 4th, 2011 at 17:19 | #11

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

  12. eel
    April 27th, 2011 at 21:18 | #12

    @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

  13. eel
    April 27th, 2011 at 21:19 | #13

    I am trying to do the same thing as Henkka, and it seems to work okay… Is there anything wrong with this method?

  14. May 18th, 2011 at 05:03 | #14

    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.

  15. November 20th, 2011 at 05:17 | #15

    Thank you so much! you just saved me!!

  16. January 3rd, 2012 at 11:33 | #16

    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.

  17. Roger Wyatt
    February 7th, 2012 at 15:17 | #17

    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.

    • Konr Ness
      February 7th, 2012 at 15:25 | #18

      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.

  18. March 8th, 2012 at 13:04 | #19

    Uff, I was not aware of such SESSION behaviour even after 10+ yrs of PHP experience… very nice, thanx!

  19. March 19th, 2012 at 06:13 | #20

    nice code..
    thanks

  20. Yihad
    April 23rd, 2012 at 05:47 | #21

    I love you and I wanna make you love.

    Not really ^_^ but thanks from the deep of my heart

  21. David
    May 7th, 2012 at 07:05 | #22

    thx a lot. That solved my blocking problems :)

  22. libert
    June 3rd, 2012 at 18:52 | #23

    i faced this problem with a comet implementation and your post was helpfull ! thank you :D

  23. lexxsoft
    July 2nd, 2012 at 14:54 | #24

    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.

  24. August 28th, 2012 at 14:58 | #25

    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.

  25. Wim
    November 6th, 2012 at 14:50 | #26

    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!

  26. November 27th, 2012 at 10:42 | #27

    Thank You!
    Great and simple solution for a maddening problem

  27. Kalai Selvan
    February 18th, 2013 at 10:43 | #28

    Thanks !!!. Helped me a lot

  28. April 9th, 2013 at 22:58 | #29

    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.

  29. Vir
    April 17th, 2013 at 04:50 | #30

    Nice article. Thank you so much !!!

  30. OJ
    April 21st, 2013 at 06:54 | #31

    Thank you very much !!!!!

  31. szaman
    July 19th, 2013 at 01:47 | #32

    it help me so much!

  32. ruio
    August 1st, 2013 at 16:00 | #33

    Thanks, a very useful tip :)

  33. Daniel Nilsson
    October 17th, 2013 at 06:39 | #34

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

  34. October 24th, 2013 at 17:42 | #35

    Great weblog here! Also your web site a lot up very
    fast! What host are you the use of? Can I get your
    associate link for your host? I want my web site loaded up as fast as yours lol

  35. ocoder
    October 29th, 2013 at 19:33 | #36

    I love you man, thanks a lot !

  36. January 25th, 2014 at 14:11 | #37

    I visit day-to-day some web pages and sites to read content,
    however this web site presents quality based posts.

  37. February 3rd, 2014 at 18:59 | #38

    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!

  38. romli
    March 14th, 2014 at 03:55 | #39

    cool thanks…

  39. Eugen
    March 31st, 2014 at 02:43 | #40

    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.

  40. April 9th, 2014 at 13:31 | #41

    Even years later this post proves to be incredibly helpful! I hadn’t run into this issue before but this post just saved us a ton of time.

  41. Alex
    April 13th, 2014 at 16:20 | #42

    Gratitude

  42. Fer
    June 10th, 2014 at 09:31 | #43

    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?

  43. June 17th, 2014 at 07:48 | #44

    If PHP is not handling requests asynchronously even after calling session_write_close, it may just be xdebug.

  44. Johnb704
    June 22nd, 2014 at 22:09 | #45

    You are my inspiration , I have few web logs and very sporadically run out from to brand. gdecdcdbdgba

  45. July 27th, 2014 at 05:18 | #46

    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.

  1. January 18th, 2012 at 15:09 | #1
  2. October 15th, 2012 at 20:45 | #2
  3. April 21st, 2013 at 04:32 | #3
  4. June 5th, 2013 at 17:59 | #4
  5. July 15th, 2013 at 21:16 | #5
  6. October 6th, 2013 at 17:13 | #6
  7. October 10th, 2013 at 06:09 | #7
  8. December 31st, 2013 at 01:33 | #8
  9. July 29th, 2014 at 01:35 | #9
  10. August 4th, 2014 at 20:06 | #10
  11. August 4th, 2014 at 20:07 | #11
  12. August 4th, 2014 at 20:08 | #12