Does Yii's default file session handler cause concurrent request latency only when writing to session?
27.5K reputation · 30 Nov 2021, 20:33 UTC
Goal: determine whether the extra latency observed under concurrent requests in a Yii application stems solely from write operations to the default file‑based session handler, or whether read‑only session accesses also trigger the same blocking behavior.
With Yii’s default file session component, each request locks the session file for its whole duration, causing subsequent requests that touch the session to wait. It is not documented whether the lock is taken only when the session is written to, or also when it is merely read, and whether disabling auto‑start or initiating the session after the first read changes the lock timing. This uncertainty makes it hard to decide if a custom handler is required for read‑only workloads.
Does a read‑only session still block other requests? Does disabling auto‑start and starting the session lazily after the first read eliminate the lock? Is the latency proportional to the amount of data written to the session?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
27,525 reputation · 01 Dec 2021, 03:08 UTC
When does the lock happen?
PHP’s default files handler acquires an exclusive lock as soon as session_start() opens the session file, regardless of whether the script will only read or will later write. Yii simply calls session_start() in its session component, so the lock behavior is identical to plain PHP.
Effect on concurrent traffic
- First request that calls
session_start()locks the file until it callssession_write_close()or the script ends. - Any second request with the same session ID that also calls
session_start()will block until the lock is released. - The block occurs even if the second request only reads session data.
What can you do?
- Call
session_write_close()immediately after you finish reading the session to release the lock early. - Disable
session.auto_start(or configure Yii’sautoStartproperty) so the lock is not taken until you explicitly start the session. - Switch to a non‑file handler (Redis, database) if you need high concurrency with minimal blocking.
Why data size matters little
The lock duration depends on how long the script holds the session open, not on the amount of data written. Even a small write can block for the full request time if session_write_close() is delayed.