Dev Learning Lab

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

Fundamentals › Architecture and operations

Load balancers

Where does a request go when you run several servers?

Why it exists — If there is only one server, that one server has to receive every request even when requests increase, and if it goes down, the whole service stops. Just starting several servers does not decide which server receives which request, or how to avoid a server that is down. A load balancer makes one entrance for incoming requests and sends them on to the servers that are alive, so even when you add servers or one of them goes down, clients keep using the same address.

Where it's used today — A web service with many users starts the same Spring Boot server on several machines and puts a load balancer in front of them. The most common one is nginx: you write the server addresses in the upstream block of the nginx configuration and pass requests to that group with proxy_pass. Load balancers that cloud companies provide do the same job, and they are also used to take servers out and put them back one at a time when you switch to a new version. A value that must continue across requests, such as a login state, is not kept only in the memory of one server; it is usually kept in a place that several servers look at together, such as Redis or a database.

When there are more requests than one server can handle, you start the same server program on several machines. But it is inconvenient if the client (the side that sends requests) has to know several server addresses. So the client connects to just one address, and a load balancer that receives requests at that address sends them on to the servers. This lab compares a setup where the client connects directly to one server with a setup that puts a load balancer in front of two servers. For the load balancer it uses nginx, the most common one. The code box has three parts: the nginx configuration (the upstream block lists the addresses of server A and server B, and proxy_pass passes requests to that group), the commands that start the servers (the same app.jar is started twice with only the port changed), and the Spring Boot controller of each server. A line that starts with # is an explanation. The controller counts the requests it received in its own memory and answers like "I am A, request #1". You remove the load balancer and stop server A after 3 requests, and see how the answers the client receives change.

Checked against real execution · Checked against real execution: the text of the nginx configuration on the screen was put as it is into real nginx 1.27.5 (the nginx:1.27-alpine image), the HelloController on the screen was compiled as it is and started as real Spring Boot 4.1.1 (embedded Tomcat 11.0.24) with the java -jar arguments on the screen, and four combinations were run with the curl command on the screen (verify/net/cmp_lb_basic.js). Which server each request went to, the refused connection, and not using the stopped server for 10 seconds were checked in the access_log ($upstream_addr, $upstream_status) and error_log of nginx

Concepts in this lab

Load balancer
A device that distributes incoming requests across several servers. It checks the state of the servers periodically (health check) and does not send requests to a server that has a problem. It keeps load from piling up on one server and keeps the service running even when some servers fail.
nginx upstream and proxy_pass
Why it exists — Even if you start several servers, if the client has to know those addresses one by one and choose among them, you have to fix the client every time you add or remove a server. upstream and proxy_pass gather the list of server addresses in one place of the nginx configuration and let the client connect to just the one nginx address, so the client stays as it is even when the server setup changes.
Where it's used today — It is used in a setup that starts the same Spring Boot server on several machines and puts nginx in front of them. To add one server, you add one more server line to upstream and make nginx read its configuration again. To give each server a different share, write weight on the server line, and to send requests to the server with fewer connections in progress, write least_conn in upstream.
In an nginx configuration, the upstream block is the place that gives a name to a group of servers that will receive the requests between them, and proxy_pass is the line that decides where the received request is passed. You write one server address per server line, as in upstream app { server 127.0.0.1:8081; server 127.0.0.1:8082; }, and write the group name in proxy_pass, as in location / { proxy_pass http://app; }, and then nginx splits the requests it receives among the servers of the group. upstream goes in the http block of nginx.conf, and if you do not write the method of splitting, weighted round robin is used. If you write a single address directly in proxy_pass, as in http://127.0.0.1:8081, it does not split and passes the requests only to that server.
Round robin
Why it exists — To choose the server for each request by checking how busy the servers are, you have to keep finding out their state. Round robin does not look at the state of the servers. It sends requests in a fixed order, going around, so one simple rule keeps the number of requests each server receives about the same.
Where it's used today — It is commonly used in front of web servers whose requests take about the same time to process. If long requests may be mixed in and work may pile up on one server, use instead the method that sends the request to the server with the fewest active connections (least_conn in NGINX).
Round robin is a method that hands out requests to the servers in turn, one server at a time. With two servers, A and B, requests go to A, B, A, B, in that order. The NGINX documentation says this method, which distributes requests evenly across the servers, is the default and that no directive is needed to turn it on, and that you can also give each server a weight. Which server gets which request follows a fixed order, so when the servers are always in the same state, requests are spread evenly across them.
Skipping a failed server
Why it exists — If requests are sent in turn even to a server that is down, every request whose turn falls on that server ends in an error. Skipping a failed server leaves out a server that cannot be connected to and sends the request again to the next server, so that users see fewer errors even when one server goes down.
Where it's used today — It is used so that requests go to the remaining servers while one server suddenly stops or is coming back up. To find out about a down server before a request arrives, it is sometimes used together with a health check, which sends a check request to the servers regularly (HAProxy, load balancers in the cloud, and so on).
Skipping a failed server is what a load balancer does when an error occurs while it tries to connect to a server: it does not use that server and sends the same request to the next server. In the NGINX documentation the default of proxy_next_upstream is error and timeout, and error also covers an error that occurs while establishing a connection with the server, so when a connection is refused, the request is passed to the next server. Also, after max_fails failures (default 1), the server is considered unavailable for fail_timeout (default 10 seconds). Because of this, even if one server stops, a new request is handled by a live server as long as other servers remain (a request that was already being handled may fail).
Spring Boot command line arguments (--server.port)
Why it exists — If you edit the configuration file every time, or build separate jars, to start the same program several times with only the port or the name changed, it is troublesome and easy to get wrong. If you pass settings as startup arguments, you can leave one jar as it is and give different values each time you start it.
Where it's used today — It is used when you start the same server several times on one computer with only the port changed (java -jar app.jar --server.port=8081, --server.port=8082), and when you pass values that differ by environment at deployment. In containers, the same thing is sometimes done with an environment variable (SERVER_PORT=8081).
An argument attached in the form --name=value when you start a program, as in java -jar app.jar --server.port=8081, is read by Spring Boot as a setting value. The Spring Boot documentation says that SpringApplication converts arguments that start with -- into settings and adds them to the Environment, and that these values take precedence over the values of configuration files such as application.properties. server.port is a setting name that Spring Boot defines, the port the embedded web server opens, and a name you make yourself such as app.name can be passed the same way and read with @Value("${app.name}").
Connection refused error
A connection refused error is the error that the sender gets when it asks for a TCP connection but no program has that port open and is waiting. In Java, a java.net.ConnectException comes at the line new Socket, and in the check run on Windows 11 the message was "Connection refused: connect". The API documentation of ConnectException says that this exception is an error that occurred while connecting, and that it is usually a case where the connection was refused because no process is waiting at the remote address and port. The operating system of that computer refuses, and inside the same computer the error comes right away, without waiting. Because the connection was not opened, not a single piece of text is sent. The TCP standard says to send a reset signal (RST) to a request that comes with no connection (RFC 9293 section 3.5.2).

Try these

Running with the default settings

  1. The servers start. The same app.jar is started twice with java -jar, so the same Spring Boot program runs separately as server A (port 8081, --app.name=A) and server B (port 8082, --app.name=B). The HelloController of each server counts the requests it received in its own count field. In front of them, nginx waits for requests on port 8080 as the line listen 8080 says. The client does not know how many servers there are and knows only the one address, localhost:8080. What receives requests at this address is nginx.
  2. The client sends a GET / request (request #1). What receives this request on port 8080 is not a Spring Boot server but nginx. Following the line proxy_pass http://app; in location /, nginx passes the request to one of the servers listed in upstream app. No method of splitting was written, so it uses the default method, round robin (going around in turn, one server at a time), and the first request goes to the first server in the list, server A (port 8081).
  3. The hello() method of server A adds 1 to count and returns "I am A, request #1". nginx returns this answer to the client as it is. The text the client received says which server answered.
  4. The client sends a GET / request (request #2). nginx passes requests going around in turn, so this time it is the turn of server B. Server B adds 1 to count and returns "I am B, request #1", and nginx returns this answer. Server A has already replied once, but the count of server B starts at "request #1". This is because each server has its own count in its own memory.
  5. The client sends a GET / request (request #3). nginx passes requests going around in turn, so this time it is the turn of server A. Server A adds 1 to count and returns "I am A, request #2", and nginx returns this answer.
  6. The client sends a GET / request (request #4). nginx passes requests going around in turn, so this time it is the turn of server B. Server B adds 1 to count and returns "I am B, request #2", and nginx returns this answer.
  7. The client sends a GET / request (request #5). nginx passes requests going around in turn, so this time it is the turn of server A. Server A adds 1 to count and returns "I am A, request #3", and nginx returns this answer.
  8. The client sends a GET / request (request #6). nginx passes requests going around in turn, so this time it is the turn of server B. Server B adds 1 to count and returns "I am B, request #3", and nginx returns this answer.
  9. All 6 requests are finished. Replies from server A: 3, from server B: 3. Failed requests: 0. The count of server A is 3, and the count of server B is 3.

Result of this run

Code

# nginx configuration (put it in the http { } block of nginx.conf. It receives on port 8080 and splits requests between server A and server B)
upstream app {
    server 127.0.0.1:8081;    # server A
    server 127.0.0.1:8082;    # server B
}

server {
    listen 8080;

    location / {
        proxy_pass http://app;    # splits requests among the servers of upstream app
    }
}

# Start server A and server B: start the same app.jar twice, changing only the port and the name
# --server.port is a setting that Spring Boot defines (the port the server opens), --app.name is a setting chosen for this example (the name of the server)
java -jar app.jar --server.port=8081 --app.name=A
java -jar app.jar --server.port=8082 --app.name=B

# Client: curl http://localhost:8080/ sends 6 requests

// HelloController.java  (HelloController is a controller made for this example. @RestController, @GetMapping, and @Value come from Spring,
// and AtomicInteger comes from Java. The start class annotated with @SpringBootApplication is omitted)
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Value("${app.name}")
    private String name;                                       // the --app.name value given at startup (A or B)

    private final AtomicInteger count = new AtomicInteger();  // the number of requests this server received (it exists only in the memory of this server)

    @GetMapping("/")
    public String hello() {
        return "I am " + name + ", request #" + count.incrementAndGet();
    }
}

Assumptions of this model

Server A and server B are real Spring Boot 4.1.1 (Spring 7.0.9, embedded Tomcat 11.0.24), and the nginx in front of them is real nginx 1.27.5. The HelloController on the screen was compiled as it is (JDK 21), and the servers were started with the --server.port and --app.name arguments written in the java -jar lines on the screen, given as they are. However, instead of packing them into a jar, they were started from the compiled classes, and the start class that the screen omits was kept separately for the test. The nginx configuration on the screen was put into the http block of nginx.conf without changing a single character, comments included. The only additions are the frame that the screen does not show (the events block and the braces of the http block) and the lines that keep records (error_log, log_format, access_log). worker_processes was not written, so nginx had 1 worker process, the default. nginx, server A, server B, and the client were started as containers of Docker 29.8.1 that share the network of one container, which makes them programs on one computer (nginx is the nginx:1.27-alpine image, and Java is 21.0.13 of the eclipse-temurin:21-jre image). So 127.0.0.1:8081, 127.0.0.1:8082, and localhost:8080 on the screen were used as they are, with no change. The client ran the curl http://localhost:8080/ command on the screen 6 times in turn (curl 8.12.1, a new connection for each request). Stopping server A was done by sending the Java process of server A the same signal that Ctrl+C sends (SIGINT), and the next request was sent after checking that the process had ended and the port was closed. Connecting after that gave a connection refused error (Connection refused). All four combinations were run, and we checked against the model the number of replies from server A and server B, the number of failed requests, which server answered each of the 6 requests and as its how-manyth answer, the text the client received, and the count of the servers (verify/net/cmp_lb_basic.js). Which server nginx tried to connect to for each request was read from the records of nginx itself. With $upstream_addr and $upstream_status written to access_log, the requests went to 8081, 8082, 8081, 8082 in that order (the first request to server A, the first server in the list); in the combination that stops server A, the 5th request left "127.0.0.1:8081, 127.0.0.1:8082" and "502, 200", and the 6th request left only 127.0.0.1:8082. At the 5th request, error_log got one line each of connect() failed (111: Connection refused) and upstream server temporarily disabled. Two more things were checked after the 6 requests on the screen. The 4 requests sent right after them all went only to server B, and nginx did not try to connect to 8081. In the requests sent more than 10 seconds after the connection was refused, nginx tried to connect to 8081 again (in this run, at the third request after the 10 seconds). The values the screen calls defaults, max_fails=1, fail_timeout=10s, and proxy_next_upstream error timeout, were checked through the behavior above without writing them in the configuration, and the values themselves are written in the nginx.org documentation. ngx_http_upstream_module: upstream goes in the http block, the default distribution is weighted round robin, the default of max_fails is 1, and the default of fail_timeout is 10 seconds. ngx_http_proxy_module: the name of a server group (upstream) can be used in proxy_pass, the default of proxy_next_upstream is error timeout, and error is an error that occurs while making a connection with the server, passing a request to it, or reading the response header. Of these, timeout (the case where a server does not answer in time) was not run. The round robin turn is counted separately by each nginx worker process (if you put a zone in upstream, the worker processes count together). With several worker processes, the order A, B, A, B may differ from this lab, and that case was not run. Not covered: the case where nginx itself stops, the case where the stopped server starts again and comes back, health checks that check the state of the servers periodically, giving each server a different share with weight, other ways of splitting such as least_conn and ip_hash, the case where a server stops while sending an answer, and the limit a server can hold out when there are very many requests. A load balancer that only does round robin and skipping a failed server can also be written yourself as a program of a few dozen lines. But in a real service you use nginx or a cloud load balancer. How far throughput grows when you add servers is covered in the in-depth lab "Load balancers and scale out", how to deploy by replacing servers one at a time in "Deployment strategies", and automatically restarting a dead server in "Kubernetes self-healing".

Previous lab: Calling another server · Next lab: Caches

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these