Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP concurrent changes on session variable for same user?

Tags:

php

session

Suppose we have a user variable $_SESSION['variable'] that may or may not be modified as the user access a page.

Suppose the same user has several browser windows open and somehow makes simultaneous requests to the server that result on changes to the session variable.

Questions:

How does the server "queue" these changes, since they are targeted at the same variable? Is there a potential for server error here?

Is there a way to "lock" the session variable for reading/writing in order to implement some kind of status check before changing its value?

EDIT ( thanks Unheilig for the cleanup)

Regarding the "queueing", I am interested in what happens if two requests arrive at the same time:

Change X to 1

Change X to 2

I know this doesn't seem a real world scenario, but it just came to my mind when designing something. It could become a problem if the system allows too many concurrent requests from the same user.

like image 894
noderman Avatar asked Feb 19 '26 14:02

noderman


1 Answers

Each individual PHP Session is 'locked' between the call to session_start() and either the call to session_write_close() or the end of the request, whichever is sooner.

Most of the time you would never notice this behaviour.

However, if you have a site which does make many concurrent requests* then these requests would appear to queue in first-come-first-served order.

To be clear; in a typical Apache/PHP setup your requests will come in to the server and start your PHP executions concurrently. It is the session_start() call that will block/pause/wait/queue because it's waiting to gain the file-lock on the session file (or similar depending on your session_hander).

To increase request throughput or reduce waiting requests therefore:

  • Open and close the session (session_start(), do_work(), session_write_close()) as rapidly as possible; to reduce the time the session is locked for writing.
  • Make sure you're not leaving the session open on requests that are doing long work (accessing 3rd party APIs, generating or manipulating documents, running long database queries etc).. unless absolutely necessary.
  • Avoid, where possible, touching the session at all. Be as RESTful as possible.
  • Manage the queuing and debouncing of requests as elegantly as possible on the client side of the application

Hope that helps.

J.

*Ajax & Frame/iFrame heavy applications often exhibit this problem.

like image 142
Jim Morrison Avatar answered Feb 22 '26 04:02

Jim Morrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!