Unix Domain Sockets for High-Speed Local IPC
Communicating across microservices on the same host over TCP (`127.0.0.1`) wastes CPU on packet headers and checksums. Unix Domain Sockets (`AF_UNIX`) stream bytes directly across kernel memory ring buffers ⚡.
import os
import socket
sock_path = "/tmp/uds_demo.sock"
if os.path.exists(sock_path):
os.unlink(sock_path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(sock_path)
server.listen(1)
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect(sock_path)
conn, _ = server.accept()
client.sendall(b"IPC FAST")
print(f"Server received: {conn.recv(1024).decode()} ⚡")
client.close()
conn.close()
server.close()
os.unlink(sock_path)
# 81. Unix Domain Sockets for High-Speed Local IPC Communicating across microservices on the same host over TCP (`127.0.0.1`) wastes CPU on packet headers and checksums. Unix Domain Sockets (`AF_UNIX`) stream bytes directly across kernel memory ring buffers ⚡. ```python import os import socket sock_path = "/tmp/uds_demo.sock" if os.path.exists(sock_path): os.unlink(sock_path) server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) server.bind(sock_path) server.listen(1) client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) client.connect(sock_path) conn, _ = server.accept() client.sendall(b"IPC FAST") print(f"Server received: {conn.recv(1024).decode()} ⚡") client.close() conn.close() server.close() os.unlink(sock_path) ``` Production web servers like Nginx and Gunicorn communicate exclusively over Unix Domain Sockets when co-located on the same physical or containerized host, slashing proxy latency in half 🚀! --- ### Question Why do Unix Domain Sockets (`AF_UNIX`) offer superior throughput and latency compared to TCP loopback? 🧠 - [ ] a. They bypass the entire network stack (TCP windowing, packet framing, checksums), moving bytes directly through kernel memory ⚡ - [ ] b. They execute within CPU L1 cache lines without triggering context switches - [ ] c. They automatically compress payloads using Huffman encoding - [ ] d. They run without requiring OS kernel file descriptor allocations --- ### Challenge Bind an `AF_UNIX` server socket to `'/tmp/chal_uds.sock'`. Connect a client, send `b'HELLO_UDS'`, receive on the server, print the decoded string, and clean up the socket file. 🎯 <details> <summary>Solution</summary> ```python import os import socket path = '/tmp/chal_uds.sock' if os.path.exists(path): os.unlink(path) server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) server.bind(path) server.listen(1) client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) client.connect(path) conn, _ = server.accept() client.sendall(b'HELLO_UDS') msg = conn.recv(64).decode() print(msg) client.close() conn.close() server.close() os.unlink(path) ``` </details>