Two locks that do not know each other: why a PHP request waits when the server is free
PHP | Session and database
- 24 min read
- 17 terms from the glossary
- 6 code blocks that were run
On my personal server, the one that hosts a few nice applications and that I use for experiments, there is one heavy page: a report that takes about half a minute to load. One day I opened it, and while it was finishing I switched to another tab and clicked a page that has nothing on it, the kind that always loads at once. It did not load. I opened another tab, same thing.
The first thing I did was check the server, because that is what you do. The processor was barely working, there was memory to spare, and the database looked bored. So what is stuck?
For no particularly good reason I opened a private window and went to the same empty page. It loaded at once. I went back to the regular window, and it was still stuck.
That can no longer be explained by a slow server. A slow server is slow for everyone. Here the same page, on the same computer and in the same second, was fast in one window and stuck in the other. In other words, my request was standing in a queue, and the queue was mine alone.
It turned out that an ordinary PHP application has two different locks that can put a request in a queue, one inside PHP and one in the database, and that they know nothing about each other. I will go over both, and at the end I will show how to tell which of them you are facing without guessing.
I am writing this post as a record of learning: what I saw, how I checked, and what I have done differently since.
You do not need to know the mechanisms in depth to read it. And if words like session and cookie are completely new, there is an appendix that starts from zero at the end of the post. You can jump to it and come back to the story.
Part one — what happened, step by step
1. The first lock: PHP's session
session_start() looks like a line that reads data and that is it. In practice it also locks. It takes the session id from the cookie, opens the session's file on the server, and puts an exclusive lock on it. And what I did not know for a long time: the lock does not come off when the reading is done. It stays until the whole script ends.
This is not a bug. If two requests of the same user read the session at the same time, each changed something and wrote it back, the second would overwrite the first without anyone noticing. So PHP simply does not let that happen: one script works on a session at any moment.
Only something comes out of it that you do not expect. All the requests of the same user run one after the other. A page that sends ten AJAX calls at once? They reach the server together and then wait for each other. And one slow page holds the lock for as long as it runs, even if it touched the session once, in the first line, and has forgotten it since.
The lock is on the whole file. You cannot lock only $_SESSION['cart'] and leave the rest open, because everything sits in the same file. And it is an ordinary file lock of the operating system, so the database does not know about it, and none of its monitoring tools will see it. That is part of what misled me when I looked at a bored database.
And this is also the explanation for the private window. The lock belongs to the session, and the session belongs to the cookie. All the tabs in a regular window share the same cookie, so they also share the lock. A private window starts without cookies, gets a new session with a file of its own, and nobody is holding that file.
(All this is true when the session is stored in files, which is the default. With Redis or a database it depends on the handler and its settings, and it is worth checking rather than assuming.)
What is this lock called? The common name is Session Lock. Beneath it is a File Lock: a lock the operating system puts on a file, at the request of the process that opened it. The component that determines where the session is stored, and therefore also how it is locked, is called the Session Handler.
2. Seeing it with your own eyes: two files
The easiest way to be convinced is to see it happen. You need two files. One that is slow on purpose:
<?php // slow.php
session_start();
sleep(20);
echo 'done';And the second does nothing, it only measures how long it waited for the session:
<?php // fast.php
$start = microtime(true);
session_start();
echo round(microtime(true) - $start, 1) . ' seconds waiting for the session';You open slow.php in one tab and right after it fast.php in a second tab. The page that has no work in it will report almost twenty seconds of waiting. Now, while slow.php is still running, you open fast.php in a private window. Zero.
Notice where the waiting is: inside session_start() itself. The code of fast.php has not started yet. If you measured times from inside the code, after that line, you would see a completely fast page and not understand what the users are complaining about. Only the browser sees the twenty seconds.
And now you add one line to slow.php:
<?php // slow.php
session_start();
session_write_close(); // saves the session and releases the lock
sleep(20);
echo 'done';You run it again, and fast.php answers at once even in a regular tab. slow.php did not get faster by even a second. It only stopped holding up everything else.
Before you run it: PHP's built-in development server (php -S) answers one request at a time. With it, fast.php will wait even in a private window, for an entirely different reason. To see the demonstration as it is meant to be seen, you need a server that runs several processes in parallel, such as Apache or PHP-FPM.
3. The second lock: blocking in the database
The second lock is a different story, in a different place. When a transaction changes a row, the database locks the row until the transaction ends, with COMMIT or ROLLBACK. Whoever needs the row in the meantime waits.
This too is easy to see. You open two windows of the query tool (the examples are in SQL Server, but it works similarly in any database with transactions). In the first one you open a transaction and "forget" to close it:
BEGIN TRAN;
UPDATE dbo.Orders SET Status = 'packed' WHERE OrderId = 1;
-- without COMMITIn the second window you touch the same row:
UPDATE dbo.Orders SET Status = 'shipped' WHERE OrderId = 1;The second window returns neither an error nor a result. It waits, and it will keep waiting as long as the first one does not close. In SQL Server with the default settings even an innocent SELECT on this row would get stuck.
The big difference from the first lock: here the database knows exactly what is going on, and you can simply ask it:
SELECT session_id, blocking_session_id, wait_type, wait_time
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;Every row that comes back is a request that is waiting, who is blocking it, and how long it has been there.
This lock does not care who you are. It locks data, so it stops everyone who touches it, no matter from which user, browser or private window. And whoever does not touch these rows will feel nothing. It is also not tied to the request that opened it but to the transaction: if the transaction stayed open, the row stays locked even after the page has long since gone back to the user.
And a small warning about words, because I fell into this: SQL Server also uses the word session, and there it means a connection to the database. The session_id in the query above has nothing whatsoever to do with PHP's session. When you talk about such a failure with someone else, it is worth saying each time which session you mean.
What is it called in the database? The lock on the row is a Row Lock. The waiting of one request for a lock that another request holds is called Blocking. And the setting that determines whether a read also waits for a locked row is called the Isolation Level.
4. Which lock you are facing
From the outside both look identical: a page does not load, and the server is not busy. The differences start when you look closely:
| PHP's session lock | Blocking in the database | |
|---|---|---|
| What is locked | The whole session | Rows, pages or a table |
| Who waits | Other requests from the same browser | Everyone who touches the same data |
| Private window | Fast | Just as stuck |
| Where the request is stuck | Inside session_start(), before the code |
Inside the query |
| What the database shows | Nothing. The request has not reached it yet | A waiting request, and who is blocking it |
| When it is released | At the end of the script, or at session_write_close() |
At COMMIT or ROLLBACK |
In practice I check two things, and both take less than a minute.
First of all a private window. If the page loads quickly there while the regular window is stuck, you are waiting for the session. If it is stuck there too, you are waiting for the data. Funny that what I did back then out of despair is in fact the fastest check there is.
Then you ask the database, with the query from above, while the page is stuck. If a waiting request comes back, you have found the blocking and also who is causing it. And if nothing comes back, that is an answer too: the stuck request has not reached the database yet.
The second answer is easy to read wrongly, and that is how I read it at first. A quiet database while a user is stuck really does say that on the database's side everything is fine. It does not say there is no lock. It says the lock is not there.
5. When the locks chain together
Until now I talked about each one separately, and separately they are fairly simple. The trouble starts when one sets off the other. It goes roughly like this:
-
Somewhere a transaction stays open, holding one row. That is the second lock.
-
A user opens a page that needs this row. Their request waits in the database. While it waits the script has not ended, so it keeps holding their session. That is the first lock.
-
They lose patience and click another page, one that does not touch this row at all. The new request stops in
session_start(), behind the first request. -
They refresh, open another tab, click again. Every click joins the same queue.
And now there are two descriptions of the same failure that do not fit together. The database sees one request waiting. The user sees a dead site, on every page and in every tab. Both are right: one small blocking in the database swelled on the way, through a lock the database does not even see.
A private window also behaves differently here, and it is worth knowing this so as not to get confused. At first it is fast, because it has a session of its own. It stays fast until you go to a page in it that needs the locked row. There it gets stuck too, and from that moment the new session is locked as well. So if a private window worked for you for a minute and then got stuck on a certain page, you probably met both locks together.
And there is one more stage, in which one user's failure becomes everyone's failure. Every request standing in the queue occupies a whole PHP process, even if it does nothing but wait. And there is a limited number of processes. Enough stuck users pressing refresh enough times, and the processes run out. From that moment people who touched nothing locked are waiting too, and everything looks like ordinary load. Go guess from here that it all started with one transaction someone did not close.
6. What to do about it
You cannot get rid of these locks, and you would not want to, because they protect real things. What you can do is hold them for less time.
With the session that means releasing it the moment you have finished writing to it. On most pages the writing happens at the start, around authentication, and the heavy work comes afterwards:
session_start();
$_SESSION['last_seen'] = time();
session_write_close(); // from here the lock is free
$report = buildHeavyReport(); // the slow part no longer holds anyone upIt is worth being precise about what exactly is closed here. session_write_close() closes the whole session: it saves the data and releases the lock. What remains after it is the $_SESSION array in memory, so reading from it keeps working as usual. It is a copy from the moment of closing: a change that another request writes in the meantime will not appear in it, and writing to it will not be saved. PHP does not warn about such a write, it simply disappears at the end of the request.
When you still need to write to the session later in the request, you open it again just before the write and close it right after:
session_start(); // locks again and loads the current data
$_SESSION['report_ready'] = true;
session_write_close(); // saves and releases againThis way the lock is held for a short moment around each write, instead of for the whole length of the request. Two things to remember about reopening. It loads the session from storage, so anything written to the array while it was closed is overwritten. And it has to happen before the page starts sending output to the browser, because after the headers have been sent PHP will not open a session.
That is also why you cannot stick session_write_close() at the top of every file and go home. First you check who writes to the session later in the request, and you wrap every such write in an open and a close.
For a page that only reads from the session there is a shortcut, which reads the data and releases at once:
session_start(['read_and_close' => true]);With the database it means not leaving a transaction open when something goes wrong in the middle. If an exception is thrown after beginTransaction and before the commit, the transaction may stay open, and the rows stay locked along with it:
$pdo->beginTransaction();
try {
$pdo->exec("UPDATE dbo.Orders SET Status = 'packed' WHERE OrderId = 1");
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $e;
}And one more thing: inside a transaction you do not do slow things that do not have to be in it. A call to an external service, sending an email, creating a file. Every such second is a second in which someone else is waiting for the row.
7. What was checked before publishing — and what remains open
Before publishing, both demonstrations were reproduced. The two files were run by PHP 8.2 with the session stored in files, in several processes that share one sessions folder. The three queries were run by SQL Server 2019 with the default settings, on a test table. The claims were also compared with the documentation of PHP and of Microsoft.
This is how fast.php answered while slow.php was running in the same browser, and then without a cookie, as in a private window:
19 seconds waiting for the session
0 seconds waiting for the sessionAnd this is the row the query on the waiting requests returned, when the second window had already been waiting for three seconds:
| session_id | blocking_session_id | wait_type | wait_time |
|---|---|---|---|
| 56 | 55 | LCK_M_X | 3035 |
| What is written here | What was found |
|---|---|
The second request waits inside session_start() |
Reproduced: 19 seconds of waiting in the same browser, 0 without a cookie |
One line of session_write_close() frees the rest |
Reproduced: fast.php answered at once, and slow.php still ran for 20 seconds |
read_and_close reads and releases at once |
Reproduced, and written in PHP's documentation |
| After closing, reading works, and writing disappears without a warning | Reproduced: the value was not saved, and no message appeared |
| Reopening overwrites what was written while the session was closed | Reproduced |
| After output has been sent, PHP will not open a session | Reproduced: session_start() returned false, with a warning |
| An update of a locked row waits until the end of the transaction | Reproduced: the second window waited until the first one closed |
A SELECT of the locked row waits too |
Reproduced in SQL Server with the default settings. A SELECT of another row answered at once |
| A transaction may stay open after an exception | True under certain conditions, detailed below |
| Waiting requests use up the PHP processes | Not reproduced |
| With Redis or a database the locking depends on the handler | Checked only against the documentation of the phpredis extension: there locking is off by default |
What was verified? Both locks, each one separately, and everything written here about closing and reopening the session.
What was not verified? The full chain of both locks together, the processes running out, and the behavior of session storage that is not files.
The check also turned up three details that did not come up in the story.
The wait_time column is measured in milliseconds. 3035 in the row above is three seconds. And the value LCK_M_X in the wait_type column says that the request is waiting for an exclusive lock.
The SELECT that got stuck depends on one setting. According to Microsoft's documentation, in SQL Server the READ_COMMITTED_SNAPSHOT setting is off by default, and a read waits for a row that another transaction changed. In Azure SQL Database it is on by default, and there such a SELECT does not wait. An update of the same row waits in both cases.
And a transaction that stays open after an exception is not the usual case. According to PHP's documentation, when the script ends PDO itself rolls back a transaction that was opened with beginTransaction and not closed. It stays open for a long time when the connection is kept between requests (a persistent connection), or when the script keeps running after it caught the exception. The rollBack in the example closes it at once, in any case.
Part two — the professional summary
A stuck page and a free server: how do you get to the right lock?
- A page does not load, and the server is not busy — leads to: Does the page load quickly in a private window?
- Does the page load quickly in a private window? — leads to: Waiting for the session: the PHP lock; Ask the database who is waiting
- Waiting for the session: the PHP lock
- Ask the database who is waiting — leads to: Did a waiting request come back?
- Did a waiting request come back? — leads to: Blocking in the database: an open transaction holds the data; The request has not reached the database yet: the lock is not there
- Blocking in the database: an open transaction holds the data
- The request has not reached the database yet: the lock is not there
Source code of the diagram (Mermaid)
flowchart TD
A[A page does not load, and the server is not busy] --> B{Does the page load quickly in a private window?}
B --> C[Waiting for the session: the PHP lock]
B --> D[Ask the database who is waiting]
D --> E{Did a waiting request come back?}
E --> F[Blocking in the database: an open transaction holds the data]
E --> G[The request has not reached the database yet: the lock is not there]The two checks answer different questions. A private window checks whether the queue belongs to one browser. The query checks whether the queue belongs to the data.
The tools: what locks, what releases, what shows
| The tool | What it does |
|---|---|
session_start() |
Opens the session and locks it until the end of the script |
session_write_close() |
Saves the data and releases the lock. The $_SESSION array stays in memory, but writing to it is no longer saved |
session_start(['read_and_close' => true]) |
Reads the data and releases at once |
BEGIN TRAN |
Opens a transaction. A row it changes is locked until it ends |
COMMIT or ROLLBACK |
End the transaction and release the locks |
sys.dm_exec_requests |
Shows every request that is waiting, who is blocking it, and how many milliseconds it has been waiting |
$pdo->inTransaction() and $pdo->rollBack() |
Close a transaction that stayed open after an exception |
How one blocking turns into a stuck site
| Stage | What happens | Who holds |
|---|---|---|
| 1 | A transaction stays open and holds one row | The database |
| 2 | A request that needs the row waits in the database, and its script keeps holding the session | Both locks |
| 3 | Every further request from the same browser stops at session_start() |
PHP's session |
| 4 | Every waiting request occupies a PHP process, until the processes run out | No lock: the processes ran out |
Check order when a page is stuck
-
Private window. If the page loads quickly there while the regular window is stuck, you are waiting for the session. If it is stuck there too, you are waiting for the data.
-
The query on the waiting requests, while the page is stuck. A row that comes back is the blocking, together with who is causing it.
-
A query that returns nothing. The stuck request has not reached the database yet. The lock is not there, and you go back to checking the session.
Working rules
-
Release the session the moment you have finished writing to it:
session_write_close()before the slow part of the page. -
A page that only reads from the session opens it with
read_and_close. -
Wrap a late write in an open and a close, before output is sent to the browser.
-
A transaction is always closed:
commitwhen it succeeded,rollBackinside thecatch. -
No slow things inside a transaction: no call to an external service, no sending an email, no creating a file.
What not to do: do not look for load when a page is stuck and the server is free; do not conclude from a quiet database that there is no lock; and do not stick session_write_close() at the top of every file without checking who writes to the session afterwards.
Review questions — with answers
10 questions. Select a question to open its answer.
Question 1: Until when does session_start() hold the lock?
Answer: Until the whole script ends, unless session_write_close() was called earlier. The lock does not come off when reading the data is done.
Question 2: Why did the page load at once in a private window?
Answer: Because the lock belongs to the session, and the session belongs to the cookie. A private window starts without cookies and gets a new session, with a file of its own, that nobody is holding.
Question 3: Why does measuring times from inside the code not show the waiting?
Answer: Because the waiting is inside session_start() itself, before the page's code has started. A measurement that starts after it sees a fast page.
Question 4: What remains after session_write_close()?
Answer: The $_SESSION array in memory. Reading from it works as usual. Writing to it is not saved, and PHP does not warn about it.
Question 5: Who waits when an open transaction holds a row?
Answer: Everyone who touches that row, from any user, browser or window. Whoever does not touch it feels nothing.
Question 6: What is the difference between a PHP session and a SQL Server session?
Answer: In PHP it is the information the server keeps about a user from one request to the next. In SQL Server it is a connection to the database. The two have nothing to do with each other.
Question 7: What does a query on the waiting requests that returned nothing say, while a user is stuck?
Answer: That the stuck request has not reached the database yet. It does not say there is no lock. It says the lock is not there.
Question 8: How does the blocking of one row turn into a whole site that looks stuck?
Answer: The request waiting for the row keeps holding the user's session, so every further request of theirs stops behind it. Every such request occupies a PHP process, and when the processes run out, other users wait too.
Question 9: Why can't you stick session_write_close() at the top of every file?
Answer: Because writing to the session after closing it is not saved. First you check who writes later in the request, and you wrap every such write in an open and a close.
Question 10: What do you not do inside a transaction?
Answer: Slow things that do not have to be in it, such as a call to an external service or sending an email. Every such second is a second in which someone else is waiting for the row.
Appendix for anyone meeting a session and a transaction for the first time
There is no shame at all in arriving here without knowing how a server remembers who you are from page to page. Here is the explanation that lets you continue the story without opening ten other tabs.
How does the server remember me from one request to the next?
Every request from a browser stands on its own, and the server does not know that it came from the same person who asked for the previous page. To remember, for example, that you have already logged in, PHP keeps a small file on the server for every visitor. That is the Session. The browser holds only the file's identifier, in a Cookie: a piece of information it sends back with every request to the same site.
- The browser sends the identifier that is in the cookie — leads to: session_start() opens the file of this identifier and locks it
- session_start() opens the file of this identifier and locks it — leads to: The script runs, reads from $_SESSION and writes to it
- The script runs, reads from $_SESSION and writes to it — leads to: End of the script: the data is saved and the lock is released
- End of the script: the data is saved and the lock is released
The diagram as text
The browser sends the identifier that is in the cookie
|
session_start() opens the file of this identifier and locks it
|
The script runs, reads from $_SESSION and writes to it
|
End of the script: the data is saved and the lock is releasedWhat is special about a private window?
A Private Window starts without the cookies of the regular window. As far as the server is concerned, this is a new visitor: it gets a new identifier and a new session file.
Why lock at all?
When two parties read the same information, change it and write it back, the second write erases the change of the first. A lock puts them in a queue: the second starts only after the first has finished. The price is the waiting.
What is a transaction?
A Transaction is a group of changes in the database that is carried out entirely or cancelled entirely. It is opened by one command and closed by one of two: COMMIT saves the changes, and ROLLBACK cancels them. Until it is closed, the rows it changed are locked to others.
What is a PHP process, and why do they run out?
Every request for a PHP page is handled by a Worker Process: one process handles one request at a time. The server keeps a limited number of such processes. A request that is waiting for a lock does nothing, but its process is occupied until it ends.
What is PDO?
PDO is PHP's access layer to databases. Through it you open a connection, run queries, and open and close transactions: beginTransaction, commit and rollBack.
Glossary of the post
| Term | Short explanation | Why remember it |
|---|---|---|
| Session | Information the server keeps about a visitor from one request to the next | The lock is on it, so the queue belongs to one visitor |
| Cookie | A piece of information the browser sends with every request, holding the session id | All the tabs share it, so they also share the lock |
| Session Lock | The lock PHP puts on the session until the script ends | The first lock: the database does not see it |
| File Lock | A lock the operating system puts on a file | That is how a session stored in files is locked |
| Session Handler | The component that determines where the session is stored: files, Redis or a database | The locking depends on it and on its settings |
| session_write_close() | A function that saves the session and releases the lock | One line that stops holding up the other requests |
| read_and_close | An option of session_start() that reads the data and releases at once |
Suits a page that only reads from the session |
| Private Window | A browser window that starts without the cookies of the regular window | The fastest check: it has a session of its own |
| Transaction | A group of changes in the database that is carried out entirely or cancelled entirely | The rows it changes are locked until it ends |
| COMMIT | The command that ends a transaction and saves the changes | Releases its locks |
| ROLLBACK | The command that ends a transaction and cancels the changes | It releases the locks too |
| Row Lock | A lock on one row in a table | Whoever does not touch the row does not feel it |
| Blocking | A request waiting for a lock that another request holds | The second lock: the database knows who is blocking whom |
| Isolation Level | The setting that determines what one transaction sees of another one's changes | Because of it, even a SELECT can wait for a locked row |
| sys.dm_exec_requests | A SQL Server system view that shows the requests running right now | In it you see who is waiting, for whom, and for how long |
| Worker Process | A PHP process that handles one request at a time | Their number is limited, and a waiting request occupies one of them |
| PDO | PHP's access layer to databases | Through it you open and close a transaction |
What is it waiting for, and who is holding it
Since then, when something gets stuck, my first question has changed. I used to ask why it is slow and go looking for load. Today I ask what it is waiting for, and who is holding it. Sometimes the answer is in the database, and sometimes it is in a small file in the sessions folder that no monitoring tool looks at.
Sources for further reading and checking
-
PHP Manual: session_write_close: the session is locked to prevent concurrent writes, so only one script works on it at any moment.
-
PHP Manual: session_start: the
read_and_closeoption. -
PHP RFC: session_start() options: the discussion that led to the option to read and close at once.
-
Mattias Geniar: PHP session locking: an explanation of the locking of the session file, and how to see it in the operating system.
-
Microsoft Learn: sys.dm_exec_requests: the columns
blocking_session_id,wait_typeandwait_time. -
Microsoft Learn: Transaction locking and row versioning guide: when a read waits for a locked row, and the
READ_COMMITTED_SNAPSHOTsetting. -
PHP Manual: PDO, transactions: the automatic rollback at the end of the script.
-
PHP Manual: the built-in development server: one process, one request at a time.
An email for every new post
A short message with a link whenever a new post is published. Signing up needs a confirmation through a link sent to the address.