Search code examples
scalaakkasprayakka-httpfire-and-forget

Do scala futures continue running after response in akka-http?


I have a REST service written in akka-http which exposes a /fire endpoint. When that endpoint is called my service should send a file, usually of ~50MB to a different service. But the /fire endpoint should return immediately to the caller and keep sending the file asynchronously, in a fire-and-forget fashion.

My implementation looks like this

path("fire") {
  post { request: FireRequest =>
      complete {
        sendFile(request.path)
        StatusCodes.OK
      }
    }
  }
}

def sendFile(path: String): Future[Unit] = Future {
  // send the large file to another service
}

I tested it and it works fine.

However, when implemented a similar behaviour with ASP.NET, I needed to use a third party framework (Hangfire) to handle the asynchronous tasks, because the threads generated by a completed request would eventually be killed.

My question is: in my akka-http sendFile is guaranteed to run until successful/failed completion, or there will be cases in which the thread on which it runs will be killed?


Solution

  • It probably depends on the ExecutionContext you are running your Future against.

    If you are using the global ExecutionContext, the behavior is to keep the Future running even after request completion.

    As far as I know, I've never seen any ExecutionContext that would kill/interrupt/cancel the Future thread in case of request completion. The concept of request completion does not exist at the language level but is more related to your http layer framework, so as long as you don't use an ExecutionContext from your http layer framework there's no reason to have such a behavior.