Session Locking? Slow Query Log Filled With Session Query?

Default session mechanism in php is locking/blocking. For example there are 5 request from same client/people (with same session id) concurrently that use session. All 5 request cannot run concurrently, but rather only one request running, the other waiting until the other request with same session id done (queue).

The purpose is to avoid race condition. For example there is a session variable named jk that count total item in cart. User add item a and b. In the beginning, there are 10 item. After added by 1 item a, and then 1 item b, the total item became 12. With sesion locking, the result is 12. But with no locking, the result not guantreed to be 12, but can be 11

Actually there is no problem with time delay for queuing up because blocking/locking is not significant. But if in other request there is a query that take a long time, the effect will be feel significantly.

For example time between request is 0.5 second. On 1 page there are 5 ajax, so will be take time 2.5 second. If there are slow query cause one request take 4 second, the other request will wait for that request to done, so page will load in 6 second.

The webserver utility will be increased because receive many connection that wait other request to be done.

Solution 0

Fix other database query. There must be other query beside session locking that cause this slow performance.

Solution 1

There are many way to solve the problem

  • Fixed the request that take a long time (optimization in code or databsase query)
  • use session_write_close in php (after call that method, the session only can be read, can’t be write/update)
  • Use redis because dont have locking mechanism

Solution 2

I think session locking is not best practice today. For some request/feature that need locking mechanism, we can lock it with database transaction, so other request will not be affected.

This writing was originated in my blog written in Bahasa Indonesia :

Interested in Software Engineering, Devops, Smart Contract. 🌐: abdillah.my.id . Made with ☕ from 🇲🇨