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

Layer 4 vs Layer 7 Load Balancers

Balance by connection, or read the request and balance by what it asks for.

โฑ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Load balancers work at different layers of the network. A Layer 4 balancer looks only at IP addresses and ports. A Layer 7 balancer reads the HTTP request itself.

  • Layer 4 (transport): balances TCP or UDP connections. Very fast and simple. It does not know what is inside.
  • Layer 7 (application): can route by host, path, header or cookie, decrypt HTTPS, and change requests. It needs more CPU.
  • Many systems use both: a Layer 4 balancer in front for raw speed, and Layer 7 balancers behind it for smart routing.

02Concept: What is it?

The numbers 4 and 7 come from the OSI model. Layer 4 is the transport layer (TCP and UDP, with ports). Layer 7 is the application layer (HTTP, gRPC, and so on). A load balancer is named after the highest layer it understands.

A Layer 4 load balancer sees a connection as a source address, a source port, a destination address and a destination port. It picks a backend server for the connection and then forwards the packets of that connection to the same server. It never needs to understand what the bytes mean, so it works for web traffic, databases, game servers, DNS or anything else on TCP and UDP.

A Layer 7 load balancer accepts the connection itself, reads the full HTTP request (method, host, path, headers, cookies), and then decides where to send that request. It usually opens its own connection to the backend. This lets it do clever things, but it has to do much more work for each request.

What each type can see
7Layer 7: HTTP requesthost, path, headers, cookies, body
Layer 6 to 5: TLS and sessionsencryption (the content is hidden unless decrypted)
4Layer 4: TCP / UDPsource and destination port
3Layer 3: IPsource and destination address
Layer 4 balancer sees these Layer 7 balancer also sees these
Layer 4 reads the envelope. Layer 7 opens the envelope and reads the letter.
๐Ÿง One question tells them apart
Does the balancer need to read the request to decide? If yes (route /api to the API servers) you need Layer 7. If it only needs to spread connections, Layer 4 is enough.

03Real-Life Example

๐ŸตThe Mail Room and the Reception Desk
A company has two ways to handle incoming mail. The mail room never opens anything. It looks at the outside of each parcel, sees the building number, and puts it on the next free trolley. That is quick, and it works for every kind of parcel. The reception desk opens each letter, reads who it is for and what it is about, and walks it to the exact department: billing, support or sales. That takes longer, but nothing ends up in the wrong place.
Mail handling
Load balancing
Mail room, only reads the outside
Layer 4: addresses and ports
Reception desk, reads the letter
Layer 7: the HTTP request
Putting parcels on the next free trolley
Spreading connections over servers in turn
Walking a letter to the right department
Routing /api to API servers, /static to static servers
Opening sealed letters
Terminating TLS (decrypting HTTPS)
Sealed envelopes the desk cannot open
TLS passthrough: Layer 7 cannot read the content
Reception is slower and needs more staff
Layer 7 costs more CPU and memory
Same requests, two different paths
Layer 4
๐Ÿ“จAny request/api, /static, /
โ†“next server in turn
๐Ÿ–ฅ๏ธServer A
๐Ÿ–ฅ๏ธServer B
๐Ÿ–ฅ๏ธServer C
Layer 7
๐Ÿ“จRead the path
โ†“/api
โ†“/static
โš™๏ธAPI pool
๐Ÿ–ผ๏ธStatic pool

04Why Do We Need It?

โšกRaw speed (L4)
No parsing, no decryption. A Layer 4 balancer can handle huge numbers of connections with very little CPU.
๐ŸงญSmart routing (L7)
Send /api to one pool, /images to another, and one domain to a different team.
๐Ÿ”TLS in one place (L7)
Decrypt HTTPS once at the balancer, so backends do not each hold certificates.
๐Ÿ”ŒAny protocol (L4)
Databases, game servers, mail and DNS are not HTTP. Layer 4 can balance them all.
๐ŸงชSafer releases (L7)
Send 5 percent of requests, or only requests with a test header, to a new version.
๐Ÿ›ก๏ธRequest-level controls (L7)
Rate limits, header rewrites, redirects and basic filtering can live at the edge.
Layer 4 spreads connections quickly. Layer 7 understands requests and routes them cleverly. Pick the lowest layer that does the job.

05Where Do We Use It?

๐ŸŒWebsites and APIs
A Layer 7 balancer routes by host and path to the right service.
๐Ÿ—„๏ธDatabases and caches
Layer 4 spreads TCP connections to replicas or proxies.
๐ŸŽฎGames and real-time media
UDP traffic is balanced at Layer 4, where speed matters more than content.
โ˜๏ธCloud load balancers
Clouds usually offer both kinds, for example a network (Layer 4) and an application (Layer 7) load balancer.
โ˜ธ๏ธKubernetes
A Service load-balances at Layer 4. An Ingress or gateway adds Layer 7 rules.
๐Ÿ•ธ๏ธService meshes
Sidecar proxies balance each request at Layer 7, even between services.

06Types / Parts / How It Works

Side by side

Layer 4 load balancer
Works on connections
  • Sees IP addresses and ports only
  • Forwards packets or connections without reading them
  • Fast, low CPU, low latency
  • Works for any TCP or UDP protocol
  • Cannot route by path, host or cookie
  • Cannot see inside HTTPS
Layer 7 load balancer
Works on requests
  • Reads host, path, headers and cookies
  • Routes each request on its own
  • Can terminate TLS, redirect, rewrite and compress
  • Needs more CPU and memory
  • Understands specific protocols such as HTTP, HTTP/2 and gRPC
  • Becomes a bigger target, because it handles decrypted data

Routing rules a Layer 7 balancer can use

Look atExample ruleUse
Host headerapi.example.com goes to the API poolMany sites behind one IP address
URL path/static/* goes to the static serversSplit one site across services
Headerx-beta: 1 goes to the new versionTesting and canary releases
CookieA session cookie goes to the same serverSticky sessions
MethodPOST goes to the write clusterSeparate read and write paths

Three ways a Layer 4 balancer can forward

MethodHow it worksGood and bad
Proxy (connection split)Accepts the client connection and opens a second one to the serverSimple and flexible. The server sees the balancer's address unless the client IP is passed on (for example with the PROXY protocol).
NAT (address rewrite)Rewrites the destination address of packets to the chosen serverFast. Replies must go back through the balancer.
Direct server returnThe server replies straight to the client, skipping the balancerVery high throughput for big replies. Needs special network set-up.
๐Ÿ“Note
TLS passthrough lets a Layer 7 balancer pass encrypted traffic on without decrypting it. In that mode it can only route like Layer 4, because the HTTP request is hidden.
VisualizerLayer 4 vs Layer 7: what can the balancer see, and where does each request go?Switch between Layer 4 and Layer 7 and watch where the eight requests land. Then choose TLS passthrough, and switch to identical servers to see when smart routing is not needed.
Load balancer type
HTTPS handling
Backend servers
The balancer reads the HTTP request:
1GET shop.example.com/ cookie: noneWeb 1served
2GET shop.example.com/api/cart cookie: session=u1API 1served
3GET shop.example.com/static/logo.png cookie: noneStatic 1served
4GET api.example.com/v1/orders cookie: token=xAPI 2served
5POST shop.example.com/api/pay cookie: session=u2API 1served
6GET shop.example.com/static/app.js cookie: noneStatic 1served
7GET shop.example.com/about cookie: noneWeb 2served
8GET api.example.com/v1/users cookie: token=yAPI 2served
Web 1 (web): 1API 1 (api): 2Static 1 (static): 2Web 2 (web): 1API 2 (api): 2
Served correctly
8/8
right kind of server
Can read the path
yes
needs Layer 7 plus decryption
Work (illustrative)
56
made-up units
Layer 7 read each request, then sent /api and the api host to the API pool and /static to the static server. The price is more work per request (56 units against 8 for Layer 4).

Simplified: every request here is its own connection, and Layer 4 takes the five servers in turn. In real life one connection often carries many requests, so Layer 4 balances connections, not requests. The work units are made up to show the shape of the trade-off (1 for Layer 4, 4 to read HTTP, +3 to decrypt).

07How to Use It / Steps / Implementation

Choosing and using each type

  1. 1
    Start with what you must read
    List the routing rules you need. Host, path or header rules mean Layer 7. Pure spreading of connections means Layer 4.
  2. 2
    Check the protocol
    Not HTTP (database, MQTT, a game protocol, plain TCP)? Use Layer 4. HTTP, HTTP/2 or gRPC with routing needs? Use Layer 7.
  3. 3
    Decide where TLS ends
    Terminate at a Layer 7 balancer for simple certificate handling and routing. Use passthrough or re-encrypt to the backend when traffic must stay encrypted all the way.
  4. 4
    Keep the client IP
    A proxy hides it. Pass it on with the X-Forwarded-For header (Layer 7) or the PROXY protocol (Layer 4), and make the backend trust it only from the balancer.
  5. 5
    Add health checks
    Both types must stop sending traffic to a sick server. Layer 7 can run a real HTTP check, Layer 4 usually checks that the port accepts connections.
  6. 6
    Combine them if needed
    A Layer 4 balancer in front spreads load over several Layer 7 balancers, which then route requests. This scales the smart tier.
A Layer 7 routing rule (Nginx style, example only)
location /api/    { proxy_pass http://api_pool; }
location /static/ { proxy_pass http://static_pool; }
location /        { proxy_pass http://web_pool; }
๐Ÿ’กDo not over-engineer
If every server can answer every request, plain Layer 4 (or a basic Layer 7 round robin) is enough. Add routing rules only when they solve a real problem.

08Key Terms to Know

TermMeaning in easy words
Layer 4The transport layer: TCP and UDP, with ports
Layer 7The application layer: protocols such as HTTP
Connection-level balancingChoosing a server once per connection (Layer 4)
Request-level balancingChoosing a server for each request (Layer 7)
TLS terminationDecrypting HTTPS at the balancer
TLS passthroughForwarding encrypted traffic without reading it
Content-based routingRouting by host, path, header or cookie
Reverse proxyA server that accepts client requests and forwards them to backends
X-Forwarded-ForAn HTTP header that carries the original client IP through proxies
PROXY protocolA small header that passes the client address through a Layer 4 proxy
Direct server returnA mode where the server answers the client without going back through the balancer

09Pros, Cons and Trade-offs

โœ… Pros
  • Layer 4 is fast, light and works for any TCP or UDP protocol
  • Layer 7 gives smart routing by host, path, header and cookie
  • Layer 7 centralises TLS, redirects and basic security rules
  • Layer 7 allows canary releases and A/B routing
  • Both give higher availability than a single server
โš ๏ธ Cons
  • Layer 4 cannot make decisions based on content
  • Layer 7 needs more CPU, memory and tuning
  • Layer 7 sees decrypted data, so it must be well protected
  • A balancer can become a bottleneck or a single point of failure
  • Hidden client IPs need extra set-up

Trade-offs

ChoiceWe gainWe lose
Layer 4 onlySpeed, simplicity, any protocolNo content-based routing
Layer 7 onlyRouting, TLS handling, rich featuresMore CPU and more things that can go wrong
L4 in front of L7Scales the smart tier, keeps routing powerTwo layers to run and monitor
Terminate TLS at the balancerRouting and one place for certificatesTraffic inside is plain unless you re-encrypt
TLS passthroughEncrypted all the way to the backendNo Layer 7 routing on the content
Per-request balancingEven load, even with long-lived connectionsMore work for the balancer

10Common Problems and Mistakes

Common mistakes

  1. Using Layer 4 and expecting path routing. It cannot see the path, so /api and /static are mixed.
  2. Using Layer 7 for everything. Paying for HTTP parsing on a plain TCP workload wastes CPU and adds latency.
  3. Long-lived connections and uneven load. With HTTP/2 or gRPC, one connection carries many requests. A Layer 4 balancer spreads connections, not requests, so one server can be much busier.
  4. Losing the client IP. Logs and rate limits all show the balancer's address.
  5. Trusting X-Forwarded-For from anyone. A client can fake it. Accept it only from your own balancer.
  6. One balancer, no backup. The balancer becomes a single point of failure. Run at least two.
  7. Plain traffic behind the balancer. After TLS termination, internal traffic is unencrypted unless you set up re-encryption.

Things to watch

๐ŸงตConnection reuse
Keep-alive and HTTP/2 mean few connections carry many requests. Check how requests, not just connections, are spread.
๐Ÿ”Timeouts
A Layer 7 balancer holds two connections. Idle and request timeouts must match on both sides.
๐Ÿ“ˆCapacity
TLS handshakes and request parsing use CPU. Watch connections per second and CPU together.
๐ŸงฏFailure mode
Decide what the balancer does when all backends fail: return an error page, or keep trying.

11Real-World Examples

โ˜๏ธCloud providers
Major clouds sell a network (Layer 4) load balancer and an application (Layer 7) load balancer as separate products.
๐ŸชฝNginx and HAProxy
Both can act as Layer 7 balancers for HTTP and as Layer 4 balancers for plain TCP.
โ˜ธ๏ธKubernetes
Services balance connections at Layer 4. Ingress controllers and gateways add host and path rules.
๐Ÿ›๏ธLarge web shops
A fast Layer 4 tier spreads connections, and a Layer 7 tier routes to catalog, cart and checkout services.
๐ŸŽฎOnline games
UDP game traffic is balanced at Layer 4 for low latency.
๐Ÿ“กgRPC services
Because one HTTP/2 connection carries many calls, teams use a Layer 7 aware balancer to spread calls.
๐Ÿ“Note
Product features and names change between providers and versions. Check the current documentation of your balancer.
Mini case: two tiers
๐ŸŒUsers
โ†’โ†“connections
โš–๏ธLayer 4spreads connections
โ†’โ†“to 2 proxies
๐ŸงญLayer 7routes requests
โ†’โ†“by path
โš™๏ธAPI
๐Ÿ–ผ๏ธStatic
Layer 4 absorbs the connection volume. Layer 7 applies the routing rules.

12Related Topics to Read Next

What are Load Balancers?โ†’

The big picture of why we balance traffic.

Load Balancing Algorithmsโ†’

How a balancer picks the server, at either layer.

OSI Modelโ†’

Where Layer 4 and Layer 7 come from.

Health Checksโ†’

How both types stop sending traffic to a sick server.

Sticky Sessionsโ†’

A Layer 7 feature that keeps a user on one server.

Proxy vs Reverse Proxyโ†’

A Layer 7 balancer is a reverse proxy.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Layer 4: IP and port only. Connection-level. Fast, simple, any TCP or UDP protocol.
  • โœ”Layer 7: reads HTTP. Request-level. Routes by host, path, header, cookie.
  • โœ”Layer 7 extras: TLS termination, redirects, rewrites, canary routing.
  • โœ”Cost: Layer 7 uses more CPU and memory per request.
  • โœ”TLS passthrough: encrypted data goes straight through, so Layer 7 cannot read it.
  • โœ”Client IP: pass it on with X-Forwarded-For (L7) or the PROXY protocol (L4).
  • โœ”Common design: Layer 4 in front, Layer 7 behind.
  • โœ”One line: โ€œLayer 4 spreads connections fast. Layer 7 reads requests and routes them cleverly.โ€
โ† Previous
Anycast Routing
Next โ†’
Health Checks