SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What are Load Balancers?
  • Load Balancing Algorithms
  • DNS Load Balancing
  • Anycast Routing
  • Layer 4 vs Layer 7 Load Balancers
  • Health Checks
  • Sticky Sessions
  • Global Load Balancing
  • Nginx and HAProxy
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Load Balancing

Nginx and HAProxy

Two popular load balancers and reverse proxies, and how you configure them.

⏱ 13 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Nginx and HAProxy are two very popular, free programs that sit in front of your servers. Both can work as a reverse proxy and as a load balancer.

  • Nginx began as a fast web server. It also serves files, handles HTTPS and balances traffic.
  • HAProxy is built for one job: balancing and proxying traffic (TCP and HTTP), with rich health checks and statistics.
  • You describe the servers and the rules in a config file, and the tool does the rest.
  • Many systems use one of them at the front door of each region, or inside the cluster.

02Concept: What is it?

A reverse proxy accepts requests from users and forwards them to servers behind it. A load balancer adds the rule for which server gets each request. Nginx and HAProxy do both. You install one on a machine, point DNS at it, and list your app servers in its config.

Where they sit
πŸ§‘Users
→↓HTTPS
🧱Nginx or HAProxyTLS, routing, balancing
→↓HTTP
πŸ–₯️App 1
πŸ–₯️App 2
πŸ–₯️App 3
Users never talk to the app servers directly. They talk to the proxy.

Same job, different roots

Nginx and HAProxy side by side
Nginx
🌐Web server + reverse proxy
πŸ“Serves static filesHTML, images, cache
🧩Config: upstream, server, location
HAProxy
βš–οΈDedicated load balancer
🩺Strong health checks and stats
🧩Config: frontend, backend, server
🧠Layer 4 and layer 7
Both can balance at layer 4 (just TCP connections) or layer 7 (they read the HTTP request, so they can route by URL, header or cookie). Layer 7 is smarter, layer 4 is lighter.

03Real-Life Example

🍡The Hotel Front Desk
A hotel has a front desk. Guests never walk to rooms on their own. The desk checks who they are, looks at which rooms are free and ready, and sends each guest to a room. The desk also keeps a list of rooms that are being cleaned, and skips them. Nginx and HAProxy are two kinds of front desk. One began as a general-purpose desk that also hands out brochures (Nginx serves files). The other is a desk built only for directing guests, with a very detailed board of room status (HAProxy).
Hotel
Nginx / HAProxy
Front desk
The proxy and load balancer
Rooms
Backend app servers
The room list
upstream (Nginx) or backend (HAProxy)
The entrance door and its rules
server and listen (Nginx) or frontend and bind (HAProxy)
Sending guests in turn
Round robin
Sending guests to the emptiest floor
Least connections
A room being cleaned
Server failing its health check
The status board
HAProxy stats page, Nginx status and metrics
Handing out brochures
Nginx serving static files
A request through the proxy
πŸ“¨RequestGET /api/items
→↓
🧱Match a rulelocation /api
→↓
βš–οΈPick a serveralgorithm + health
→↓
πŸ–₯️Forwardproxy_pass / backend

04Why Do We Need It?

βš–οΈShare the load
Many app servers behind one address, so one server does not carry everything.
🩺Skip sick servers
Health checks remove failing servers from rotation automatically.
πŸ”’Handle HTTPS in one place
The proxy ends TLS, so the app servers can speak plain HTTP inside the private network.
🧭Route by rule
Send /api to one group of servers and /static to another, from one public address.
πŸ›‘οΈA safe front door
Hide the app servers, limit connections, add timeouts and basic rate limits.
πŸ’ΈFree and proven
Both are open source, widely used, and well documented.
You do not need to write a load balancer. Describe your servers and rules in a config file, and let a proven tool do the work.

05Where Do We Use It?

πŸšͺEdge of a data centre
The first stop for public traffic, ending TLS and sending requests inward.
☸️Kubernetes ingress
Popular ingress controllers are built on Nginx or HAProxy.
πŸ—„οΈDatabase and TCP balancing
HAProxy is often used to balance TCP services like databases, or to send writes to a primary and reads to replicas.
πŸ“Static file serving
Nginx serves files and caches responses, in front of an app.
🏒On-premises setups
Where there is no cloud balancer, these tools are the balancer.
πŸ”€Inside microservices
As a gateway or a sidecar proxy that balances calls between services.

06Types / Parts / How It Works

Config in each tool (illustrative)

nginx.conf: an upstream group and a server block
upstream backend {
    least_conn;                       # default is round robin
    server 10.0.0.1:8080 weight=3;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080 backup;      # used only if the others fail
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
    }
}
haproxy.cfg: a frontend and a backend
frontend web
    bind *:80
    mode http
    default_backend app

backend app
    mode http
    balance leastconn                 # roundrobin, leastconn, source ...
    option httpchk GET /health        # active health check
    server app1 10.0.0.1:8080 weight 3 check
    server app2 10.0.0.2:8080 check
    server app3 10.0.0.3:8080 check backup
πŸ“Note
Directive names, defaults and available features depend on the version and the build you use. These snippets show the idea only. Check the official documentation before using them.

How they compare

TopicNginxHAProxy
Main identityWeb server that is also a reverse proxy and balancerDedicated load balancer and proxy
Config shapeBlocks: http, upstream, server, locationSections: global, defaults, frontend, backend
Serves static filesYes, very commonly used for itNot its purpose
Algorithms (common)Round robin (default), least_conn, ip_hash, hashroundrobin, leastconn, source, uri, and others
Health checksPassive checks in the open-source version, active checks in commercial or extra modulesRich active checks built in, plus fine control of when to remove a server
TCP / UDP balancingYes, through the stream moduleYes, a core use (TCP mode)
StatisticsBasic status page, metrics through add-onsDetailed built-in stats page and runtime API
Typical choiceOne tool for web serving, caching and proxyingA balancer in front of many services, with strong checks and TCP
VisualizerAlgorithm and weights: how 12 requests are sharedSwitch between Nginx and HAProxy and watch the config text change. Try round robin, least connections and IP hash, then give one server a higher weight.
Tool
Algorithm: round robin (default, no directive)
nginx.conf (illustrative)
upstream backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}
12 requests, one per tick. Letter = client. Colour = the server that got it. Number = ticks the connection stays open.
#1
A
3 t
#2
B
1 t
#3
A
4 t
#4
C
1 t
#5
D
5 t
#6
A
1 t
#7
B
2 t
#8
A
6 t
#9
C
1 t
#10
A
1 t
#11
D
3 t
#12
B
2 t
πŸ–₯️ 10.0.0.1weight 1
4 of 12 requests, peak 1 open
πŸ–₯️ 10.0.0.2weight 1
4 of 12 requests, peak 2 open
πŸ–₯️ 10.0.0.3weight 1
4 of 12 requests, peak 2 open
Server 1
4
requests
Server 2
4
requests
Server 3
4
requests
Busiest peak
2
open connections
Round robin hands out requests in turn, in proportion to the weights (1 : 1 : 1). It does not look at how long each request lasts, so a server can collect several slow ones in a row. The busiest server peaked at 2 open connections.

A teaching model: the request list, durations and client hashes are fixed, and it uses a smooth weighted round robin. Real tools differ in tie-breaking and in details that change between versions, so check the official docs. The addresses are examples.

07How to Use It / Steps / Implementation

Setting one up

  1. 1
    List your backends
    Write the addresses and ports of your app servers. Keep the list in one place (an upstream or a backend).
  2. 2
    Choose an algorithm
    Start with round robin. Use least connections when requests vary in length. Use a hash if you need a user to return to the same server.
  3. 3
    Add weights if servers differ
    A server twice as strong gets a weight twice as high.
  4. 4
    Turn on health checks
    Point the check at a real health URL, not just a TCP port. Decide how many failures remove a server.
  5. 5
    End TLS at the proxy
    Install the certificate on the proxy. Keep it renewed and test the chain.
  6. 6
    Set timeouts and limits
    Give connect, read and idle timeouts. Limit connections and request sizes to protect the app servers.
  7. 7
    Reload without dropping users
    Both support graceful reloads. Test your config first (nginx -t, haproxy -c) and then reload.
  8. 8
    Make the proxy highly available
    One proxy is a single point of failure. Run two, with a floating IP or a cloud balancer in front.
Check a config before reloading (commands)
nginx -t                       # test the Nginx config
haproxy -c -f /etc/haproxy/haproxy.cfg   # check the HAProxy config
πŸ’‘Do not forget the proxy itself
A load balancer that runs on one machine is itself a single point of failure. Run at least two, and put a virtual IP or DNS in front.

08Key Terms to Know

TermMeaning in easy words
Reverse proxyA server that receives requests for other servers and forwards them
Load balancerA reverse proxy that also decides which backend server gets each request
Upstream (Nginx)A named group of backend servers
Backend (HAProxy)A named group of servers that a frontend can send traffic to
Frontend (HAProxy)The listening side: which address and port to accept traffic on
proxy_passThe Nginx directive that forwards a request to an upstream or URL
WeightA number that makes a server receive more or less than its share
Health checkA test the proxy runs to see if a server is fit to receive traffic
TLS terminationEnding the encrypted HTTPS connection at the proxy
Graceful reloadApplying a new config without dropping current connections
Stick table / ip_hashWays to keep a client on the same backend

09Pros, Cons and Trade-offs

βœ… Pros
  • Free, open source and very widely used
  • Fast and light on resources
  • Flexible routing and algorithms
  • Health checks and weights built in
  • Handles HTTPS in one place
  • Good documentation and community
⚠️ Cons
  • You run and patch them yourself
  • A single instance is a single point of failure
  • Config mistakes can break all traffic
  • Some features differ between open-source and paid versions
  • Not a full global solution on their own
  • Dynamic setups (autoscaling) need extra tooling

Trade-offs

ChoiceWe gainWe lose
Self-managed Nginx or HAProxyFull control, no vendor lock-in, often cheaperYou operate it: upgrades, scaling, high availability
Cloud managed balancerLess to run, built-in scaling and availabilityLess control, cost, tied to the provider
NginxOne tool for web serving, caching and proxyingFewer built-in balancer features in the open-source build
HAProxyStrong balancing, checks and statistics, good for TCPNot a web server, no file serving
Layer 7 modeRoute by URL, header or cookieMore CPU, must parse requests
Layer 4 modeVery fast, protocol agnosticCannot look inside the request

10Common Problems and Mistakes

Common mistakes

  1. A single proxy. The balancer itself is the single point of failure.
  2. Weak health checks. Checking only that a port is open misses a broken app.
  3. Timeouts left at defaults. Slow backends tie up connections, or long uploads get cut.
  4. Forgetting forwarded headers. The app sees the proxy's IP, not the real client. Pass the client address (for example X-Forwarded-For) and trust it only from the proxy.
  5. Reloading an untested config. A typo can take down the front door. Always test first.
  6. Hard-coded server IPs. With autoscaling, backends come and go. Use service discovery or templates.
  7. Trusting the proxy for security alone. It is one layer, not a full defence.

Things to watch

πŸ”ŒConnection limits
Open file and connection limits on the proxy host can become the bottleneck.
🧯Config drift
Keep configs in version control and deploy them like code.
πŸ“ˆMetrics
Watch active connections, response codes, backend latency and the number of healthy servers.
πŸ”Certificates
An expired certificate on the proxy stops everything. Automate renewal.

11Real-World Examples

🌐A large share of the web
Nginx is widely used as a web server and reverse proxy across the internet.
βš–οΈHigh-traffic balancers
HAProxy is a common choice for high-volume load balancing at the front of big sites.
☸️Kubernetes ingress
Several popular ingress controllers run Nginx or HAProxy inside the cluster.
☁️Inside cloud setups
Teams place them behind a cloud balancer to add custom routing, caching or TCP rules.
πŸ—„οΈDatabase access
HAProxy often fronts database replicas, with health checks that know which node is the primary.
🧱Gateways
Many API gateways are built on top of Nginx.
πŸ“Note
Market share and features change over time. Treat these as general descriptions, not exact statistics.
Mini case: two proxies and three apps
πŸ§‘Users
→↓virtual IP
🧱Proxy 1active
🧱Proxy 2standby
→↓balance
πŸ–₯️App 1
πŸ–₯️App 2
πŸ–₯️App 3
Active Standby Client
Two proxies share one virtual IP, so the front door has no single point of failure.

12Related Topics to Read Next

What are Load Balancers?β†’

The idea behind both tools.

Load Balancing Algorithms→

Round robin, least connections and hashing, as set in the config.

Proxy vs Reverse Proxy→

Both tools are most often used as reverse proxies.

Layer 4 vs Layer 7 Load Balancers→

The two modes both tools can run in.

Health Checks→

How a proxy decides if a backend can receive traffic.

Sticky Sessions→

ip_hash, source and stick tables are ways to keep a client on one server.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: reverse proxies and load balancers, set up by config file.
  • βœ”Nginx: web server first. upstream + server + location, proxy_pass.
  • βœ”HAProxy: balancer first. frontend + backend + server, balance, check.
  • βœ”Algorithms: round robin, least connections, hash of IP.
  • βœ”Also: weights, backup servers, TLS termination, timeouts.
  • βœ”Health: HAProxy has rich active checks. Open-source Nginx is mostly passive.
  • βœ”HA: run two proxies. One is a single point of failure.
  • βœ”One line: β€œA front desk for your servers: pick one, check it is healthy, send traffic.”
← Previous
Global Load Balancing
Next β†’
What is an API?