The Developer Day | Staying Curious

TAG | ajax



Anti Asynchronous AJAX calls and PHP sessions

Few days ago we found a strange bug in one of our applications we are developing. We were creating a certain feature that made up to 2 - 6 asynchronous ajax calls when certain pages were hit. Those ajax requests contact various services providers and it takes a different amount of time for each one of them to respond. We found it odd that none of the calls were actually asynchronous and they were starting to execute one after another. For example we fire 3 asynchronous ajax calls:

  • ajax call 1 takes 2sec.
  • ajax call 2 takes 3 sec. but responds after 5 sec. only
  • ajax call 3 takes 4 sec. but responds after 9 sec. only

It didn’t took long to figure out that it had something to do with our php handler scripts that are accepting these ajax calls. We found out that the session_start() function call did not allow these scrips to run in paralel. It soon became clear that two php scripts can’t use the same session in paralel because without locking they could both do some changes to session and one script would override other script’s changes.

Turns out there is a function for exactly these kinds of situations in PHP and it’s named session_write_close(); It’s purpose is to write session data and end session. After it is done writing it releases the lock for other scripts to use the session. So now our php handler scripts initialize the session to check that the user is logged in, writes the session changes and ends it, contacts services providers and then starts the session again to make the final session changes. That way one script doesn’t hold the session locked for it’s whole execution time.

, , , , Hide

Find it!

Theme Design by