The background processing

I’m curious if I can respond to user and continue data processing after that. The real life example could be the following: the user uploads the document, the validation is OK, document saved and I can return the response. Besides I need to do extra job, like document content indexation in search engine, etc.

I think about following solution. The last MvcEvent is ‘finish’. The last (by priority) listener is Laminas\Mvc\SendResponseListener. As I understand after it does its work the response is ready to be flushed. So I create my own MvcEvent::EVENT_FINISH listener with priority lower than SendResponseListener has. In my listener I do:

if (session_id()) {
    session_write_close();
}
ob_end_flush();
ob_flush();
flush();
fastcgi_finish_request();

// do the other stuff in background

I’d like to know if I’m not making some big mistake here. So far everything looks ok and it even works in the way I want.

ps: I know about alternative solution with queues and extra process that will do such kind of workload.

Heyo,

Overall, using fastcgi_finish_request(); works, but be aware:

  1. works only under PHP-FPM - careful not to migrate to MOD-PHP, Swoole or RoadRunner by leaving this in place!
  2. the PHP-FPM process will be kept “busy” until background processing is done, so there’s a concurrency limit caused by max spawned processes

If these are not a problem, go ahead (and document your choice).

Alternatively, use a more traditional “push work to a queue, do it in a background worker” instead :slight_smile: