Laravel High CPU Usage Because of File-based Session Storage

I recently re-wrote the Hyvor login. The old app was a legacy PHP application. The new one was written in Laravel.

All our apps (Hyvor Talk, Hyvor Blogs, etc.) use the same auth system. So, it handles a few million internal API requests per day and saves a LOT of sessions. However, all this was handled by a 4GB, 2vCPU VPS on DigitalOcean. The CPU usage of the old app was around 15-20%.

So, I decided to use the same server capacity for the new Laravel app. However, CPU usage bumped upto 100%, making everything slower.

My first guess was maybe Laravel needs more CPU than just using PHP. However, later I noticed that our old system stored sessions in the database while the new system used the file system. I just lsed the session directory in the storage and there were thousands of files.

I guessed maybe that was the issue. And, it was! I created a table to save Laravel sessions and changed SESSION_DRIVER to database (Instructions are here).

CPU usage decreased to around 20-30%.

My conclusion is that a relational database handles large amounts of data better. Opening, reading, and writing to bare files require more CPU power. So, if you have a high CPU problem with your application, saving sessions (or other data) in the filesystem and reading them frequently MAY be the problem - but remember, there are many other possible reasons.

I should also mention that using in-memory key-value storage like Redis will make it faster. However, for now, we’ll stay with the MYSQL database.

Tagged: Laravel MYSQL
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
101