Python selectors: Watch Many Sockets Without One Thread per Client

By Editorial Team Published 10 min read
Circular switchboard with one selector arm and three illuminated ports, illustrating Python selectors watching many sockets.

A client connects to your server and starts typing a request. Very slowly. Somewhere between “hello” and the newline, it appears to go for lunch.

With Python selectors, the other clients can keep getting answers. One thread watches many sockets, works on the ones that can make progress, and lets the operating system wait when there is nothing useful to do.

Let’s build a tiny TCP “shout booth”: send a line of text, receive its ASCII letters in uppercase. The transformation is deliberately boring. The interesting part is that one unfinished conversation will not hold the others hostage.

What Is Python’s selectors Module?

selectors is a standard-library interface for I/O readiness monitoring. Register sockets, specify whether you care about reading or writing, and ask which are ready. DefaultSelector chooses an efficient available implementation for the platform. [1]

Think of an apartment building with a light above every door. A dedicated thread per client is rather like assigning an attendant to each apartment. A selector lets one attendant wait for the panel to light up and visit the doors that need attention.

Both designs can be useful. Threads often make blocking code straightforward. A selector becomes attractive when many connections spend much of their lives waiting, and you want explicit control over their I/O and buffers.

This is concurrency: several conversations remain in progress. Our server still executes its Python handlers one at a time.

The client-server model describes the participants. A selector helps decide how the server divides its attention.

Ready Does Not Mean Complete

A readable socket may offer part of a request, several requests together, or an end-of-stream indication. TCP delivers a byte stream; application message boundaries need their own rule. Our rule will be a newline. [2]

These two fragments form one request:

First arrival:   i am still thi
Second arrival:  nking\n

The server must remember the first fragment without waiting inside that client’s handler for the second. Meanwhile, another client can submit a complete line and get its answer.

Writing has a similar catch: a writable socket can accept some bytes locally. It does not promise room for the entire reply, or confirm that the remote application has read it. Keep unsent bytes and try them later. [2, 3]

Python selectors: Four Operations That Matter

OperationJob in our server
register()Add the listening socket or a newly accepted connection.
select()Wait for readiness and return the sockets that need attention.
modify()Add write interest when a reply is queued; remove it when the queue empties.
unregister()Stop monitoring a socket before closing it.

The two event flags are EVENT_READ and EVENT_WRITE. The optional data attached to a registration carries our per-client state: unfinished input, pending output, and connection bookkeeping. [1]

One subtle distinction: select() is allowed to wait. Individual socket operations must not hold up the event loop. We explicitly make both the listener and accepted sockets nonblocking; accepted sockets do not inherit nonblocking behavior consistently across operating systems. A BlockingIOError means to come back later. [3]

Build the Server: A Shout Booth with a Waiting Room

Use Python 3.10 or newer, with no third-party packages. Save the following complete script as selectors_server.py. It listens only on your own computer, at 127.0.0.1.

"""A bounded, single-threaded TCP line server. Python 3.10+; stdlib only.

Run: python selectors_server.py --port 65432
Protocol: ASCII lowercase becomes uppercase; each request ends with LF.
"""

import argparse
from dataclasses import dataclass, field
import selectors
import socket
import time

MAX_CLIENTS = 100
MAX_LINE = 1024          # Bytes before the newline.
MAX_QUEUED = 64 * 1024   # Pending reply bytes per client.
IDLE_SECONDS = 30.0


@dataclass
class Client:
    incoming: bytearray = field(default_factory=bytearray)
    outgoing: bytearray = field(default_factory=bytearray)
    eof: bool = False
    last_active: float = field(default_factory=time.monotonic)


def close_client(sel, sock):
    sel.unregister(sock)
    sock.close()


def service(sel, key, mask):
    sock, state = key.fileobj, key.data
    try:
        if mask & selectors.EVENT_READ:
            try:
                chunk = sock.recv(4096)
            except BlockingIOError:
                chunk = None
            if chunk is not None:
                if chunk:
                    state.last_active = time.monotonic()
                    state.incoming.extend(chunk)
                    while (end := state.incoming.find(b"\n")) != -1:
                        if (end > MAX_LINE or
                                len(state.outgoing) + end + 1 > MAX_QUEUED):
                            close_client(sel, sock)
                            return
                        state.outgoing.extend(state.incoming[:end].upper())
                        state.outgoing.append(10)
                        del state.incoming[:end + 1]
                    if len(state.incoming) > MAX_LINE:
                        close_client(sel, sock)
                        return
                else:
                    state.eof = True
                    state.incoming.clear()  # Discard an unterminated line.

        if mask & selectors.EVENT_WRITE and state.outgoing:
            try:
                sent = sock.send(state.outgoing[:16384])
            except BlockingIOError:
                pass
            else:
                if sent == 0:
                    close_client(sel, sock)
                    return
                del state.outgoing[:sent]
                state.last_active = time.monotonic()

        if state.eof and not state.outgoing:
            close_client(sel, sock)
            return
        events = 0 if state.eof else selectors.EVENT_READ
        if state.outgoing:
            events |= selectors.EVENT_WRITE
        sel.modify(sock, events, state)
    except OSError:
        close_client(sel, sock)


def run(port=65432):
    with selectors.DefaultSelector() as sel, socket.socket() as listener:
        listener.bind(("127.0.0.1", port))
        listener.listen()
        listener.setblocking(False)
        sel.register(listener, selectors.EVENT_READ, data=None)
        print(f"{type(sel).__name__} on 127.0.0.1:{listener.getsockname()[1]}",
              flush=True)
        try:
            while True:
                for key, mask in sel.select(timeout=1.0):
                    if key.data is None:
                        try:
                            conn, _ = listener.accept()
                        except BlockingIOError:
                            continue
                        if len(sel.get_map()) - 1 >= MAX_CLIENTS:
                            conn.close()
                            continue
                        conn.setblocking(False)
                        sel.register(conn, selectors.EVENT_READ, Client())
                    else:
                        service(sel, key, mask)

                now = time.monotonic()
                for key in list(sel.get_map().values()):
                    if (key.data is not None and
                            now - key.data.last_active >= IDLE_SECONDS):
                        close_client(sel, key.fileobj)
        except KeyboardInterrupt:
            print("Stopping.")
        finally:
            for key in list(sel.get_map().values()):
                close_client(sel, key.fileobj)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=65432)
    run(parser.parse_args().port)

Run it in a terminal:

python selectors_server.py

On systems where the interpreter command is python3, use that instead. The first line identifies the selected backend and listening port. An EpollSelector on one machine and a KqueueSelector on another represent different plumbing behind the same interface.

Try Three Clients, Including One That Cannot Finish a Sentence

Keep the server running. Save this second complete script as selectors_clients.py and run it in another terminal.

"""Three TCP clients; one pauses halfway through a request. Python 3.10+."""

import argparse
from contextlib import ExitStack
import socket


def read_line(sock):
    reply = bytearray()
    while not reply.endswith(b"\n"):
        chunk = sock.recv(1)
        if not chunk:
            raise ConnectionError("Server closed before the reply was complete")
        reply.extend(chunk)
    return reply.decode("ascii").rstrip("\n")


def main(port=65432):
    with ExitStack() as stack:
        clients = [stack.enter_context(socket.create_connection(
            ("127.0.0.1", port), timeout=5)) for _ in range(3)]
        slow, fast, other = clients
        slow.sendall(b"i am still thi")  # Deliberately omit the newline.
        fast.sendall(b"hello from client b\n")
        other.sendall(b"client c is ready\n")
        print("B:", read_line(fast))
        print("C:", read_line(other))
        slow.sendall(b"nking\n")
        print("A:", read_line(slow))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=65432)
    main(parser.parse_args().port)
python selectors_clients.py

You should see:

B: HELLO FROM CLIENT B
C: CLIENT C IS READY
A: I AM STILL THINKING

Client A sends an unfinished line. B and C then submit complete requests, and the client script reads their answers before allowing A to finish. All three connections are open together. Neither script creates a thread per client.

The client uses blocking sockets and sendall() to keep the demonstration readable. That is fine here: each message is tiny, and this script is not the server’s event loop. Its one-byte receive loop makes the newline boundary explicit rather than pretending one recv() equals one reply.

If port 65432 is busy, use python selectors_server.py --port 65433 and python selectors_clients.py --port 65433. Stop the server with Ctrl+C.

The Three Details That Make This More Than an Echo Toy

Each connection owns its unfinished business. The Client object remains attached to that socket between events. default_factory=bytearray gives each connection separate buffers. Incoming bytes accumulate until a newline appears; multiple complete lines in one read produce multiple replies.

A send is a progress report. If send() accepts 37 bytes, the code removes precisely those 37 bytes from outgoing. The remainder survives for the next writable event. BlockingIOError leaves the pending data intact. Using sendall() inside this nonblocking loop would obscure how much of a reply remains if an error occurs. [3]

Write interest is temporary. A connected socket often has spare send-buffer capacity. Registering it permanently for writing can make the selector return immediately, again and again, even when the application has nothing to send. The server watches for writes only while outgoing contains bytes.

That final detail can be the difference between a quiet waiting room and a receptionist repeatedly shouting “I could post a letter!” into an empty office.

What Happens When a Client Is Slow?

A slow reader can leave replies waiting in application memory after the socket’s send capacity becomes constrained. Our example uses explicit limits:

ResourceDemonstration policy
Accepted clientsAt most 100; additional connections are closed.
One request lineAt most 1,024 bytes before the newline.
Pending repliesAt most 64 KiB per client; exceeding the cap closes that connection.
InactivityClose after about 30 seconds without a successful read or write, checked once per loop.
Work per readiness eventAt most one 4,096-byte receive and one send attempt of up to 16,384 bytes.

These are teaching choices, not recommended production sizing. The byte limits refer to application buffers; operating-system buffers and object overhead also consume memory. The inactivity timer is not a complete-request deadline: a client that trickles bytes can remain active.

Closing an over-limit connection is load shedding. A more elaborate server can pause read interest when its output queue reaches a high watermark, then resume below a lower watermark. If it stops draining incoming TCP data, transport flow control can eventually carry pressure back toward the sender. Our explanation of backpressure in networking follows that feedback path.

The code also handles a client that finishes sending but still wants replies: it stops reading after EOF, drains queued responses, then closes. An unfinished final line is discarded because our protocol requires a newline. A reset or other socket error closes the affected connection.

The uppercase conversion acts on ASCII lowercase bytes. It is not Unicode-aware text casing. Keeping framing byte-based also avoids decoding a multibyte character halfway through its arrival.

Python selectors vs. asyncio: Which Should You Use?

selectors gives you the readiness mechanism and leaves the state machine to you. It is excellent for learning what happens between “a connection exists” and “a complete response arrived.” It also suits specialized low-level networking tools.

For many application servers, asyncio streams provide a more convenient level of abstraction, with coroutine scheduling and higher-level reading and writing. A selector-based asyncio loop uses the selectors module underneath, but asyncio is not universally a wrapper around it: Windows normally uses a proactor event loop. [4, 5]

Our Python asyncio guide moves from readiness bookkeeping to async and await. You still need message framing, resource limits, and a policy for slow consumers.

Neither approach makes a long calculation disappear. Put a blocking database call, a large synchronous file operation, or expensive computation in our handler and every client waits behind it. The event loop only stays responsive while each turn stays short.

Three Questions Before You Build Something Bigger

Will this handle a million clients? This demonstration deliberately caps connections at 100. Real capacity depends on the backend, operating-system limits, memory, application work, and workload. Removing threads does not remove those limits. On Windows, selectors supports sockets rather than the broader set of Unix file objects, and its select-based backend has additional scaling limits. [1, 5]

Is this an Internet-ready service? It is a local learning example. A deployed service needs decisions about authentication, TLS, monitoring, deadlines, overload behavior, and application protocol design. A selector supplies none of those by itself.

What should I change first? Add a small command such as PING, then deliberately fragment it across two sends. Next, try two newline-terminated commands in one send. Your output should follow the protocol boundaries rather than the shape of the network reads.

The useful trick is learning to leave an unfinished conversation unfinished. Store its state, attend to someone who is ready, and return when the next bytes arrive.

References and Further Reading

Network Encyclopedia Editorial Team

Every entry is written, reviewed and kept up to date by our editors. Spotted a mistake? We fix it in the open.

Editorial Mission · Correction Policy · Suggest a correction