Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Fundamentals › Architecture and operations

Calling another server

How is a server calling another server different from calling a method?

Why it exists — If all features are in one program, changing only the payment part means restarting the whole program, and features run by another company, such as card payment or sending text messages, cannot be done by my program alone. A remote call hands such features to a separately running server, sends a request over the network, and receives the result, so that different programs can divide the work among themselves.

Where it's used today — It is used when a shopping mall server asks the server of a payment company to process a payment, or asks the server of another service for information such as maps or weather. In a service whose features are split across several servers, it is common for the order server to call the member server or the stock server. In Spring, you send the request with the RestClient that Spring provides, set a connect timeout and a read timeout on the request factory, and handle the ResourceAccessException that comes from a connection failure or a timeout. To keep the thread that sent the request from standing still while it waits for the answer, you use WebClient, and work whose answer need not be received right away is sometimes passed to a message queue.

A large service sometimes splits its features among several servers. If the order server and the payment server are different programs that run separately, then instead of calling a method to make a payment, the code of the order server has to send a request (POST /pay) to the payment server over the network. In Spring, this request is sent with the RestClient that Spring provides. The code on the screen has two versions. If the payment feature is in the same program, you call the method of a PayService object (a class made for this example) with payService.pay(), and if it is on another server, you call the payment server with restClient.post().uri(...).retrieve().body(String.class). Both get a String, "Payment done", back, but when you call a server across a network, the other side may be off and refuse the connection, and if the other side is slow, you have to wait for the answer. So when you create the RestClient you decide how long to wait for an answer (the timeout), and you catch the ResourceAccessException that comes when the call fails. The result was made by compiling the code on the screen as it is and running it, with a small server standing in for the payment server started separately.

Checked against real execution · Compiled and ran the code on the screen as it is with the RestClient of Spring Framework 7.0.9, with a small HTTP server standing in for the payment server (normal, slow, and off), and checked twelve combinations (verify/spring/cmp_remote_basic.js)

Concepts in this lab

Remote call
A remote call (a call between servers) is when the program of one server sends a request to another server over the network and uses a feature of that server. Section 3.3 of RFC 9110 calls a program that makes a connection and sends a request a client, and a program that accepts a connection and responds a server, and says that the same program can be a client on one connection and a server on another. So an order server is a server to a browser and a client to a payment server. Unlike a method call inside the same program, the other side may be off and the connection may fail, if the other side is slow you have to wait until the answer comes, and the answer may never come. So the code that makes the call has to decide how long to wait and what to do when it fails. In Spring, you make such a call with the RestClient that Spring provides, and the waiting time is set on the request factory.
Method invocation
A method invocation, or calling a method, is an expression that runs the body of a method. You write the method name, then parentheses, and inside the parentheses the values to pass, as in add(2, 3). For each call the compiler looks for a method with that name and, for a method with a fixed number of arguments, checks that the number of values passed is the same as the number of parameters. If there is no method with that name, or the numbers do not match so that no method can be called at all, it is a compile-time error. At run time the values passed are evaluated in order from the left, they are stored in newly created parameter variables, and then the body runs. If you call the same method twice, the body also runs twice.
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.
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.
ResourceAccessException
Why it exists — A call to another server can fail because of the network, and the kind of that failure differs depending on which HTTP client library you use. Spring throws it as one exception, so that the calling code can catch "no response was obtained" in one place regardless of the library.
Where it's used today — In the code that calls another server, you catch it with catch (ResourceAccessException e), and then send the request again, use a default value, or tell the user to try again in a moment. When failures continue, a circuit breaker sometimes counts this exception and stops the calls for a while.
ResourceAccessException is the exception that Spring (spring-web) throws when an I/O error occurs while calling another server with RestClient and no response could be obtained. This is the case when the other server is off and the connection is refused, or when the timeout you set has passed and the wait is cut off. It is a RuntimeException that inherits from RestClientException, so catching it is not forced, and you look at getCause() to see what actually happened. In the run for this lab, the cause was java.net.ConnectException when the connection was refused and java.net.SocketTimeoutException when the read timeout was hit. When the other side did answer but with an error status code such as 404 or 500, it arrives not as this exception but as HttpClientErrorException or HttpServerErrorException.

Try these

Running with the default settings

  1. The main of the order server creates a RestClient. RestClient is the HTTP client that Spring (spring-web) provides, and it sends HTTP requests to other servers and receives the answers. OrderApp is a class name chosen for this example. First it creates the SimpleClientHttpRequestFactory that Spring provides (the request factory: the part that actually makes the connection and sends the request), and uses setConnectTimeout to allow up to 1 second to make the connection and setReadTimeout to wait up to 1 second for the answer after connecting. Then it passes this factory to RestClient.builder() to create the RestClient.
  2. The statement restClient.post().uri("http://localhost:9000/pay").retrieve().body(String.class) runs. It looks like chained method calls, but what this statement does is make a connection to the payment server, send a POST /pay request over the network, and receive the answer. The code that makes the payment is not in this program; it is in the payment server program that runs separately. post() sets the HTTP method, uri(...) sets the address to send to, and body(String.class) converts the body of the answer into a String and returns it.
  3. The payment server receives the POST /pay request and processes the payment. This payment server takes 0.1s to process it. Meanwhile, the main thread of the order server just waits for the answer at this statement, and the payment server program does the work of making the payment.
  4. After 0.1s the payment server sends a 200 response with the body "Payment done". body(String.class) returns this body as a String, and it is assigned to result. System.out.println(result) prints "Payment done". The answer came sooner than the 1s you set, so the timeout was not used.

Result of this run

Code

// Code of the order server. Payment is handled by a separately running payment server. OrderApp is a name chosen for this example.
import java.time.Duration;

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;

public class OrderApp {
    public static void main(String[] args) {
        // The wait time (timeout) is set on the request factory, which actually makes the connection and sends the request
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(Duration.ofSeconds(1));  // up to 1 second to make the connection
        factory.setReadTimeout(Duration.ofSeconds(1));     // after connecting, waits up to 1 second for the answer
        RestClient restClient = RestClient.builder()
                .requestFactory(factory)
                .build();

        try {
            String result = restClient.post()
                    .uri("http://localhost:9000/pay")    // address of the payment server (9000 is an example number)
                    .retrieve()
                    .body(String.class);                 // receives the body of the answer as a String
            System.out.println(result);
        } catch (ResourceAccessException e) {           // connection failure or timeout
            System.out.println("Call failed: " + e.getCause());
        }
    }
}

Assumptions of this model

The behavior was checked by running the RestClient of Spring Framework 7.0.9 (spring-web) on JDK 21.0.12.1 (Windows 11). For all twelve combinations (two places for the payment feature, three states of the payment side, and two for whether a timeout was set), the same text as the code on the screen was written as OrderApp.java, compiled with javac, and run. In the code that calls another server, only the 9000 of the address was replaced with a free port that was actually opened (9000 is an example number). The role of the payment server was played by a small HTTP server that the check program (verify/spring/src/RemoteBasicProbe.java) started on 127.0.0.1 with the ServerSocket of Java; when it receives POST /pay, it sends, after 0.1s or 3s, a 200 response with the body "Payment done" (text/plain, UTF-8). A payment server that is off was imitated by opening a port and then closing it, so that nobody listens on it. This payment server was built for this lab to finish processing without checking whether the order side had closed the connection, which does not mean that every server behaves that way. For each combination, we checked against the model the text that main printed, the time taken, the request line the payment server received (POST /pay HTTP/1.1), when the payment server finished processing, and whether the connection of the order side was already closed at that time, and we also confirmed that the code on the screen is the same text as the source that was run (verify/spring/cmp_remote_basic.js). The time taken is written roughly on the screen; the values measured in the run were 0.10 to 0.21s for about 0.1s, 0.06s or less for right away, 1.01s for about 1s, and 3.01 to 3.08s for about 3s. We made the same call once more in the check program and confirmed that the exception caught by catch is exactly org.springframework.web.client.ResourceAccessException and that the causes are java.net.ConnectException (connection refused) and java.net.SocketTimeoutException (Read timed out). The explanation after ConnectException in the text that catch prints differed with the request factory. The SimpleClientHttpRequestFactory with a timeout set added "Connection refused: getsockopt", and the one created with RestClient.create() printed only the class name with no explanation. In the library setup of this run (no Apache HttpClient, Jetty, or Reactor Netty), RestClient.create() chose JdkClientHttpRequestFactory, which uses the HttpClient of the JDK, and it set no timeout. With other libraries present, it may choose a different request factory. When the payment server was made to receive the request and never answer, the RestClient created with RestClient.create() waited past 4s (we did not watch beyond that), and the RestClient with a 1s timeout ended at about 1s with ResourceAccessException (cause SocketTimeoutException). PayService of the same program (a class made for this example) imitated the time the payment takes with Thread.sleep, and since "only the payment side is off" cannot happen to a method, it was run with 0.1s, the same as the default settings. That a method call has no connection step, and that the thread that called the method runs the body as it is, are explanations of how the Java language works and were not measured separately. A method call can also be handed to another thread and waited for with Future.get with a time limit, but this lab covers only the line that simply calls a method. The screen covers only the simplest case of one call; the cases where the connect timeout actually fires (a peer that gives no answer at all to the connection request) and 404 and 500 responses are covered in "Calling external APIs and timeouts", a device that shields you from failing servers in "Circuit breaker", ways to undo the work of several servers in "Saga and outbox", and receiving requests in one place and splitting them in "Gateway and gradual migration".

Previous lab: Processes · Next lab: Load balancers

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these