Back
+20 XP
Concept

Connection Pooling & Socket Recycling

Opening new TCP connections incurs a 3-way handshake and TLS negotiation overhead. Connection pools maintain pre-warmed idle sockets, recycling them across requests to eliminate connection setup latency 🏊.

python
import queue
import socket

class SocketPool:
    def __init__(self, capacity=5):
        self._pool = queue.Queue(maxsize=capacity)

    def acquire(self):
        try:
            return self._pool.get_nowait()
        except queue.Empty:
            return None

    def release(self, sock):
        try:
            self._pool.put_nowait(sock)
        except queue.Full:
            sock.close()

pool = SocketPool(capacity=2)
s1, s2 = socket.socketpair()
pool.release(s1)
recycled = pool.acquire()
print(f"Recycled same socket: {recycled is s1} 🏊")
s1.close()
s2.close()

# 8. Connection Pooling & Socket Recycling Opening new TCP connections incurs a 3-way handshake and TLS negotiation overhead. Connection pools maintain pre-warmed idle sockets, recycling them across requests to eliminate connection setup latency 🏊. ```python import queue import socket class SocketPool: def __init__(self, capacity=5): self._pool = queue.Queue(maxsize=capacity) def acquire(self): try: return self._pool.get_nowait() except queue.Empty: return None def release(self, sock): try: self._pool.put_nowait(sock) except queue.Full: sock.close() pool = SocketPool(capacity=2) s1, s2 = socket.socketpair() pool.release(s1) recycled = pool.acquire() print(f"Recycled same socket: {recycled is s1} 🏊") s1.close() s2.close() ``` Robust connection pools validate socket liveness before returning them to callersβ€”either by performing a zero-byte peek (`recv(1, MSG_PEEK | MSG_DONTWAIT)`) or tracking idle lease timeouts to evict stale dead sockets πŸ›‘οΈ! --- ### Question What hazard occurs when retrieving an idle socket from a pool after extended inactivity? 🧠 - [ ] a. Intermediate firewalls or upstream servers may have closed the idle socket via TCP FIN/RST packets 🏊 - [ ] b. The socket automatically changes its assigned local port number - [ ] c. Python garbage collection deletes the remote server's memory - [ ] d. Operating system file descriptors expire after exactly 60 seconds --- ### Challenge Build `SocketPool` with `acquire()` and `release(conn)`. Release `s1`, acquire it back, assert `conn is s1`, and print `True`. Clean up sockets. 🎯 <details> <summary>Solution</summary> ```python import queue import socket class SocketPool: def __init__(self, capacity=2): self._pool = queue.Queue(maxsize=capacity) def acquire(self): try: return self._pool.get_nowait() except queue.Empty: return None def release(self, sock): try: self._pool.put_nowait(sock) except queue.Full: sock.close() pool = SocketPool() s1, s2 = socket.socketpair() pool.release(s1) conn = pool.acquire() print(conn is s1) s1.close() s2.close() ``` </details>

Checkpoint

What hazard occurs when retrieving an idle socket from a pool after extended inactivity? 🧠

Practice

Build `SocketPool` with `acquire()` and `release(conn)`. Release `s1`, acquire it back, assert `conn is s1`, and print `True`. Clean up sockets. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks