Inferensys

Glossary

Layer 4 Load Balancing

Layer 4 load balancing is a network traffic distribution method operating at the transport layer (TCP/UDP) of the OSI model, routing packets based on IP addresses and port numbers.
ML engineer running AI model benchmarks, performance charts on multiple screens, late night home office setup.
NETWORKING

What is Layer 4 Load Balancing?

Layer 4 load balancing is a foundational network traffic distribution method that operates at the transport layer of the OSI model.

Layer 4 load balancing operates at the transport layer (TCP/UDP) of the OSI model, making routing decisions based solely on information from IP packet headers—specifically source and destination IP addresses and port numbers. This method, also known as connection-based or network load balancing, is unaware of the application content within the packets. It efficiently distributes incoming traffic by inspecting the initial TCP handshake or UDP datagram header and then forwarding the entire session to a selected backend server based on a simple algorithm like round robin or least connections.

This approach provides high-performance, low-latency traffic distribution ideal for protocols like DNS, FTP, and gaming servers, where session persistence is maintained by directing all packets from a client's IP/port tuple to the same backend instance. While less context-aware than Layer 7 load balancing, its simplicity allows for massive throughput and is the core mechanism behind Network Load Balancers (NLBs) and technologies like Direct Server Return (DSR). It is a critical component for building scalable, high-availability infrastructure and heterogeneous fleet orchestration platforms that manage raw data streams.

TRANSPORT LAYER MECHANICS

Key Characteristics of Layer 4 Load Balancing

Layer 4 load balancing operates at the transport layer (TCP/UDP) of the OSI model. It makes high-speed routing decisions based on network-level information, providing a fundamental building block for scalable and resilient infrastructure.

01

Network-Level Decision Making

Layer 4 load balancers inspect only the IP packet headers, specifically the source and destination IP addresses and TCP/UDP port numbers. They do not decrypt or inspect the payload content of packets. This allows for extremely fast routing decisions, often implemented in hardware or kernel-space software, with latencies typically under 1 millisecond. Decisions are based on simple, stateless rules like directing all traffic on port 80 (HTTP) to one server pool and traffic on port 443 (HTTPS) to another.

02

Connection-Based Routing

Routing is performed on a per-connection basis. Once a client initiates a TCP handshake (SYN packet) with the load balancer's Virtual IP (VIP), the load balancer selects a backend server and forwards all subsequent packets for that connection's 5-tuple (source IP, source port, destination IP, destination port, protocol) to the same server. This provides basic session persistence for the duration of the TCP connection, but does not inherently maintain persistence across multiple connections from the same client.

03

High Performance & Throughput

Due to its simplicity, Layer 4 load balancing is designed for maximum throughput and minimum latency. It is ideal for handling massive volumes of raw network traffic, such as:

  • Streaming media (video, audio)
  • Online gaming traffic
  • Voice over IP (VoIP)
  • Database clustering protocols
  • Any protocol where packet-level speed is more critical than content-aware routing. It efficiently distributes millions of packets per second with minimal computational overhead.
04

Transparency to Backend Servers

A Layer 4 load balancer typically operates in Direct Server Return (DSR) or Network Address Translation (NAT) mode. In NAT mode, the load balancer modifies the destination IP of the incoming packet to that of the selected backend server. The server sees the load balancer's IP as the source. This provides transparency but requires the return traffic to flow back through the load balancer. In DSR mode, the server responds directly to the client, improving efficiency but requiring more complex network configuration.

05

Health Checking at the Transport Layer

Health checks are simple and network-focused. The load balancer periodically probes backend servers by attempting to establish a TCP connection to a specified port (e.g., port 22 for SSH, 80 for HTTP). If the connection succeeds, the server is considered healthy. More advanced checks might send a basic protocol-specific probe (like an HTTP GET request) but still operate at the connection level. This is less granular than Layer 7 health checks but is faster and consumes fewer resources.

06

Common Use Cases & Limitations

Primary Use Cases:

  • Distributing non-HTTP(S) protocols (e.g., DNS, FTP, SMTP, custom TCP/UDP).
  • SSL/TLS Passthrough, where encrypted traffic is forwarded to backend servers for decryption.
  • Building high-performance, scalable foundations for applications where content-aware routing is not required.

Key Limitations:

  • Cannot make routing decisions based on HTTP headers, URLs, or cookies.
  • Cannot perform content-based switching (e.g., route /api/ to one pool and /images/ to another).
  • Provides less intelligent traffic management compared to Layer 7 (Application Layer) load balancers.
COMPARISON

Layer 4 vs. Layer 7 Load Balancing

A technical comparison of transport layer (L4) and application layer (L7) load balancing, detailing their operational characteristics, use cases, and performance trade-offs.

Feature / CharacteristicLayer 4 (Transport) Load BalancingLayer 7 (Application) Load Balancing

OSI Model Layer

Layer 4 (Transport)

Layer 7 (Application)

Decision Basis

IP addresses and TCP/UDP port numbers

Content of the message (e.g., HTTP headers, URL, cookies, message body)

Traffic Visibility

Packet headers only; payload is opaque

Full application message; can inspect and modify content

Typical Protocols

TCP, UDP

HTTP/HTTPS, gRPC, WebSocket

Session Persistence Method

Based on source/destination IP:Port tuple

Based on application data (e.g., HTTP cookie, JWT)

SSL/TLS Handling

Pass-through or termination with limited context

Full termination, inspection, and re-encryption

Routing Granularity

Per-connection or per-packet

Per-request or per-API call

Health Check Capability

Basic connectivity (TCP handshake, ICMP)

Advanced application logic (HTTP status codes, response body validation)

Processing Overhead

Low (fast packet forwarding)

High (requires parsing, decryption, inspection)

Use Case Example

Distributing database queries, gaming servers, VoIP traffic

Routing API calls to specific microservices, A/B testing, URL-based routing

TRANSPORT LAYER OPERATIONS

Common Use Cases for Layer 4 Load Balancing

Layer 4 load balancing, operating at the transport layer (TCP/UDP), is foundational for high-performance, high-availability network architectures. Its core use cases focus on efficient traffic distribution, network-level security, and seamless scaling.

01

High-Volume TCP/UDP Traffic Distribution

Layer 4 load balancers excel at distributing massive volumes of raw TCP and UDP traffic. They inspect only the IP header and port numbers, making routing decisions with ultra-low latency (often sub-millisecond). This is critical for:

  • Real-time applications like gaming, VoIP, and live video streaming.
  • Database clusters requiring fast connection routing for read replicas.
  • DNS servers handling billions of UDP-based queries. The algorithm is typically simple (e.g., round-robin, least connections), minimizing computational overhead and maximizing throughput for connection-oriented and connectionless protocols.
02

Network-Level Security & DDoS Mitigation

Operating at the transport layer allows these balancers to act as a first line of defense. They can perform TCP SYN flood mitigation by terminating client connections and validating them before proxying to backend servers. Key security functions include:

  • IP whitelisting/blacklisting based on source IP addresses.
  • Rate limiting connections per second from a single IP.
  • SSL/TLS termination, offloading expensive decryption/encryption cycles from application servers.
  • Absorbing volumetric attacks before they reach vulnerable application logic, providing a security perimeter for the entire server fleet.
03

Horizontal Scaling of Stateless Services

This is the quintessential use case for enabling elastic scalability. A Layer 4 load balancer presents a single Virtual IP (VIP) to clients while distributing requests across a dynamically changing pool of identical backend instances. It is ideal for:

  • Web server farms (e.g., Nginx, Apache clusters) where sessions are not stored locally.
  • Microservices with stateless APIs.
  • Environments using auto-scaling groups, where the balancer's health checks automatically add or remove instances from the pool. This decouples client endpoints from the underlying infrastructure, allowing for zero-downtime deployments and repairs.
04

High-Availability & Failover for Critical Infrastructure

Layer 4 balancers provide robust active-active or active-passive failover configurations for non-HTTP services. By continuously monitoring backend health via TCP health checks, they ensure traffic is only directed to healthy nodes. This is essential for:

  • Database proxy layers (e.g., for PostgreSQL or MySQL read pools).
  • Mail servers (SMTP, IMAP).
  • Custom TCP-based enterprise applications and legacy systems. The use of protocols like VRRP (Virtual Router Redundancy Protocol) allows multiple physical load balancers to share a VIP, creating a highly available load balancing service itself.
05

Global Server Load Balancing (GSLB) Foundation

Layer 4 principles are extended geographically in Global Server Load Balancing. A GSLB solution uses DNS and Layer 4 health checks to direct users to the optimal data center based on:

  • Geographic proximity (latency-based routing).
  • Data center health (active/available capacity).
  • Explicit policies (e.g., disaster recovery failover). When a user's request arrives at the chosen data center, the local Layer 4 load balancer then distributes it within the server pool. This creates a resilient, multi-region architecture for global applications.
06

Handling Long-Lived Connections & Streaming

Unlike HTTP-based (Layer 7) balancers that may inspect each request/response, Layer 4 balancers establish a connection and then largely let the packet flow. This makes them optimal for:

  • SSH, RDP, or VPN access to a pool of bastion hosts.
  • Real-time messaging protocols like MQTT or XMPP.
  • Streaming media where a single TCP connection carries a continuous flow of data.
  • Financial trading platforms requiring persistent, low-latency sockets. Once the initial routing decision is made, all packets for that connection follow the same path, ensuring consistency and performance for stateful, long-duration sessions.
LAYER 4 LOAD BALANCING

Frequently Asked Questions

Layer 4 load balancing is a foundational networking technique for distributing traffic based on IP and port information. These questions address its core mechanisms, use cases, and distinctions within modern infrastructure.

Layer 4 load balancing is a network traffic distribution method that operates at the transport layer (Layer 4) of the OSI model, making routing decisions based solely on information found in the IP and TCP/UDP headers of a packet. It works by inspecting the source and destination IP addresses and port numbers of incoming connection requests. The load balancer, acting as a virtual IP (VIP) endpoint, uses a configured algorithm (e.g., round robin, least connections, or an IP hash) to select a healthy backend server from its pool and then forwards the network packets to that server, often using Network Address Translation (NAT). The key characteristic is that it is connection-oriented; once a client's session is established with a backend server, subsequent packets for that session are sent to the same server, but the load balancer does not inspect the actual content (HTTP, gRPC, etc.) within the packets.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.