Building a Transparent Layer 4 TCP Proxy
A Layer 4 (L4) proxy forwards raw byte streams between clients and upstreams without application-layer parsing. Multiplexing both socket pairs through an event selector routes duplex traffic with microsecond latency 🔀.
import socket
c_in, c_out = socket.socketpair()
u_in, u_out = socket.socketpair()
# Forward client request to upstream backend:
c_out.sendall(b"TCP_PAYLOAD_DIRECT")
payload = c_in.recv(4096)
u_in.sendall(payload)
# Upstream receives exact bytes:
received = u_out.recv(4096)
print(f"Backend received: {received.decode()} 🔀")
for s in (c_in, c_out, u_in, u_out): s.close()
# 7. Building a Transparent Layer 4 TCP Proxy A Layer 4 (L4) proxy forwards raw byte streams between clients and upstreams without application-layer parsing. Multiplexing both socket pairs through an event selector routes duplex traffic with microsecond latency 🔀. ```python import socket c_in, c_out = socket.socketpair() u_in, u_out = socket.socketpair() # Forward client request to upstream backend: c_out.sendall(b"TCP_PAYLOAD_DIRECT") payload = c_in.recv(4096) u_in.sendall(payload) # Upstream receives exact bytes: received = u_out.recv(4096) print(f"Backend received: {received.decode()} 🔀") for s in (c_in, c_out, u_in, u_out): s.close() ``` High-performance proxies (like HAProxy, Envoy, or Cloudflare's Spectrum) operate in L4 mode for protocols like database connection pools, MQTT, and Redis clusters to avoid the CPU tax of parsing application payloads 🚀! --- ### Question What is the primary architectural advantage of a Layer 4 (L4) proxy over a Layer 7 (L7) reverse proxy? 🧠- [ ] a. L4 pipes raw byte streams directly without decoding HTTP headers or parsing bodies, minimizing memory and CPU usage 🔀 - [ ] b. L4 proxies eliminate TCP handshakes between endpoints - [ ] c. L4 proxies can only be implemented using native C extensions - [ ] d. L7 proxies cannot handle JSON payloads --- ### Challenge Forward `b'PROXY_TEST'` from `c_out` into `c_in`, and pipe it across `u_in` to `u_out`. Print the received string decoded on `u_out`. 🎯 <details> <summary>Solution</summary> ```python import socket c_in, c_out = socket.socketpair() u_in, u_out = socket.socketpair() c_out.sendall(b'PROXY_TEST') u_in.sendall(c_in.recv(1024)) print(u_out.recv(1024).decode()) for s in (c_in, c_out, u_in, u_out): s.close() ``` </details>