0

In Laravel we have an api endpoint that may take a few minutes. It's processing an input in batches and giving a response when all batches are processed. Pseudo-code below.

Sometimes it takes too long for the user, so the user navigates away and the connection is killed client-side. However, the backend processing still continues until the backend tries to return the response with a broken pipe error.

To save ressources, we're looking for a way to check after each batch if the client is still connected with a function like check_if_client_is_still_connected() below. If not, an error is raised and processing is stopped. Is there a way to achieve this ?

function myAPIEndpoint($all_batches){
    $result = [];
    for ($batch in $all_batches) {
       $batch_result = do_something_long($batch);
       $result = $result + $batch_result;
       check_if_client_is_still_connected();
    }
    return result;
}

PS: I know async tasks or web sockets could be more appropriate for long requests, but we have good reasons to use a standard http endpoint for this.

Robycool
  • 1,104
  • 2
  • 14
  • 26
  • maybe read into the queue system (jobs) and max execution time? – online Thomas Oct 05 '21 at 13:23
  • @onlineThomas how would that help to see a client got disconnected ? – Robycool Oct 07 '21 at 12:03
  • Rest requests are fire and forget. There is no persistent connection. So could you please explain what you mean with "still connected"? The reason I bring up Jobs is that you can give a response immediatly and later let the client know the process has finished. – online Thomas Oct 07 '21 at 14:35
  • @onlineThomas I hoped there would be something in the http protocol that would allow us to see that the user cannot receive the response anymore (either because he closed the browser, or if request was cancelled client-side like [here](https://stackoverflow.com/questions/50516438/cancel-previous-request-using-axios-with-vue-js/53213999) ) – Robycool Oct 11 '21 at 07:09

0 Answers0