Video in progress

What happens if you don't set a timeout on every call to an external service?

If the external service stops responding, your threads wait forever. The thread pool and connection pool slowly fill up, and in the end your service can't answer even requests that have nothing to do with it.

📖 Answer

This is a very common disaster scenario on prod. Tomcat has 200 threads by default. The payment provider "hangs" — every payment request takes a thread and waits. Within a few minutes all 200 threads are busy, and now neither the catalog page nor login opens. One external service took down your whole application.

Many HTTP clients have no default timeout or a very large one, so always set it explicitly:

HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(2))
        .build();

HttpRequest request = HttpRequest.newBuilder(URI.create(url))
        .timeout(Duration.ofSeconds(5))   // limit for waiting on the response
        .build();

Tell the two kinds of timeout apart: connect timeout (establishing the connection) and read/response timeout (the response arriving). You need both.

Choose the value based on the external service's usual p99: if it normally answers in 300 ms, there's no point waiting 30 seconds. The database needs timeouts too — connectionTimeout in HikariCP, and statement_timeout for queries.