Distribute Requests Across Multiple Upstream Services
🎯 Introduction
One entry point can serve multiple application instances. This article adds a second mock backend, verifies request distribution, and explains why having two addresses does not make a system failure-proof.
🛠 Prepare a Second Backend
Append a second top-level server to mock.conf. Do not put it inside the first server:
server {
listen 127.0.0.1:9002;
server_name backend-b;
default_type application/json;
location = /notes {
add_header X-Backend 'b';
return 200 '{"instance":"b","notes":["learn nginx"]}';
}
location / {
return 404 '{"error":"not found"}';
}
}
Reload and connect directly to http://127.0.0.1:9002/notes first. Expect "instance":"b". The data is the same and the instance names differ, making distribution easy to observe without first learning to deploy a business application.
🧱 Define a Backend Group with upstream
Create conf/servers/upstream.conf with this content:
upstream notes_api {
server 127.0.0.1:9001 max_fails=1 fail_timeout=10s;
server 127.0.0.1:9002 max_fails=1 fail_timeout=10s;
keepalive 8;
}
This file is included inside http, so upstream and server are siblings. The group name notes_api is a configuration identifier and needs no DNS record. The default algorithm is weighted round robin. With equal weights here, successive new requests will usually show both instances.
Change proxy_pass in the entry point's /api/ block to:
proxy_pass http://notes_api/;
Keep the other header and timeout settings. keepalive 8 caches up to eight idle upstream connections per worker; it does not limit the backend to eight concurrent requests. The HTTP/1.1 and Connection settings established earlier support this reuse. See the official upstream documentation.
🧪 Verify Distribution and Failure Handling
After checking and reloading, run this in Bash:
for n in {1..6}; do
curl -sS http://127.0.0.1:8080/api/notes
printf '\n'
done
for repeats the operation six times. -sS hides the progress meter but preserves error messages. Verify that both a and b appear; do not treat strict alternation as guaranteed in every environment.
Next, temporarily change the second upstream port to the unused 9999. Check and reload, then repeat the requests. The default proxy retry policy can try another upstream for eligible connection errors or timeouts. This exercise uses GET requests before any response has been returned, so you can usually still receive data from a. The error log should report failed connections to 9999. Restore 9002 and reload afterward.
max_fails=1 fail_timeout=10s provides passive failure detection: after enough failures within the specified period, Nginx temporarily avoids that upstream. This is not an active health check that sends periodic probes. Results with one worker also do not establish how state is shared across multiple workers.
🪤 Multiple Instances Still Require Application Support
In a real application, both instances must access consistent data. If login state exists only in one instance's memory, a request sent to the other may lose that state. The application must provide shared sessions or another suitable approach; Nginx does not synchronize application data.
Do not broaden retry conditions simply to reduce visible errors. If a backend has already created an order or charged a payment, resending the request can duplicate the operation. Applications need reliability mechanisms such as deduplication. See the proxy retry documentation for constraints.
Both mock backends and the entry point belong to the same process hierarchy in this exercise. If the machine or Nginx stops, all become unavailable together. This teaches request distribution; it is not a highly available deployment.
❓ Questions and Answers
Q1: Do two backends always double performance?
No. The database, CPU, network, or shared resources may be the bottleneck. Measure the actual results.
Q2: Can I make the slowest address a standby?
backup marks a server for use when the primary servers are unavailable. First check that this fits your capacity and failure plan. For now, learn to use two ordinary members.
🧪 Exercise
Add weight=2 to the first upstream, leave the second at its default weight, and send many new requests. Observe the results, then restore equal weights.
Check your result: explain why the first address generally receives a larger share, while a finite sample need not be exactly 2:1. Both instances should respond successfully.
🎉 You can now configure and verify multiple upstreams, and understand why balancing does not replace application reliability!
Forwarded Headers and Timeouts
Understand the proxied Host, client address, and protocol, and configure connection and read timeouts appropriately.
Logs and Troubleshooting
Use access logs to identify who returned a 404, error logs to diagnose 502s, and request and upstream timings to investigate latency.
