The labs on this site need JavaScript to run. The same content is written out below.
Learn › Spring › Other features
Calling external APIs and timeouts
When a call to another server gets no answer, how long does it wait?
Why it exists — The caller cannot tell whether the server on the other side of the network is slow, is down, or has lost a packet. An HTTP call with no limit can wait until the operating system gives up in the connect phase, and can wait forever in the phase of reading the response. A timeout puts an end, "up to here", on this waiting, so a call that gets no answer finishes as a failure and the thread is returned to other requests.
Where it's used today — Where you call another company's API, such as payment, text messaging, and map search, and where services call each other over HTTP, you set both a connect timeout and a read timeout. You set the values more generously than the time the other side usually takes to answer, and shorter than the time the user can wait. They are also often used together with a circuit breaker (Resilience4j and others), which stops calling for a while when failures continue.
The order server calls the API of the payment server. The calling thread stops and waits until the result comes back, and a timeout sets how long it waits before giving up. There are two timeouts. The connect timeout measures the time until the connection is established, and the read timeout is the limit on how long it waits, after the connection is established, while no data arrives. If you do not set them, the client never gives up on its own. Change the state of the remote server and the timeouts to see which timeout expires and when. The 2 seconds, 3 seconds, and 10 seconds on the screen are example values.
Checked against real execution · The code on the screen (the RestClient of Spring 7.0.9, timeouts of 2 and 3 seconds) was run in a Linux container and all 24 combinations were checked. The remote side was a Spring Boot 4.1.1 server, a container with no listening program, and a container where iptables drops the packets
Concepts in this lab
- Connect timeout and read timeout
- These are the two time limits that set how long a call to another server waits before giving up. The connect timeout is the limit on waiting until the TCP connection to the remote server is established, and the read timeout is the limit on waiting with no response data arriving after the connection is established. The two measure different intervals, so setting only the connect timeout does not protect against the case where the connection is made but the response is late. If no timeout is set, a slow remote server keeps the calling thread occupied, and when the thread pool runs out, the failure spreads to the calling side. A read timeout does not mean that the remote server did not handle the request, so you must watch out for duplicate handling when you send the same request again.
- RestClient
- Why it exists — RestTemplate required passing long arguments to different methods for different cases, such as getForObject and exchange, and WebClient, which chains methods, needed a reactive library. RestClient lets you use the chaining style in synchronous calls.
- Where it's used today — You use it when a Spring Boot server calls a payment API or the HTTP API of another service. You get the RestClient.Builder that Spring Boot has prepared injected, set the base URL and headers, and use it; if you need to handle many calls without tying up threads, you use WebClient.
- This is the client that Spring provides for calling the HTTP API of another server. You build a request by chaining methods, as in client.get().uri(url).retrieve().body(type), and a message converter converts the response body to an object and returns it. It is synchronous, which means that the calling thread waits until the response arrives, and it is the successor to RestTemplate, which has been in use for a long time. A 4xx response is turned into an HttpClientErrorException, a 5xx response into an HttpServerErrorException, and a connection failure or a timeout into a ResourceAccessException, and that exception is thrown. The actual communication is done by a request factory, and timeouts are also set on the request factory.
- Tomcat's threading model
- Why it exists — If one thread handles a request all the way through, even code that waits for a database response can be written from top to bottom in order, without being split into callbacks. Tomcat takes those threads from a pool created in advance and sets an upper limit on their number, so threads do not grow endlessly even when requests pile up.
- Where it's used today — A Spring MVC service with slow external calls or many concurrent requests tunes server.tomcat.threads.max together with the size of the database connection pool. When requests seem to be stuck, you look in a thread dump to see at which line a request processing thread such as http-nio-8080-exec-1 is waiting.
- Tomcat manages its request processing threads in a pool, and one thread takes one request and handles it until the response is finished. The number of requests it can handle at the same time is limited by the maximum number of threads (200 by default). Unlike the standard Java ThreadPoolExecutor, when no thread is idle it adds threads up to the maximum first, and new requests wait only when all of them are in use. A thread stays occupied even while the request is waiting on a database or an external call.
- Three-way handshake
- Why it exists — If data is sent right away without confirming the connection, it is sent without knowing whether the other side is ready to receive, or where to start counting the numbers attached to each piece. The three-way handshake lets both sides confirm each other's starting numbers in three exchanges, which sets the basis for counting missing pieces and order afterward.
- Where it's used today — Developers do not call it directly, but the connection timeout is the limit on how long to wait for this process to finish. If a firewall silently drops the SYN, there is no reply and the wait lasts until this timeout, and if no program is waiting on the other side's port, Connection refused appears right away.
- The three-step process used to establish a TCP connection. The client sends a connection request (SYN), the server sends its acceptance together with its own connection request (SYN+ACK), and the client acknowledges it (ACK). After both sides have confirmed that they can send to and receive from each other, data transfer starts.
- HTTP status codes
- Why it exists — If results were reported only as text in the body, each server would write them differently, and browsers, proxies, and monitoring tools could not tell whether a request succeeded. A status code reports the result as a fixed number, so these tools can do caching, retries, and error counting without being adjusted for each server.
- Where it's used today — It is used to branch handling by the kind of error, such as a frontend that sends the user to the login screen on a 401 and to a "page not found" notice on a 404. In operations, you watch the ratio of 5xx responses and, if it suddenly rises, treat it as an outage and send an alert.
- A three-digit number that shows the result of the server's handling of a request. 2xx means success, 3xx means a move to another location (redirection), 4xx means a problem with the client's request, and 5xx means an error on the server side. Common ones are 200 (success), 201 (created), 400 (bad request), 401 (authentication required), 403 (no permission), 404 (not found), and 500 (server error).
Try these
- Default settings — Only the connect timeout is set. It does not cover a slow response, so the thread waits 10 seconds.
- Setting the read timeout as well — If the response does not arrive within 3 seconds, the thread stops waiting.
- Server that does not answer, no timeouts — The thread stays occupied until the operating system gives up.
- Server that does not answer, read timeout only — The read timeout is of no use during the connection phase.
- Server that does not answer, connect timeout — The call gives up after 2 seconds and releases the thread.
- When the server program is not running — The refusal comes back right away, so the call does not wait for a timeout.
- When a 404 or 500 comes back — The response arrived, but in the calling code it shows up as an exception.
Running with the default settings
- Calling client.get() ... body(String.class): One thread of the order server starts calling the payment server. RestClient holds this thread until the result comes back, so during that time the thread cannot handle other requests.
- Connection attempt: Before the HTTP request can be sent, a TCP connection to the payment server must be established. The connection request is sent. The 2-second connect timeout starts counting from this point.
- Connection established: The payment server accepts the connection right away. The job of the connect timeout ends here. However long things take after this, the connect timeout does not expire.
- GET /payments/1 sent: The request is sent over the established connection, and the thread waits for the response. No read timeout is set.
- No read timeout: Nothing stops the wait. The job of the connect timeout (2 seconds) ended when the connection was established, so it is of no use here. The thread stays occupied for 10 seconds, until the response arrives.
- Response arrives: After 10 seconds, the payment server sends a 200 response. RestClient converts the body to a string and returns it. The result is a success, but one thread could do no other work for 10 seconds.
Result of this run
- If you do not set a read timeout, the wait has no limit. When the payment server slows down, the threads of the order server stay occupied for that long, and when many requests come in at once, all the threads in the thread pool become occupied and the order server itself can no longer respond. The connect timeout alone does not protect against a slow response. The two timeouts measure different intervals, so you must set both.
Code
// Only the lines inside main are shown (class, main declaration, and imports omitted)
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(2)); // connect timeout
// no read timeout is set (waits with no limit)
RestClient client = RestClient.builder()
.requestFactory(factory)
.build();
try {
String body = client.get()
.uri("http://pay-server/payments/1")
.retrieve()
.body(String.class); // this thread waits here until the result comes back
} catch (HttpClientErrorException e) { // 4xx response
} catch (HttpServerErrorException e) { // 5xx response
} catch (ResourceAccessException e) { // connection failure, timeout
}
Assumptions of this model
All 24 combinations were actually called with the code on the screen as it is (the RestClient of Spring Framework 7.0.9, with SimpleClientHttpRequestFactory as the request factory, a connect timeout of 2 seconds, and a read timeout of 3 seconds), and it was confirmed that the result, the kind of exception, the cause of the exception, the time waited, and whether the remote server handled the request match the screen. The caller and the remote server are Linux containers on a Docker network on one PC (Java 21, Linux kernel 6.18). The remote server is a Spring Boot 4.1.1 server (embedded Tomcat), and for "Slow" it responds 10 seconds after it receives the request. "Connection refused" was checked with a container that is running but has no program listening on that port, and "No answer to the connection request" was checked with a container where the same server is running but a firewall (iptables 1.8.13) silently drops the packets that come to that port. "Right away" on the screen was under 1 second in every real run (the longest was 0.6 seconds, and because a new Java process is started for each combination, it includes the time to prepare code that runs for the first time). The roughly 135 seconds that the operating system took to give up when there was no connect timeout is the value measured in this Linux environment, and it differs depending on the operating system and its settings (on Windows 11, a call to 192.0.2.1, an address that is not assigned to any machine, took about 21 seconds, but that value can change with the network the PC is on, so it was not used for the check). That the wait has no limit when no timeout is set was confirmed by execution only as far as the timeout value put on the connection being 0, and that 0 means no limit follows the java.net.URLConnection documentation. Execution showed the call waiting for a response that arrives after 10 seconds. The read timeout is not a limit on the time the whole response takes but a limit on the time spent waiting with no data arriving. A response that arrives a little at a time, once every second over 6 seconds, was confirmed to be received to the end even with a read timeout of 3 seconds. The situation where requests pile up and all the threads are occupied was checked by sending 2 payment requests to an order server whose Tomcat worker threads were reduced to 2, and then, 0.5 seconds later, sending a request that has nothing to do with payment. That request got its answer after about 9.5 seconds with no read timeout, and after about 2.5 seconds with a read timeout of 3 seconds. How timeouts are set and what their defaults are differ depending on the kind of request factory. The model is simplified to the case where a new connection is established for every call (the check also did not reuse connections), and it does not cover a connection pool that reuses connections and its wait time, retries, or circuit breakers.
Previous lab: Testing · Next lab: Cache abstraction