Skip to Content

Ruby - the context of HTTP requests

Posted on

HTTP requests

A successful HTTP request has 3 main steps:

  1. Open a TCP connection to the endpoint.
  2. Send a request over the connection.
  3. Read the response written to the connection.

In each step, if there is something wrong, Ruby will raise different errors. For example:

  • Net::OpenTimeout is raised when a connection cannot be created within a specified amount of time. It means that the TCP connection takes time to set up.
  • Net::ReadTimeout is raised in step 3, because it takes time for server to send a response after the connection is set up.

To avoid those error, just follow the rule:

Always use a timeout for http requests.

Example with faraday gem:

# Request options can be passed to the connection constructor and will be applied to all requests.
request_options = {
  params_encoder: Faraday::FlatParamsEncoder,
  timeout: 5
}

conn = Faraday.new(request: request_options) do |faraday|
  # ...
end

# You can then override them on a per-request basis.
conn.get('/foo') do |req|
  req.options.timeout = 10
end
Option Type Default Description
:timeout Integer, Float nil (adapter default) The max number of seconds to wait for the request to complete.
:open_timeout Integer, Float nil (adapter default) The max number of seconds to wait for the connection to be established.
:read_timeout Integer, Float nil (adapter default) The max number of seconds to wait for one block to be read.
:write_timeout Integer, Float nil (adapter default) The max number of seconds to wait for one block to be written.

References

comments powered by Disqus