Posts Tagged ‘fastcgi_finish_request’

problem with multi fastcgi_finish_request requests in nginx

May 1st, 2013

The php server nginx has a very handy function fastcgi_finish_request(). If fastcgi_finish_request is called in a function, the function will return immidiately but still do the job in background. So it is intuitive to think of using fastcgi_finish_request() to do some jobs in parallel when needed.

However, when a process call the fastcgi_finish_request() many times in a row, the later calls have to wait for the previous call to finish. So it’s not such a big help when you call fastcgi_finish_request() many times in a row, because all these requests will be executed in sequence. Rather you should put all the long calls in a fastcgi_finish_request() call.

For example:

function a() {
     long_work(); // 1st call
     // if we write a log here, we'll find 1st call immediately returns.
     long_work(); // 2nd call
     // if we write a log here, we'll find this 2nd call will have to wait for 10s before it returns.
}

function long_work() {
    sleep(5);
    fastcgi_finish_request();
}

A workaround to mimic multithread with fastcgi_finish_request() is to use curl. We put the long work in a php file, and then use curl to request the php file.

// ------ long_work.php ----------
long_work();
function long_work() {
    sleep(5);
    fastcgi_finish_request();
}


And then in function a(), we can request long_work many times.

function a() {
    // curl( 'http://localhost/long_work.php' ); // 1st call
    // curl( 'http://localhost/long_work.php' ); // 2nd call
}