Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between node.js HTTP Server, Request, and Response Timeouts

When it comes to timing out HTTP requests, it looks like node.js has three separate timeouts:

  1. server.setTimeout http://nodejs.org/api/http.html#http_server_settimeout_msecs_callback
  2. request.setTimeout http://nodejs.org/api/http.html#http_request_settimeout_timeout_callback
  3. response.setTimeout http://nodejs.org/api/http.html#http_response_settimeout_msecs_callback

Can anyone clarify what the difference is between each of these methods and why someone would want to use each one?

like image 726
Kirk Ouimet Avatar asked Oct 21 '14 18:10

Kirk Ouimet


1 Answers

  1. You are running a web server in your node.js app. This determines how long node will leave a client request connection open with no traffic before closing it due to idle timeout. An example is a user loses power in their house while downloading a large file from your app. You set this once and it will apply to all client connections your server receives.
  2. This is for outgoing requests from your node program to a remote web server. So you write a scraper to download a file and your Internet connection dies while downloading. This determines when node finally gives up on waiting for data from the remote side. This will only affect a specific request as the underlying TCP connection will be closed and each outgoing request will get a distinct TCP connection.
  3. Since the HTTP request and corresponding response occur via the same underlying TCP socket, my understanding is req.setTimeout and res.setTimeout ultimately result in the same underlying system call that sets the timeout on the TCP socket itself using the corresponding libuv/os calls. So I think both are equivalent and you can you whichever one is more convenient or whichever one feels semantically clearer to you. I could be wrong about this though so if anyone else knows for certainly feel free to correct me.

Generally the defaults are reasonable. However, you might want to set these longer if you knew you had a lot of clients on very slow or flakey connections (you serve mobile phones in remote areas or satellites or whatever), and connections that were actually still viable we being closed due to timeout. You might want to set them shorter if you knew your clients were well-connected (like servers in the same datacenter), and you wanted to free up resources more aggressively.

like image 101
Peter Lyons Avatar answered Sep 18 '22 10:09

Peter Lyons