Video in progress

What is a timeout, and why should every network call have one?

A timeout is a limit on how long to wait for a response. Without it, a slow or hung service ties up the caller's threads indefinitely and eventually brings the caller down too.

📖 Answer

A network call ends in one of three ways: a response came, an error came, or nothing came. The third case is the most dangerous.

Imagine Tomcat has 200 threads. payment-service hangs and doesn't respond. Every request takes a thread and waits forever. Within a minute or two all 200 threads are busy, and now order-service doesn't even answer /health.

There are two kinds of timeouts:

  • connect timeout: waiting for the connection to be established (1-2 seconds is usually enough);
  • read (response) timeout: waiting for the response after connecting.
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(1));
factory.setReadTimeout(Duration.ofSeconds(3));

RestClient client = builder.requestFactory(factory).build();

Choose the value from metrics, not by guessing: if the service's p99 response time is 400 ms, a 30-second timeout makes no sense.