Laravel High CPU Usage Due to 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 up to 100%, making everything slower.

I knew that Laravel needs more CPU than PHP, because of the service container and Reflection Magic it does. But, this much?

Both PHP and Laravel systems worked exactly the same way except for session storage. The old system stored sessions in the database while the new system used the file system. I just ls ed to the session storage directory and there were thousands of files.

I was not sure but gave it a shot. I created a table to save Laravel sessions and changed SESSION_DRIVER to the database (Instructions are here).

CPU usage decreased to around 20-30%!

So, it is safe to say that in larger volumes, relational databases are more optimized to save data with high I/O frequency than saving in the filesystem.

I should also mention that using in-memory key-value storage like Redis will be more efficient than MYSQL. In our case, this requires a larger RAM to save all those millions of sessions of Hyvor Talk users. So, we will keep saving sessions in MYSQL for now. We will migrate to Redis only if required.

Newsletter

Comments

Published with Hyvor Blogs