什么是负载均衡器?了解负载均衡及其工作原理
Networking

什么是负载均衡器?了解负载均衡及其工作原理

负载均衡器将流量分配到多台服务器,以提高性能、稳定性和可扩展性。了解负载均衡器的工作原理、常用算法和实施策略。

✦ 快速摘要
负载均衡器将流量分配到多台服务器,以提高性能、稳定性和可扩展性。了解负载均衡器的工作原理、常用算法和实施策略。
这篇文章怎么样?

负载均衡器是现代系统架构的关键组件,能够智能地将流量分配到多台服务器。本文详细介绍什么是负载均衡器、常用的负载均衡算法、健康检查、会话持久性以及实际部署架构。

什么是负载均衡器?

负载均衡器(Load Balancer)是位于客户端和服务器组(服务器池/服务器集群)之间的设备或软件,负责将来自用户的请求分配到后端服务器,使负载均匀分布——防止任何单台服务器过载而其他服务器闲置。

当您的网站或应用程序不断增长,用户流量持续增加时,单台服务器将无法处理所有请求。这时负载均衡器就派上用场了——它智能地将流量分配到多台服务器,确保系统始终稳定且响应迅速。

现实生活类比

想象一家有5个收银台的餐厅。如果所有顾客都排在同一个收银台,等待时间会非常长,尽管其他4个收银台空闲。负载均衡器就像引导顾客到最空闲收银台的引导员,确保所有收银台都在工作,顾客等待时间最短。

为什么需要负载均衡器?

高可用性

如果只有一台服务器且它发生故障,整个服务将停止运行。有了负载均衡器:

  • 流量自动重定向到其余健康的服务器。
  • 系统可以承受一台或多台服务器故障而不影响用户。
  • 可以实现99.99%或更高的在线时间。

可扩展性

负载均衡器实现水平扩展——在流量增加时向池中添加新服务器,而不是升级现有硬件(垂直扩展)。水平扩展更加灵活且成本效益更高。

最佳性能

在服务器之间均匀分配负载确保:

  • 没有服务器过载。
  • 为所有用户提供稳定的响应时间。
  • 最大化利用硬件资源。

零停机维护

您可以将单台服务器从池中移除进行维护或更新,而不影响服务。负载均衡器会自动将流量分配到其余服务器。

负载均衡器的类型

第4层负载均衡器(传输层)

在OSI模型的传输层(TCP/UDP)运行。基于源/目标IP和端口号等网络信息做出路由决策,不检查请求内容。

特点:

  • 更快,因为不需要分析内容。
  • 适合非HTTP服务(数据库、邮件、游戏服务器)。
  • 不能基于URL路径或HTTP头部进行路由。

第7层负载均衡器(应用层)

在应用层运行,能够读取和分析HTTP请求内容。基于URL、头部、Cookie和请求体做出路由决策。

特点:

  • 更灵活——可以将/api路由到API服务器,将/images路由到图片服务器。
  • 支持SSL终止、压缩和缓存。
  • 由于需要内容检查,比第4层略慢。
  • 最常用于Web应用程序。

全局服务器负载均衡(GSLB)

在全球级别分配流量,将用户路由到最近的数据中心。通常使用基于DNS的路由结合健康检查。

常用负载均衡算法

轮询(Round Robin)

按顺序循环分配请求:服务器1 → 服务器2 → 服务器3 → 服务器1 → ...

优点: 简单,易于实现。 缺点: 不考虑各服务器的实际容量。如果服务器配置不同,较弱的服务器会过载。

加权轮询(Weighted Round Robin)

类似轮询但为每台服务器分配权重。更强的服务器获得更高权重,接收更多请求。

示例:服务器A(权重5)、服务器B(权重3)、服务器C(权重2)→ 每10个请求中,A接收5个,B接收3个,C接收2个。

最少连接(Least Connections)

将请求发送到活跃连接最少的服务器。适合请求处理时间不均匀的场景——处理完成更早的服务器更快接收新请求。

加权最少连接(Weighted Least Connections)

将最少连接与权重相结合。同时考虑当前连接数和服务器容量。

IP哈希(IP Hash)

使用客户端IP的哈希值来确定服务器。相同的IP始终被导向同一台服务器——无需复杂的粘性会话机制即可确保会话持久性

最快响应时间(Least Response Time)

将请求发送到响应时间最快且连接最少的服务器。最智能的算法,确保用户始终由最快的服务器服务。

随机(Random)

随机选择服务器。简单且在服务器数量大、流量高时出奇地有效(根据大数定律)。

算法对比表

算法 复杂度 最佳用例 感知会话 感知容量
轮询 O(1) 相同服务器,短请求
加权轮询 O(1) 不同配置的服务器 是(静态)
最少连接 O(n) 请求处理时间不同 是(动态)
加权最少连接 O(n) 不同服务器,多样请求 是(两者)
IP哈希 O(1) 需要会话持久性
最快响应时间 O(n) 要求最高性能 是(动态)

健康检查——服务器健康监控

负载均衡器持续监控后端服务器的状态,确保只将流量发送到健康的服务器。

主动健康检查

负载均衡器主动定期向每台服务器发送检查请求(健康检查探针):

  • HTTP健康检查: 向特定端点(通常是/health)发送GET请求,检查状态码是否为200。
  • TCP健康检查: 验证TCP连接是否成功。
  • 自定义检查: 测试更复杂的条件(数据库连接、磁盘空间、内存使用)。

被动健康检查

在处理实际请求时监控服务器的响应。如果服务器返回过多错误(5xx)或超时,负载均衡器将其标记为不健康。

故障处理

当服务器被标记为不健康时:

  1. 负载均衡器停止向该服务器发送新请求。
  2. 当前请求可能在另一台服务器上重试。
  3. 健康检查继续运行——当服务器恢复时,负载均衡器自动将其添加回池中。

会话持久性(粘性会话)

某些应用程序要求来自同一用户的所有请求必须发送到同一台服务器(例如:购物车、登录会话)。几种处理方法:

负载均衡器在响应中添加包含服务器信息的Cookie。后续携带此Cookie的请求被发送到同一台服务器。

源IP绑定

使用客户端IP绑定到特定服务器(类似IP哈希)。

应用层解决方案

最佳方案是设计无状态应用——将会话数据存储在共享存储(Redis、数据库)中而不是服务器上。这样,任何服务器都可以处理任何请求。

常用负载均衡器解决方案

软件负载均衡器

  • Nginx: 兼具Web服务器、反向代理和负载均衡器功能。高性能,配置灵活,免费。当前最流行的选择。

  • HAProxy: 专用负载均衡器,性能极高。被GitHub、Stack Overflow等大公司使用。

  • Traefik: 为容器环境(Docker、Kubernetes)设计。自动发现和配置服务。

  • Envoy: 由Lyft开发的现代微服务架构代理。常用作服务网格中的边车代理。

云负载均衡器

  • AWS弹性负载均衡(ELB): 应用负载均衡器(ALB)用于第7层,网络负载均衡器(NLB)用于第4层。

  • Google Cloud负载均衡: 支持全局负载均衡,自动扩展。

  • Azure负载均衡器: 与Azure生态系统集成。

硬件负载均衡器

  • F5 BIG-IP: 具有高级性能和安全功能的企业解决方案。
  • Citrix ADC: 面向大型企业的应用交付控制器。

负载均衡器与代理

负载均衡器与代理有密切关系:

反向代理作为负载均衡器

Nginx和HAProxy同时充当反向代理和负载均衡器。它们接收客户端请求,确定合适的后端服务器并转发请求——这正是反向代理与负载均衡算法相结合的功能。

代理负载均衡

在使用代理的系统中(网页爬虫、广告验证),负载均衡器将请求分配到不同的代理以优化性能并避免单个代理过载。TMProxy集成了内部负载均衡机制,自动将请求分配到超过1000万个IP的代理池中。

实际部署架构

单负载均衡器

最简单的架构——一个负载均衡器在多台服务器前面。缺点:负载均衡器是单点故障。

主动-被动(故障转移)

两个负载均衡器——一个主动处理流量,一个被动待命。当主动发生故障时,被动自动接管(故障转移)。

主动-主动

两个负载均衡器都处于活跃状态,共享流量。比主动-被动更好地利用资源,并消除单点故障。

监控与关键指标

有效运营负载均衡器需要全面的监控。以下是最需要跟踪的关键指标:

每秒请求数(RPS)

负载均衡器每秒处理的请求数量。此指标表明系统当前的负载,并帮助预测何时需要扩展。随时间跟踪RPS以识别流量模式并相应地规划容量。

活跃连接数

每台后端服务器上的并发活跃连接数。如果一台服务器的活跃连接数异常高于其他服务器,可能需要调整均衡算法,或该服务器正在经历请求处理缓慢。

错误率

失败请求(HTTP 4xx和5xx)的百分比。错误率突然飙升可能表明:后端服务器故障、部署问题或系统过载。当错误率超过正常阈值(通常为1-5%)时设置告警。

响应时间(p50、p95、p99)

响应时间百分位数比平均值更重要。p50显示大多数用户的体验,p95揭示最慢5%用户的体验,p99捕获严重的异常值。如果p99比p50高出许多倍,系统存在尾延迟问题。

后端健康状态

每台后端服务器的健康检查状态:健康、不健康或排空中。跟踪健康状态历史有助于检测"抖动"服务器(在健康和不健康之间不断切换)——这是硬件或配置问题的信号。

带宽(吞吐量)

每秒通过负载均衡器的数据量(字节)。监控带宽确保不超过网络接口限制,并帮助在需要时规划升级。异常的带宽模式可能表明DDoS攻击或数据泄露。

常用监控工具: Prometheus + Grafana是负载均衡器监控中使用最广泛的组合。Datadog、New Relic和AWS CloudWatch也是云环境中的热门选择。

不要忽视p99延迟

平均值可能掩盖严重问题。如果p99是p50的10倍,1%的用户正在经历糟糕的体验——足以影响转化率和品牌形象。始终基于p95/p99而非平均值设置告警。

真实案例研究

Netflix——全球规模的负载均衡

Netflix为全球超过2亿用户提供服务,使用多层负载均衡架构。在全球层,Netflix使用基于DNS的负载均衡将用户路由到最近的AWS区域。在区域层,Zuul(他们自主开发的API网关)充当第7层负载均衡器,将请求分发到数千个微服务实例。Netflix还开发了Eureka用于服务发现和Ribbon用于客户端负载均衡,使每个服务能够在调用其他服务时自行进行负载均衡。

GitHub——为数百万开发者提供的HAProxy

GitHub使用HAProxy作为主要负载均衡器,每天处理数百万次git操作和Web请求。选择HAProxy是因为其极高的性能和处理数十万并发连接的能力。GitHub部署了多个HAProxy实例的主动-主动架构,结合自定义健康检查确保流量仅路由到正常运行的服务器。维护期间,通过负载均衡器优雅地排空各服务器的流量。

电商闪购——处理流量高峰

在闪购活动期间(双十一、黑色星期五),流量可能在几秒内飙升到正常水平的10-50倍。电商平台使用多层负载均衡策略:全局负载均衡器跨数据中心分配、应用负载均衡器跨服务器组分配(产品目录、购物车、支付),每个组根据负载均衡器指标自动扩展。队列系统(Redis、RabbitMQ)位于负载均衡器之后,对支付处理等敏感服务进行流量节流。

总结: 负载均衡器是现代系统架构的基本组件,确保应用始终可用、快速且可扩展。无论您运营的是小型网站还是复杂的微服务系统,了解负载均衡将帮助您设计稳健的基础设施,准备好应对任何级别的流量。

参考资料

常见问题

常见问题Q&A
什么是负载均衡器,它是如何工作的?
负载均衡器是位于客户端和服务器组之间的设备或软件,将传入的请求分配到后端服务器以均匀分布负载。它持续检查服务器健康状况,只将流量发送到正常运行的服务器。
第4层和第7层负载均衡器有什么区别?
第4层在传输层运行,基于IP和端口进行路由——速度快但不够灵活。第7层在应用层运行,可以读取HTTP请求——更灵活,能够根据URL路径、头部和Cookie进行路由。
哪种负载均衡算法最常用?
轮询是最简单和最流行的算法,适合相同配置的服务器。最少连接适合请求处理时间不同的场景。加权轮询适合不同配置的服务器。最快响应时间最智能但更复杂。
小型网站需要负载均衡器吗?
单台服务器的小型网站可能暂时不需要。但当流量增长或需要高可用性(99.99%)时,负载均衡器变得必不可少,可以消除单点故障并实现水平扩展。
什么是粘性会话,什么时候需要使用?
粘性会话(会话持久性)确保来自同一用户的请求始终发送到同一台服务器。当应用在服务器上存储会话数据(购物车、登录)时需要使用。更好的方案是设计无状态应用,使用Redis等共享存储。

Load Balancers are critical components of modern system architecture, intelligently distributing traffic across multiple servers. This article explains in detail what a load balancer is, popular load balancing algorithms, health checks, session persistence, and real-world deployment architectures.

What is a Load Balancer?

A Load Balancer is a device or software that sits between clients and a group of servers (server pool/server farm), responsible for distributing incoming user requests to backend servers so that the load is evenly spread — preventing any single server from being overwhelmed while others sit idle.

As your website or application grows and user traffic increases, a single server can no longer handle all requests. This is where a Load Balancer comes into play — intelligently distributing traffic across multiple servers to ensure your system remains stable and responsive.

A Real-World Analogy

Imagine a restaurant with 5 checkout counters. If all customers line up at just one counter, wait times would be extremely long despite 4 other counters being free. A load balancer is like the host directing customers to the least busy counter, ensuring all counters are utilized and customers wait as little as possible.

Why Do You Need a Load Balancer?

High Availability

If you have only one server and it fails, your entire service goes down. With a load balancer:

  • Traffic is automatically redirected to remaining healthy servers.
  • The system can tolerate the failure of one or more servers without affecting users.
  • Achieving 99.99% uptime or higher becomes possible.

Scalability

Load balancers enable horizontal scaling — adding new servers to the pool when traffic increases, instead of upgrading existing hardware (vertical scaling). Horizontal scaling is far more flexible and cost-effective.

Optimal Performance

Even load distribution across servers ensures:

  • No server becomes overloaded.
  • Consistent response times for all users.
  • Maximum utilization of hardware resources.

Zero-Downtime Maintenance

You can remove individual servers from the pool for maintenance or updates without affecting the service. The load balancer automatically distributes traffic to the remaining servers.

Types of Load Balancers

Layer 4 Load Balancer (Transport Layer)

Operates at the Transport layer (TCP/UDP) of the OSI model. Makes routing decisions based on network information like source/destination IP and port number, without inspecting request content.

Characteristics:

  • Faster because it doesn't analyze content.
  • Suitable for non-HTTP services (databases, email, game servers).
  • Cannot route based on URL path or HTTP headers.

Layer 7 Load Balancer (Application Layer)

Operates at the Application layer, capable of reading and analyzing HTTP request content. Makes routing decisions based on URL, headers, cookies, and request body.

Characteristics:

  • More flexible — can route /api to API servers and /images to image servers.
  • Supports SSL termination, compression, and caching.
  • Slightly slower than Layer 4 due to content inspection.
  • Most popular for web applications.

Global Server Load Balancing (GSLB)

Distributes traffic at a global level, routing users to the nearest datacenter. Typically uses DNS-based routing combined with health checks.

Round Robin

Distributes requests sequentially in a circular pattern: Server 1 → Server 2 → Server 3 → Server 1 → ...

Pros: Simple, easy to implement. Cons: Doesn't account for actual server capacity. If servers have different specs, weaker servers will be overloaded.

Weighted Round Robin

Similar to Round Robin but assigns weights to each server. Stronger servers get higher weights and receive more requests.

Example: Server A (weight 5), Server B (weight 3), Server C (weight 2) → For every 10 requests, A receives 5, B receives 3, C receives 2.

Least Connections

Sends requests to the server with the fewest active connections. Ideal when request processing times vary — servers that finish earlier receive new requests sooner.

Weighted Least Connections

Combines Least Connections with weights. Considers both current connection count and server capacity.

IP Hash

Uses a hash of the client IP to determine the server. The same IP is always directed to the same server — ensuring session persistence without complex sticky session mechanisms.

Least Response Time

Sends requests to the server with the fastest response time and fewest connections. The smartest algorithm, ensuring users are always served by the fastest server.

Random

Selects a server randomly. Simple and surprisingly effective when server count is large and traffic is high (by the law of large numbers).

Algorithm Comparison Table

Algorithm Complexity Best Use Case Session-Aware Capacity-Aware
Round Robin O(1) Identical servers, short requests No No
Weighted Round Robin O(1) Mixed server specs No Yes (static)
Least Connections O(n) Varying request durations No Yes (dynamic)
Weighted Least Conn. O(n) Mixed servers, diverse requests No Yes (both)
IP Hash O(1) Session persistence needed Yes No
Least Response Time O(n) Maximum performance required No Yes (dynamic)

Health Checks — Server Health Monitoring

Load balancers continuously monitor the status of backend servers to ensure traffic is only sent to healthy servers.

Active Health Check

The load balancer proactively sends check requests (health check probes) to each server periodically:

  • HTTP Health Check: Sends a GET request to a specific endpoint (usually /health), checking for status code 200.
  • TCP Health Check: Verifies if a TCP connection succeeds.
  • Custom Check: Tests more complex conditions (database connection, disk space, memory usage).

Passive Health Check

Monitors responses from servers during actual request processing. If a server returns too many errors (5xx) or timeouts, the load balancer marks it as unhealthy.

Failure Handling

When a server is marked unhealthy:

  1. The load balancer stops sending new requests to that server.
  2. Current requests may be retried on another server.
  3. Health checks continue — when the server recovers, the load balancer automatically adds it back to the pool.

Session Persistence (Sticky Sessions)

Some applications require all requests from the same user to go to the same server (e.g., shopping cart, login session). Several approaches handle this:

The load balancer adds a cookie to the response containing information about the serving server. Subsequent requests carrying this cookie are sent to the same server.

Source IP Affinity

Uses the client IP to bind to a specific server (similar to IP Hash).

Application-Level Solution

The best approach is designing stateless applications — storing session data in shared storage (Redis, database) instead of on the server. This way, any server can handle any request.

Software Load Balancers

  • Nginx: Serves as a web server, reverse proxy, and load balancer. High performance, flexible configuration, free. The most popular choice today.

  • HAProxy: A dedicated load balancer with extremely high performance. Used by major companies like GitHub and Stack Overflow.

  • Traefik: Designed for container environments (Docker, Kubernetes). Automatically discovers and configures services.

  • Envoy: A modern proxy for microservices architecture, developed by Lyft. Commonly used as a sidecar proxy in service meshes.

Cloud Load Balancers

  • AWS Elastic Load Balancing (ELB): Application Load Balancer (ALB) for Layer 7, Network Load Balancer (NLB) for Layer 4.

  • Google Cloud Load Balancing: Supports global load balancing with automatic scaling.

  • Azure Load Balancer: Integrated with the Azure ecosystem.

Hardware Load Balancers

  • F5 BIG-IP: An enterprise solution with premium performance and security features.
  • Citrix ADC: Application Delivery Controller for large enterprises.

Load Balancer and Proxy

Load balancers have a close relationship with proxies:

Reverse Proxy as Load Balancer

Nginx and HAProxy function as both reverse proxies and load balancers. They receive requests from clients, determine the appropriate backend server, and forward requests — this is the function of a reverse proxy combined with a load balancing algorithm.

Proxy Load Balancing

In systems using proxies (web scraping, ad verification), load balancers distribute requests across different proxies to optimize performance and avoid overloading a single proxy. TMProxy integrates internal load balancing to automatically distribute requests across a pool of over 10 million IPs.

Real-World Deployment Architecture

Single Load Balancer

The simplest architecture — one load balancer in front of multiple servers. Drawback: the load balancer is a single point of failure.

Active-Passive (Failover)

Two load balancers — one active handling traffic, one passive on standby. When the active fails, the passive automatically takes over (failover).

Active-Active

Both load balancers are active, sharing traffic. Better resource utilization than Active-Passive and eliminates single point of failure.

Monitoring and Key Metrics

Operating a load balancer effectively requires comprehensive monitoring. Here are the most critical metrics to track:

Requests Per Second (RPS)

The number of requests the load balancer processes per second. This metric indicates the current system load and helps predict when you need to scale. Track RPS over time to identify traffic patterns and plan capacity accordingly.

Active Connections

The number of concurrent active connections per backend server. If one server has unusually high active connections compared to others, the balancing algorithm may need adjustment, or that server may be experiencing slow request processing.

Error Rate

The percentage of failed requests (HTTP 4xx and 5xx). A sudden spike in error rate can indicate: backend server failures, deployment issues, or system overload. Set alerts when error rate exceeds normal thresholds (typically 1-5%).

Response Time (p50, p95, p99)

Response time percentiles are more important than averages. p50 shows the experience of most users, p95 reveals the experience of the slowest 5% of users, and p99 catches severe outliers. If p99 is many times higher than p50, the system has a tail latency problem.

Backend Health Status

The health check status of each backend server: healthy, unhealthy, or draining. Tracking health status history helps detect "flapping" servers (constantly switching between healthy and unhealthy) — a sign of hardware or configuration issues.

Bandwidth (Throughput)

The amount of data (bytes) passing through the load balancer per second. Monitoring bandwidth ensures you don't exceed network interface limits and helps plan upgrades when needed. Unusual bandwidth patterns may indicate DDoS attacks or data leaks.

Popular Monitoring Tools: Prometheus + Grafana is the most widely used combination for load balancer monitoring. Datadog, New Relic, and AWS CloudWatch are also popular choices for cloud environments.

Don't ignore p99 latency

Average values can hide serious problems. If p99 is 10x higher than p50, 1% of your users are having a terrible experience — enough to impact conversion rate and brand image. Always alert on p95/p99, not averages.

Real-World Case Studies

Netflix — Global-Scale Load Balancing

Netflix serves over 200 million users worldwide using a multi-layered load balancing architecture. At the global tier, Netflix uses DNS-based load balancing to route users to the nearest AWS region. At the regional tier, Zuul (their custom API gateway) acts as a Layer 7 load balancer, distributing requests to thousands of microservice instances. Netflix also developed Eureka for service discovery and Ribbon for client-side load balancing, enabling each service to load-balance its own calls to other services.

GitHub — HAProxy for Millions of Developers

GitHub uses HAProxy as its primary load balancer, handling millions of git operations and web requests daily. HAProxy was chosen for its extremely high performance and ability to handle hundreds of thousands of concurrent connections. GitHub deploys an Active-Active architecture with multiple HAProxy instances, combined with custom health checks to ensure traffic only routes to properly functioning servers. During maintenance, individual servers are gracefully drained of traffic through the load balancer.

E-Commerce Flash Sales — Handling Traffic Spikes

During flash sale events (Singles' Day, Black Friday), traffic can surge 10-50x above normal levels within seconds. E-commerce platforms use multi-tier load balancing strategies: Global load balancers distribute across datacenters, Application load balancers distribute across server groups (product catalog, cart, payment), and each group auto-scales based on load balancer metrics. Queue systems (Redis, RabbitMQ) sit behind the load balancer to throttle traffic to sensitive services like payment processing.

Conclusion: Load Balancers are essential components of modern system architecture, ensuring applications remain available, fast, and scalable. Whether you're running a small website or a complex microservices system, understanding load balancing will help you design robust infrastructure ready to handle any level of traffic.

Sources

Frequently Asked Questions

Frequently Asked QuestionsQ&A
What is a Load Balancer and how does it work?
A Load Balancer is a device or software that sits between clients and a group of servers, distributing incoming requests across backend servers to spread the load evenly. It continuously checks server health and only sends traffic to servers that are functioning properly.
What is the difference between Layer 4 and Layer 7 Load Balancers?
Layer 4 operates at the Transport layer, routing based on IP and port — fast but inflexible. Layer 7 operates at the Application layer, reading HTTP requests — more flexible, capable of routing by URL path, headers, and cookies.
Which load balancing algorithm is most popular?
Round Robin is the simplest and most popular for identical servers. Least Connections works well with varying request durations. Weighted Round Robin suits mixed server specs. Least Response Time is the smartest but more complex.
Do small websites need a Load Balancer?
Small websites with a single server may not need one initially. However, when traffic grows or high uptime (99.99%) is required, a load balancer becomes essential to eliminate single points of failure and enable horizontal scaling.
What is a sticky session and when should I use it?
A sticky session (session persistence) ensures requests from the same user always go to the same server. It's needed when applications store session data on the server (shopping cart, login). A better approach is designing stateless apps with shared storage like Redis.