HAProxy as a line of defence: protection against DDoS and Layer 7 attacks
Maik Wichmann
Team Lead Cloud Engineering
In practice, websites are not only attacked via traditional security vulnerabilities, but very frequently through overload. For businesses, therefore, the relevant question is not only whether a platform can be compromised, but above all how it remains accessible under heavy load, abuse and targeted flooding attacks. DDoS attacks, HTTP floods, bot traffic and misused application endpoints are among the most common causes of web services failing to respond properly or crashing completely.
HAProxy is a highly effective tool in this context because it can precisely control, at Layer 7, which clients are permitted to access the system, at what speed, how often and via which paths. At the same time, it is important to bear in mind the tool’s limitations.
This article summarises the key points relevant to the production operation of a publicly accessible web platform. The focus is on a typical architecture featuring a dedicated HAProxy server, an upstream firewall and Linux kernel hardening on the proxy host.
Layer 7 and Layer 3/4 attacks: The threat landscape in production
From an operational perspective, two distinct classes of problems can be identified. Firstly, there are attacks at the application layer, i.e. Layer 7: HTTP GET/POST floods, bot waves, login brute-force attacks, excessive API usage or malicious requests to high-cost endpoints. Secondly, there are network and transport attacks at Layers 3 and 4, such as SYN floods or UDP floods, which exhaust links, firewalls or kernel resources.
This distinction is crucial from an operational perspective. A Layer 7 attack can often be identified by its characteristics: too many requests per IP address, unusual access to /login, suspicious user agents or high error rates. A Layer 3/4 attack, by contrast, is often purely a volume-based overload, in which bandwidth, connection tracking or the TCP handshake collapse before any HTTP logic even comes into play.
For administrators, this leads to a simple but important principle: HAProxy is an excellent tool for controlling and mitigating application traffic, but it is not the sole solution to large-scale floods. The architecture must be multi-layered; otherwise, the proxy itself becomes the bottleneck.
Where HAProxy excels: rate limiting and Layer 7 protection
HAProxy really comes into its own where connections and HTTP requests need to be intelligently evaluated. This includes rate limiting, per-IP tracking using stick tables, ACL-based rules, protection of sensitive paths and the early rejection of malicious sessions. It is precisely these mechanisms that are particularly valuable for dealing with HTTP floods and bot behaviour.
A typical example is limiting the request rate per source IP. If a client generates several dozen or hundreds of requests within ten seconds, HAProxy can use stick tables to take immediate action. The simplest option is a 429 response; a more stringent option is temporary tarpitting or rejection at the TCP level.
Equally important is the segmented handling of sensitive endpoints. /login, /password_reset or /api/auth should never have the same thresholds as a static home page. Good HAProxy configurations therefore distinguish between general traffic and high-risk paths, and apply stricter rules only where they make technical sense.
Where HAProxy reaches its limits: volumetric DDoS attacks
As soon as the attack primarily targets link capacity, packet processing or the TCP handshake, the main defence must take place before HAProxy. Otherwise, large UDP floods or broad SYN waves will saturate the host’s bandwidth or kernel resources before HAProxy can demonstrate its true strength at the application level.
Therefore, an upstream firewall in a web architecture is not only sensible but also absolutely essential. However, the same principle applies here: whilst a firewall that only permits TCP ports 80 and 443 reduces the attack surface, it is no substitute for a dedicated DDoS mitigation strategy. SYN floods on TCP ports 80 and 443 will still reach HAProxy. Against volumetric attacks, ISP mitigation, Anycast, CDN or scrubbing services remain the most robust options.
For system engineers, this is not a theoretical nuance, but a clear area of responsibility. The CDN or scrubbing services absorb volume and unwanted protocols, the Linux kernel stabilises queuing and TCP behaviour, and HAProxy manages semantic access control at the HTTP and session levels.
Reference architecture: firewall, HAProxy and backend working together
A practical minimal architecture consists of a firewall in front of one, or better still two, dedicated HAProxy servers in a failover cluster, behind which the actual web or API backends are located. The firewall only allows TCP ports 80 and 443 from the outside to pass through to the proxy; HAProxy terminates TLS, checks hosts and paths, limits connections and requests, and then distributes them to internal backend systems.
This structure offers several advantages:
- The proxy host is clearly specialised in ingress and traffic control
- Security and routing decisions are implemented centrally.
- The actual application servers are decoupled from gross abuse and, ideally, only see traffic that has already been filtered and evaluated.
A simple routing example looks like this:
`site.example.com` goes to an app backend, `/api` to a separate API backend, and `/login` is subject to stricter limits than normal page requests. This separation is minor from a technical perspective, but hugely effective from an operational standpoint.
Hardening at the HAProxy level: stick tables, ACLs and request limits
The most important starting point on the HAProxy side is stick tables. They allow metrics such as current connections, connection rate, HTTP request rate or error rates to be collected for each source IP. Based on this, ACLs can be formulated to curb suspicious behaviour at a very early stage.
A typical pattern for secure defaults is a moderate limit on the request rate – for example, 50 requests in ten seconds per IP address for general paths, and significantly stricter limits for login or authentication routes. For a small to medium-sized platform, this is often sufficient to intercept trivial bot waves or poorly written scripts without severely impacting legitimate users.
For more aggressive scenarios, the same logic can be tightened. Additional TCP rules are then introduced, such as an `inspect-delay`, which allows for early evaluation, or limits on `conn_cur` and `conn_rate`, which prevent a single source from opening hundreds of parallel sessions unchecked. Such measures primarily protect the backends and the proxy’s workers.
Another tried-and-tested pattern in configurations is the combination of a whitelist and blocking logic. Monitoring systems, internal admin IP addresses or known upstream systems are explicitly permitted, whilst unknown or suspicious sources are subject to stricter rules. This reduces the risk of accidentally blocking your own operational tools.
Kernel hardening: sysctl parameters for the HAProxy host
Even the most secure proxy remains vulnerable if the Linux kernel is not sufficiently buffered or hardened under load. That is why certain sysctl settings are essential for any production proxy role. Particularly relevant are tcp_syncookies, somaxconn, tcp_max_syn_backlog and netdev_max_backlog, as they directly influence how the host handles incoming connections and packet spikes.
For a small host with 2 vCPUs and 2 GB of RAM, conservative values are often the better choice. A `somaxconn` of 1024, a `tcp_max_syn_backlog` of 2048, enabled SYN cookies and moderately increased buffers are usually sufficient for stable baseline setups. Only when monitoring shows that legitimate traffic is actually pushing these limits to their maximum should settings be adjusted more aggressively.
The handling of conntrack is also important. If stateful filtering or other local firewall rules are active on the host, nf_conntrack_max must be adjusted to match the actual load patterns. If the value is too low, the platform will crash even during load spikes; if it is set too high, memory consumption will rise unnecessarily, which quickly becomes problematic on small systems.
Role of the firewall in front of the HAProxy server
In the architecture described, the firewall acts as the first line of defence. It should not only filter ports but – where possible – have DDoS and flood policies enabled, limit SYN and UDP anomalies, and discard obvious non-HTTP traffic before it reaches the proxy.
The main practical benefit is that the HAProxy host is thus exposed to less irrelevant traffic. This increases the likelihood that the CPU, memory and socket queues will remain available for the web traffic that is actually relevant. At the same time, it becomes clear that this layer is not merely a ‘firewall at the front end’, but an active component of the availability strategy.
System engineers should always consider this layer in conjunction with the provider. If an attack reaches several hundred Mbit/s or more, it is no longer the precision of the local ACL that is decisive, but rather the question of whether the traffic can be intercepted before it reaches one’s own uplink.
Safe defaults vs. aggressive settings: when each approach makes sense
A common mistake in projects is to set aggressive values too early. Particularly on smaller HAProxy hosts with 2 GB of RAM, excessive limits, too many stick-table entries or overly large conntrack tables quickly lead to unnecessary resource consumption. Safe defaults are therefore not a sign of carelessness, but rather an expression of a controlled operating model.
Safe defaults typically mean: moderate `maxconn` values, short but not excessively strict timeouts, clean health checks, throttling on critical paths, backlog values within reasonable limits, and enabled logging with a clear set of metrics. This results in a system that remains stable whilst simultaneously revealing where the actual load limit lies.
Aggressive settings should only be included in the configuration once the platform is being closely monitored. These include higher `maxconn` values, stricter login limits, more stringent TCP reject rules, larger kernel queues and shorter timeouts. These measures are not fundamentally wrong, but they must be justified by measured data; otherwise, the risk of false positives increases.
HAProxy monitoring: Baseline metrics in Prometheus and Grafana
Without metrics, any hardening remains speculative. Administrators should therefore establish a baseline before activating stricter rules: CPU load, RAM usage, network packets per second, SYN behaviour, established sessions, conntrack utilisation and HAProxy-internal metrics such as current sessions, request rate and 5xx responses.
These metrics can be made available to Prometheus via HAProxy itself. This allows host and HAProxy data to be collected via the node_exporter and the HAProxy endpoint, and then correlated in Grafana. The practical benefit is enormous: if the request rate rises during a test or attack but the link remains free, the problem is more likely to lie at Layer 7; if packet rates and interface load skyrocket, the network layer is the first to be investigated.
Five metrics are particularly informative:
- haproxy_frontend_current_sessions
- haproxy_frontend_http_requests_total
- haproxy_frontend_http_responses_total{code="5xx"}
- node_network_receive_packets_total
- node_nf_conntrack_entries
This combination very quickly reveals whether a problem stems from HTTP abuse, network traffic or state exhaustion.
Test procedure: configuration, load test and abuse test
A practical test procedure begins with a syntax and integrity check. Before each deployment, the configuration is validated using `haproxy -c -f /etc/haproxy/haproxy.cfg`, after which sysctl changes are loaded and kernel logs are checked. Only then should load testing begin.
The next step is to establish a baseline under legitimate load. Tools such as wrk or hey are sufficient for the initial test. The aim is not to push the system to its limits straight away, but to develop a feel for how the CPU, memory, sessions and error rates respond under realistic usage. It is often already apparent at this stage whether timeouts, health checks or backend distribution have been chosen appropriately.
This is followed by the Layer 7 abuse test. Here, a large number of requests are deliberately generated against general paths and then against sensitive endpoints such as /login. The expectation is that rate limits will kick in, 429 responses will be returned, and the rest of the platform will remain accessible. If this does not happen, thresholds or stick-table logic must be adjusted.
Finally, TCP and SYN behaviour should only be tested in a controlled staging environment, for example using tools such as hping3. The aim here is not to cause maximum damage to the environment, but to observe how the kernel, firewall and proxy interact: If SYN counts rise without established sessions collapsing completely, the protective mechanisms are at least partially effective. If the connection or the firewall fails, the defence mechanisms must be moved further upstream.
A brief operational example: HAProxy 3.2 on a host with 2 vCPUs
Suppose a company is running a public web application behind a firewall. HAProxy 3.2 is running on the dedicated proxy host with 2 vCPUs and 2 GB of RAM. The firewall only permits TCP ports 80 and 443 to HAProxy; HAProxy terminates TLS, distributes traffic across two application servers and an API backend, and uses stick tables to limit suspicious clients.
In this scenario, secure defaults would be a plausible starting configuration. This means: `nbthread 2`, a moderate `maxconn`, request limits on general traffic, stricter limits on `/login` and robust health checks on the backends. On the kernel side, SYN cookies are enabled, the SYN backlog is increased and conntrack is not set too high. The system is therefore not ‘as secure as possible’, but it is easy to monitor and stable.
If metrics later show that, for example, API clients are generating significantly more legitimate requests or that login surges are regularly pushing the threshold, the settings can be fine-tuned as required. This is precisely the operational strength of this architecture: hardening is not carried out blindly, but is based on measured data.
Common misconceptions about HAProxy as DDoS protection
A common misconception is that HAProxy can simply ‘filter out’ even large DDoS attacks. This is only partly true. At Layer 7, HAProxy can be very effective; at Layers 3/4, its effectiveness ends where the uplink, firewall or kernel are already saturated.
Equally problematic is the assumption that only the application needs to be protected. In reality, resilience is determined by the combination of the edge gateway, host kernel, proxy rules, backend capacity and monitoring. If any of these layers is neglected, it almost inevitably becomes the first genuine single point of failure.
The opposite can also occur: teams harden their systems so aggressively that normal users are blocked. NAT scenarios, corporate proxies or shared mobile network egress points in particular can appear to generate ‘too many requests per IP’, even though the behaviour is legitimate. Without whitelists, clean metrics and a phased roll-out, protective measures then become an operational problem in their own right.
Conclusion: HAProxy as part of a multi-layered DDoS defence
HAProxy is not a panacea for the secure deployment of a web application, but it is a highly precise tool within a multi-layered defence strategy. The core idea is simple: Manage Layer 7 issues with HAProxy; intercept Layer 3/4 traffic volumes in the network upstream using a firewall, CDN or scrubbing services; configure the Linux kernel of the proxy host stably; and base any hardening on observable metrics.
In an architecture featuring a firewall, a dedicated HAProxy server and robust monitoring, this enables the creation of a robust protection model that both limits typical bot and HTTP attacks and reduces the impact of TCP floods. The real key to success here is not so much a single parameter as the discipline of measuring baselines, choosing conservative default settings and only optimising aggressively once the data warrants it.
Are you considering how to make your applications and systems resilient against DDoS attacks, HTTP floods and SYN floods?
Our experts can support you with the analysis, architectural design and operation of suitable protective measures.
Frequently asked questions about HAProxy and DDoS protection
What is HAProxy?
HAProxy is a high-performance, open-source load balancer and reverse proxy for TCP- and HTTP-based applications. It accepts incoming connections, distributes them across backend servers and controls access based on rules. In security-focused architectures, HAProxy is frequently used for bot defence, rate limiting and as the first control layer for HTTP traffic.
Does HAProxy provide reliable protection against DDoS attacks?
HAProxy provides very effective protection against application-layer attacks, such as HTTP floods, bot waves or brute-force attempts on login endpoints. HAProxy alone is not sufficient against volumetric attacks at Layers 3 and 4. In such cases, an upstream firewall, ISP mitigation or a CDN is required.
What is the difference between Layer 7 and Layer 3/4 DDoS attacks?
Layer 7 attacks target the application logic, for example by sending excessive HTTP requests to resource-intensive endpoints or carrying out massive login attempts. Layer 3/4 attacks are volumetric and saturate bandwidth, connection tracking or the TCP handshake before the application even sees them.
What are stick tables in HAProxy?
Stick Tables are an in-memory data structure in HAProxy that collects metrics such as connections, request rates or error rates per client (for example, per source IP). Based on this data, ACL rules can be formulated to throttle suspicious behaviour at an early stage, for example via a 429 response or a rejection at the TCP level.
HAProxy or NGINX for DDoS defence?
HAProxy is a specialised load balancer offering particularly fine-grained control via Stick Tables and ACLs. NGINX is primarily a web server with reverse proxy functions. HAProxy comes into its own for complex rate limiting, per-IP tracking and targeted Layer 7 defence, whilst NGINX is the sensible choice wherever static content also needs to be served.
Which sysctl settings are recommended for an HAProxy host?
Particularly relevant are tcp_syncookies, somaxconn, tcp_max_syn_backlog and netdev_max_backlog, as they control how the host handles incoming connections and packet spikes. For a small host with two vCPUs and two GB of RAM, conservative values are advisable, such as somaxconn set to 1024 and tcp_max_syn_backlog set to 2048, supplemented by enabled SYN cookies.
Are a firewall and HAProxy sufficient for DDoS defence?
Together, they form a solid foundation against bot and HTTP attacks. A firewall reduces the attack surface, whilst HAProxy performs semantic evaluation and throttles abusive sessions. In the case of volumetric attacks at several hundred Mbit/s, this is not enough: ISP mitigation, Anycast, CDN or scrubbing services are the reliable options here.
Which metrics indicate an ongoing Layer 7 attack?
Particularly telling is the combination of `haproxy_frontend_current_sessions`, `haproxy_frontend_http_requests_total`, `haproxy_frontend_http_responses_total{code="5xx"}`, node_network_receive_packets_total and node_nf_conntrack_entries. If the request rate rises without packet rates and interface load skyrocketing, this points to a Layer 7 attack. If packet rates skyrocket first, the problem lies at the network layer.
