Search code examples
phplaravelsessionload-balancingsession-cookies

Multiple Load-balanced Laravel Applications on same server causing session timeout issues


I recently took over an old, server-side rendered Laravel 5.6 app and upgraded it to version 8 running on an Nginx server with PHP 7.4.

The setup consists of:

  • 2 servers sitting behind a load balancer
  • The database sitting on a third server that both servers are accessing
  • Both servers host several installations of the code-base for each client
  • All instances use the database for their sessions and use a unique "SESSION_COOKIE_NAME" declared in the .env file.
  • Each instance of the application is sitting in a sub-folder inside /var/www/ for eg /var/www/example.med***.com

.env

SESSION_DRIVER=database
SESSION_TIMEOUT=true
SESSION_TIMEOUT=86400
SESSION_LIFETIME=120
SESSION_COOKIE_NAME="LOCAL_SESSION" // different for every instance of the app
SESSION_DOMAIN=".med***.com"

With the app being rather old, the dashboard, which is being used to display records, refreshes on a timeout every 30 seconds, thus making a request to the server, which has a timeout of 24 hours.

The users are reporting that the app will randomly log them out of the system, even though each logged-in user is making enough requests to ensure the timeout limit is not reached.

Could this be a load balancer issue or am I missing a setting?


Solution

  • The issue ended up being rather simple.

    Laravel uses the app key to encrypt session cookies. The instances for each application on their respective servers were using different app keys and therefore if server 1 encrypted the cookies and the next request went to server 2, the cookies were invalid.

    This seems to have resolved the issue.