1

I want requests to timeout after some time, say 20 seconds. If the application takes longer than 20 seconds to send a response, Phoenix should cancel execution and immediately reply with some error (preferably an HTTP 503).

I've scoured the Phoenix docs but couldn't find any mention of a request timeout option. It looks like Cowboy has a :timeout option, which I tried setting to 10 ms, but it still allowed a request to take 8951 ms:

config :app, SomeApp.Endpoint,
  http: [port: 4000, timeout: 10]

It turns out the Cowboy docs define this option as:

Time in ms with no requests before Cowboy closes the connection.

which is not what I'm looking for.

Is it possible to set a request timeout in Phoenix?

2 Answers 2

2

This is by no means a responsibility of the web-server/framework. Cowboy has no clue (and it should not have!) about what’s going on in the application, it serves the connections. Phoenix could take care of that, but it would violate SRP. After all, the aforementioned timeout is more about the business logic. Imagine cowboy/phoenix would be trying to handle timeout: what should happen with the currently executing handler?

That said, the application should handle this kind of timeout and it’s relatively easy: one just needs to wrap the underlying execution in the task with a timeout you want. That way it would be flexible, reliable and you might specify which controllers/actions should behave that way, and which should not.

In a pseudocode (it’s a real code, but I did not test it):

def create(conn, params) do # or any other action
  fn -> prepare_result end
  |> Task.async()
  |> Task.yield(10)  # ⇐ HERE!!!
  |> case do
    {:ok, result} -> # success
      conn
      |> put_status(200)
      |> json(%{ok: result})
    nil -> # not finished yet; do smth with the task itself!
      conn
      |> put_status(503)
      |> json(%{error: :timeout})
    {:exit, reason} -> # should not happen [see Task.yield/2 docs]
      conn
      |> put_status(500) # internal server error; unexpected
      |> json(%{error: reason})
  end
end

Task.yield/2.


Sidenote: of course, if you need this behaviour across the whole application, just declare a macro doing that, or like.

2
0

If this..

config :app, SomeApp.Endpoint,
  http: [port: 4000, timeout: 10]

doesn't work.. Try changing to..

config :app, SomeApp.Endpoint,
  http: [port: 4000, protocol_options: [idle_timeout: 10_000]]

1
  • Worth noting that idle_timeout is only available in Cowboy 2.0+ Commented Oct 1, 2020 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.