Load Balancing with HAProxy: Getting Started Guide

December 10, 2024

It has become almost impossible to manage the increasing traffic load of modern web applications with a single server. We know this problem closely and we need a powerful load balancing tool like HAProxy for its solution.

HAProxy helps us solve performance and reliability issues by intelligently distributing traffic between our servers. It is simple to configure, high performance and offers enterprise-level security features.

In this guide, starting from HAProxy installation, we will examine load balancing strategies, server health checks and SSL termination step by step. Starting from the basic concepts, we will provide practical examples and solutions that you can use in production environment.

HAProxy Installation and Basic Configuration

Before starting the HAProxy installation, we should check the requirements of our system. The minimum hardware requirements for a basic HAProxy installation are quite modest – 1 CPU core and 1 GB RAM should be enough.

System requirements and installation steps

We follow the steps below to install HAProxy on our Ubuntu system:

  1. Update system packages
  2. Installing the HAProxy package
  3. Activate the service

For installation, we run the following command through the terminal: sudo apt-get update && sudo apt-get install haproxy

Create a basic configuration file

HAPROXY Fusion Access Logs Dashboard
HAProxy Access Logs Dashboard

HAProxy’s configuration file is located at /etc/haproxy/haproxy.cfg. For a basic configuration, we need to create global and defaults sections. In the global section, we specify log settings and security parameters, and in the defaults section, we specify default settings such as timeout values.

Initial configuration testing and verification

To test our configuration haproxy -c -f /etc/haproxy/haproxy.cfg command. This command checks the configuration file and informs us if there are any errors. This test is critical before starting HAProxy.

If our configuration is correct, we use the following command to start the service: sudo systemctl start haproxy

To check the status of the service: sudo systemctl status haproxy

For HAProxy to start automatically in case of a system restart: sudo systemctl enable haproxy

For more information about Linux terminal commands, you can check our Linux Commands Guide article.

Load Balancing Strategies

Load balancing strategies are one of the most powerful features of HAProxy. In this section we will analyse the three most effective strategies.

Round Robin algorithm implementation

round robin algoritmasi
Load Balancer with Round Robin Algorithm

Round Robin is our most simple and straightforward load balancing algorithm. This algorithm distributes incoming requests to servers in order. We enable this algorithm by using the balance roundrobin parameter in our configuration. The beauty of Round Robin is that it uses all servers equally and its implementation is simple.

Least Connection method setup

If we are looking for a more dynamic approach, we prefer the Least Connection method. This method redirects new requests to the server with the fewest active connections. We use the balance leastconn directive in the configuration. This algorithm performs 4% better than Round Robin, especially in applications with variable processing times.

Session Persistence

Session management is a critical feature that keeps users connected to the same server. We offer two basic methods:

  1. Cookie Based Persistence: It is used when working in HTTP mode. By adding the cookie directive to our backend configuration, we place a cookie in the user’s browser.
  2. IP Based Persistence: It works in both TCP and HTTP mode. By adding stick-table and stick on src directives to the backend section, we ensure session persistence according to the user’s IP address.

Session management is especially indispensable for e-commerce sites and applications that require user sessions. In case of a server crash, HAProxy automatically redirects the user to another server.

Server Health Checks

Continuously monitoring the health of our servers is critical to the success of our load balancing strategy. At HAProxy, health checks ensure that only healthy servers can handle the traffic.

Health check parameters

Active health checks on HAProxy attempt to establish a connection to our servers at regular intervals. When failed checks exceed a certain threshold, the server is automatically disabled. Our basic parameters are:

  • check: Enables simple TCP checks by adding to the server line
  • inter: Sets the time between controls (default 10 seconds)
  • rise: Number of successful checks required to reactivate the server
  • fall: Number of failed checks required for deactivation

Create custom control scripts

When we want to make more detailed controls for our HTTP applications, we can create custom HTTP controls. For this

  1. We add option httpchk to the backend section
  2. We specify the HTTP method and URL with http-check send
  3. We define the expected response code with http-check expect

We can also use external agent programmes to monitor the system resources of our servers more closely. These programmes run on the server and transmit detailed system information to HAProxy.

Error condition management

We also use passive health checks in fault management. These checks detect failures by monitoring live traffic. When a server fails:

  • The server is automatically disabled
  • Traffic is routed to healthy servers
  • Checks continue and the server is re-commissioned when it recovers

With the error-limit parameter, we determine how many consecutive failed requests will disable the server. The on-error parameter defines the action to be taken in case of error.

SSL Termination and Security

Security is one of the most critical components of our load balancing solution. Let’s examine how we can protect our systems with HAProxy’s powerful SSL termination and security features.

SSL certificate configuration

Thanks to SSL termination, we perform all encryption operations on HAProxy. This approach significantly reduces the load on our backend servers. We ensure secure data transfer with OpenSSL integration.

We follow these steps to configure our SSL certificate:

  1. Certificate file creation in PEM format
  2. Combining private key and certificate
  3. Add SSL directives to the HAProxy configuration file
  4. Set the TLS version to a minimum of TLSv1.2

Security headers and ACL rules

ACLs (Access Control Lists) work like the firewall of our system. With these rules, we can block unwanted traffic and enforce our security policies. We configure our security headers as follows:

  • X-Frame-Options: Protection against clickjacking attacks
  • X-XSS-Protection: Preventing cross-site scripting attacks
  • X-Content-Type-Options: Prevent MIME-type sniffing

With our ACL rules, we automatically block suspicious requests over the HTTP 1.0 protocol. In addition, we detect potential malicious bots by performing User-Agent checks.

DDoS protection implementation

We apply a multi-layered protection strategy against DDoS attacks. With PacketShield technology, we control packet flooding and block malicious packets before they are processed at the kernel level.

With our Global Rate Limiting feature, we can set threshold values at both the connection and application layer. Thanks to the Global Profiling Engine, we monitor client behaviour patterns across our load balancer clusters and detect abnormal activities.

We list our security layers as follows:

  • Access Control Lists (Layer 1)
  • Client Fingerprinting (Layer 2)
  • Real-Time Cluster-Wide Monitoring (Layer 3)
  • Web Application Firewall (Layer 4)

This multi-layered security approach strongly protects our systems against modern cyber threats. With HAProxy Enterprise, we can distinguish malicious traffic from legitimate users thanks to advanced bot management and client fingerprinting features.

Conclusion

HAProxy has become an indispensable component of our modern web applications. All the features we examined, from installation to security, clearly show why HAProxy is the leading load balancing solution. With robust configuration options, intelligent load balancing strategies and powerful security features, it allows us to keep our systems both performant and secure.

For a successful HAProxy implementation, remember to regularly configure health checks and constantly update security measures. Closely monitor the performance of your servers and choose the most appropriate load balancing strategy for your traffic patterns. By actively using security features such as SSL termination and DDoS protection, you can protect your systems against modern threats.

Frequently Asked Questions About HAProxy

What are the basic installation steps of HAProxy?

To install HAProxy, first update the system packages, then install the HAProxy package and enable the service. In Ubuntu, installation can be done with the command ‘sudo apt-get update && sudo apt-get install haproxy’.

How to perform server health checks in HAProxy?

HAProxy checks the health of the servers at regular intervals. Basic TCP checks or custom HTTP checks can be configured. When failed checks exceed a certain threshold, the server is automatically disabled.

How to provide SSL termination and security with HAProxy?

HAProxy can take over encryption operations by configuring SSL certificates. It can also block unwanted traffic with ACL rules and add security headers. A multi-layered security strategy can be applied for DDoS protection.

CyberSkills Hub

CyberSkillsHub, siber güvenlik dünyasının yenilikçi ve teknoloji meraklısı bir figürüdür. CyberSkillsHub’un en büyük özelliği, Akıllı Sınav sistemidir, bu sistem sayesinde öğrencilerin bilgi eksikliklerini anında belirleyebilir ve onlar için özel kurslar tasarlayabilir. Bu dinamik karakter, sadece en yeni ve en güçlü güvenlik teknolojilerine hakim değil, aynı zamanda öğrencilerin ihtiyaçlarını anlamaya odaklanmış bir eğitmen olarak da öne çıkmaktadır. İster bir başlangıç seviye öğrencisi olun, ister deneyimli bir profesyonel, CyberSkillsHub, sizin siber güvenlik yolculuğunuzda yanınızda olacak güvenilir bir rehberdir. İnsanlarla etkileşime geçme yeteneği ve teknolojiye olan tutkusu, CyberSkillsHub'u öğrencilere kişiselleştirilmiş, etkili ve anlamlı eğitim sağlama konusunda benzersiz kılar. Siber güvenliği herkes için erişilebilir ve anlaşılır kılmak, CyberSkillsHub’un misyonunun temelidir.