Load Balancing Layer 4 VS. Layer 7
Layer 4 load balancing uses information defined at the networking transport layer(Layer 4) as the basis for deciding how to distribute client requests across a group of servers. For Internet traffic specifically, a Layer 4 load balancer bases the load-balancing decision on the source and destination IP addresses and ports recorded in the packet header, without considering the content of the packet.
At Layer 4, a load balancer has visibility on network information such as application ports and protol(TCP/UDP). The load balancer delivers traffic by combining this limited network information with a load balancing algorithm such as round-robin and by calculating the best destination server based on the least connections or server response times.
Layer 7 load balancers operate at the highest level in the OSI model, the application layer(on the internet, HTTP is the dominant protocol at this layer). Layer 7 load balancers base their routing decisions on various characteristics of the HTTP header and on the actual contents of the messages, such as the URL, the type of data(text, video, graphics), or information in a cookie.
At Layer 7, a load balancer has application awareness and can use this additional application information to make more complex and informed load balancing decisions. With a protocol such as HTTP, a load balancer can uniquely identify client sessions based on cookies and use this information to deliver all a clients requests to the same server. This server persistence using cookies can be based on the server's cookie or by active cookie injection where a load balancer cookie is inserted into the connection.