Lesson 4 of 9 · 23m
Concurrent TCP Servers: Threads, Processes, and Event Loops
Choose a concurrency model based on blocking behavior and shared state — and learn why accept loops, timeouts, and worker lifecycles matter more than framework hype.
A one-client-at-a-time server is fine until a slow client occupies the only worker. Then the service is technically up but operationally dead. Python gives you several concurrency models; none is universally right. The correct question is where time is spent: CPU-bound work, blocking I/O, or many mostly idle connections.
Thread-per-connection is simple and bounded
import socketserver
class Handler(socketserver.StreamRequestHandler):
timeout = 10
def handle(self):
line = self.rfile.readline(8192)
if not line:
return
self.wfile.write(line.upper())
class Server(socketserver.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
with Server(("127.0.0.1", 8080), Handler) as srv:
srv.serve_forever()Threads make blocking APIs easy to reason about. They fail badly when unbounded: 20,000 clients means 20,000 threads, stack memory, scheduler pressure, and debugging pain. Put a hard limit on workers if traffic can spike.
Processes isolate faults but cost more
A process pool is attractive when handlers use CPU-heavy C extensions or mutable state you do not want shared. The tradeoff is serialization and memory. Do not solve a concurrency problem by copying state into N processes and hoping it stays consistent. Shared counters, cache consistency, and in-flight transactions become distributed-systems problems inside one host.
Event loops shine for many idle sockets
An event loop uses nonblocking sockets and readiness notifications: one thread services thousands of connections because most are waiting rather than computing. asyncio is Python's native model, but even if you do not use asyncio directly, the operational idea matters. Blocking one connection must not block the loop. If a handler calls a synchronous database driver or sleeps, the entire service stalls.
Backlog and accept behavior are operational controls
listen(backlog) controls connections waiting to be accepted. If accept is slower than arrival, the kernel queues briefly and then clients see timeouts or resets. Monitoring only CPU can mislead you; the real bottleneck may be accept latency caused by a blocked worker pool. Health checks should exercise the full path rather than merely opening a TCP connection.
Shared state needs an owner
In threaded servers, use queues to hand work to dedicated writer threads, or use locks around genuinely shared structures. Do not let every connection mutate global dictionaries ad hoc. In event-loop servers, state mutation is safer because only one task runs at a time, but awaits can interleave operations. The interleaving is the race.
Field notes
- Set per-connection read, write, and idle timeouts; slowloris attacks exploit patient servers.
- Log peer address, connection age, bytes read/written, and close reason. You will need it during incidents.
- Graceful shutdown means stop accepting, stop new work, drain in-flight requests, then close.
- Do not kill threads forcibly. Design cooperative cancellation or move work into processes.
- Load-test with slow and silent clients, not just fast local requests.
Was this lesson helpful?