Skip to content
Advertisement

configure Apache and MySQL for parallel and cancelable service to clients

We have a client server architecture with Angular on client side and Apache2 PHP PDO and MySQL on the server side. server side exposing an API to clients that gives them data to show.

Some observations :

  1. some API calls can take very long to compute and return response.
  2. server side seem to handle a single request per client at any given time (im seeing only one coresponding query thats being executed in mysql), that limit comes either from apache or from mysql since front-end sending requests in parallel for sure.
  3. front end cancels requests that are not relevant anymore (data being fetched will not be visible)
  4. seems like requests canceled by front end are not canceled in server side and continues to run anyway, i think even if they are queued they will still run when their turn arrives (even though they were cancelled on client side)

Need help to understand :

  1. what exactly is the cause of not having all requests (or at least X>1 requests) run on parallel? can it be changed?
  2. What configurations should i change in either apache or mysql to overcome this?
  3. is there a way to make apache drop cancelled requests? at least those that are still queued and not started?

Thanks!

EDIT

Following @Markus AO comment (Thanks Markus!!!) this was session blocking related… wish i knew about that before!

Advertisement

Answer

OP has a number of tangled problems on the table. However I feel these are worthwhile concerns (having wrestled with them myself), so let’s take this apart. For great justice; main screen turn on:

Solving Concurrent Request Problems

There are several possible problems and solutions with concurrent connections in a (L)AMP stack. Before looking at tuning Apache and MySQL, however, let me gloss a common “mystery” issue that creates concurrence problems; namely, a necessary evil called “PHP Session Locking“.

PHP Session Blocking & Concurrent Requests

In a nutshell: When you use sessions in your application, after calling session_start(), PHP locks the session file stored at your session.save_path directory. This file lock will remain in place until the script ends, or session_write_close() is called. Result: Any subsequent calls by the same user will be queued, rather than concurrently processed, to ensure there’s no session data corruption. (Imagine parallel scripts writing into the same $_SESSION!)

An easy way to demonstrate this is to create a long-running script; then call it in your browser; and then open a new tab, and call it again (or in fact, call any script sharing the same session cookie/ID). You’ll see that the second call won’t execute until the first one is concluded. This is a common cause of strange AJAX lags, especially with parallel AJAX requests from a single page. Processing will be consecutive instead of concurrent. Then, 10 calls at 0.3 sec each will take a total of 3 sec to conclude, and so on. We don’t want that, do we!

You can remedy request blocking caused by PHP session lock by ensuring that:

  1. Scripts using sessions should call session_write_close() once done storing session data. The session lock will be immediately released.
  2. Scripts that don’t require sessions shouldn’t start sessions to begin with.
  3. Scripts that need to only read session data: Using session_start() with ['read_and_close' => true] option will give you a read-only (non-persistent) $_SESSION variable without session locking. (Available since PHP 7.)

Options 1 and 3 will leave you with read access for the $_SESSION variable and release/avoid the session lock. Any changes made to $_SESSION after the session is closed will be silently discarded; no warnings/errors are displayed.

The session lock request blocking issue is only consequential for a single user (using the same session). It has no impact on multi-user concurrence. For further reading, please see:


Apache & MySQL Concurrent Requests

Once upon a time, before realizing PHP was the culprit behind blocking/queuing my concurrent calls, I spent a small aeon in tweaking Apache and MySQL and wondering, what happen?

Apache 2.4 supports 150 concurrent requests by default; any further requests will queue up. There are several settings under the MPM/Multi-Processing Module that you can tune to support the desired level of concurrent connections. Please see:

MySQL has options for max_connections (default 151) and max_user_connections (default unlimited). If your application sends a lot of concurrent requests per user, you’ll want to ensure the global max connections is high enough to ensure a handful of users don’t hog the entire DBMS.

Obviously, you’ll further want to tune these settings in light of your server CPU/RAM specs. (The calculations for which are beyond this answer.) Your concurrency issues probably aren’t caused by too many open TCP sockets, but hey, you never know…


Canceling Requests to Apache/PHP/MySQL

We don’t have much to go on as far as your application’s specific wiring, but I understand from the comments that as it stands, a user can cancel a request at the front-end, but no back-end action is taken. (Ie. any back-end response is simply ignored/discarded.)

“Is there a way to make Apache drop cancelled requests?” I’m assuming that your front-end sends the requests directly and without delay to Apache; and onward to PHP > MySQL > PHP > Apache. In that case, no, you can’t really have Apache cancel the request that it’s already received; or you could hit “stop”, but chances are PHP and MySQL are already munching it away…

Holding a “Cancel Window”

However, you could program a “cancel window” lag into your front-end, where requests are only passed on to Apache after e.g. a 0.5-second sleep waiting for a possible cancel. This may or may not have a negative impact on the UX; may be worth implementing to save server resources if a significant portion of requests are canceled. This assumes an UI with Javascript. If you’re getting direct HTTP calls to API, you could have a “sleepy proxy receiver” instead.

Using a “Cancel Controller”

How would one cancel PHP/MySQL processes? This is obviously only feasible/doable if calls to your API result in a processing time of any significant duration. If the back-end takes 0.28 sec to process, and user cancels after 0.3 seconds, then there isn’t much left to cancel, is there.

However, if you do have scripts that may run for longer, say into a couple of seconds. You could always find relevant break-points in your code, where you have a “not-canceled” check or a kill/rollback routine. Basically, you’d have the following flow:

  • Front-end sends request with unique ID to main script
  • PHP script begins the long march for building a response
  • On cancel: Front-end re-sends the ID to a light-weight cancel controller
  • Cancel controller logs ID to temporary file/database/wherever
  • PHP checks at break-points if there’s a cancel request for current process
  • On cancel, PHP executes a kill/rollback routine instead of further processing

This sort of “cancel watch” will obviously create some overhead, and as such you may want to only incorporate this into heavier scripts, to ensure you actually save some processing time in the big picture. Further, you’d only want at most a couple of breakpoints at significant junctions. For read requests, you could just kill the process; but for write requests, you’d probably want to have a graceful rollback to ensure data integrity in your system.

You can also cancel/kill a long-running MySQL thread, already initiated by PHP, with mysqli::kill. For this to make sense, you’d want to run it as MYSQLI_ASYNC, so PHP’s around to pull the plug. PDO doesn’t seem to have a native equivalent for either async queries or kill. Came across $pdo->query('KILL CONNECTION_ID()'); and PHP Asynchronous MySQL Query (see answer for PDO). Haven’t tested these myself. Also see: Kill MySQL query on user abort

PHP Connection Handling

As an alternative to a controller that passes the cancel signal “from the side”, you could look into PHP Connection Handling and poll for aborted connection status at your cancel check-points with connection_aborted(). (See “MySQL kill” link above for a code example.)

A CONNECTION_ABORTED state follows if a user clicks the “stop” button in their browser. PHP has a ignore_user_abort() setting, default “Off”, which should abort a script on user-abort. (In my experience though, if I have a rogue script and session lock is on, I can’t do anything until it times out, even when I hit “stop” in the browser. Go figure.)

If you have “ignore user abort” on false, ie. the PHP script terminates on user abort, be aware that this will be a wholly uncontrolled termination, unless you have register_shutdown_function() implemented. Even so, you’d have to flag check-points in your code for your shutdown function to be able to “rewind the clock” from the termination point onward. Also note this caveat:

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush(). ~ PHP Manual on ignore_user_abort

I have no experience with implementing “user abort” over AJAX/JS. For a starting point, see: Abort AJAX Request and Cancel an HTTP fetch() request. Not sure how/if they register with PHP. If you decide to travel down this road, please return and update us with your code / research!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement