Lwt thread continues after return

Hello,
I am trying to design an server with asynchronous task.
For some endpoints, the server responds with a 202 “accepted” response and I would like to start here a lwt thread to process a computation.
The way you define a handler for an endpoint in opium is to provide a function that generate the response. the type of the handler Request.t -> Response.t Lwt.t.
A example handler is

(fun _ -> 
        let resp = (Opium.Response.of_json ~status:(`Code 202) (`Assoc [])) in
        Lwt.return resp)

But I would like to start a computation there as a Lwt thread

(fun _ -> 
        let resp = (Opium.Response.of_json ~status:(`Code 200) (`Assoc [])) in
        let _ = (** long computation here **) in
        Lwt.return resp)

Does the handler return immediatly after building the response (and thus before the end of the computation) ?
How can I assure that the long computation remains even after the return of the handler ?

So your result resp does not depend on the computation? What is going to consume the result of the computation and how?

Your:

let _ = (** long computation here **) in

won’t work if the “long computation here” is a blocking computation which is not based on Lwt promises - you shouldn’t run blocking computations in a Lwt “thread”.

If your long computation executes for its side effects and is non-blocking based on Lwt promises, then have a look at Lwt.async and Lwt.dont_wait

Edit: If your long computation is not based on Lwt promises, take a look also at Lwt_preemptive.detach which will execute the computation in a Thread.t thread. There is also a Lwt_domain.detach function which will execute it in a domain.

Yes, my result resp does not depend on the computation. The computation triggers at the end some api call to an other service to register its result.

I’m not familiar with lwt but can’t you simply use Lwt.async (or dont_wait just above) ?

Otherwise you could simply have some kind of global worker queue somewhere and deposit work to do there.

Thank you very much.
Indeed my long computation executes for its side effects and is non-blocking, based on Lwt promises. Lwt.async should do the trick.

That should work fine. The Lwt.async block will run to completion for as long as the promise passed to Lwt_main.run does not resolve.