Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python socket idle timeout: bound one blocking receive

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

A socket timeout limits how long one receive waits for data; it does not define a whole-request deadline.

Download Python source kit

Operation contract

A local socket pair has no incoming byte at first, so recv raises a timeout. The peer then sends one byte, and the next receive succeeds. This shows the per-operation idle boundary without contacting a remote host. A framed protocol still needs length limits and enough reads to assemble a message.

Failure and ownership boundary

Repeated successful one-byte receives can extend total elapsed time indefinitely. Track an overall deadline separately, validate frame length before allocation, and close both sockets on every path. Socket pair availability and exact timing vary by platform; the fixture checks only local stream behavior.

Working program

python
import socket

reader, writer = socket.socketpair()
with reader, writer:
    reader.settimeout(0.02)
    try:
        reader.recv(1)
    except socket.timeout:
        print("idle_timeout", True)
    writer.sendall(b"R")
    print("received", reader.recv(1).decode("ascii"))

Output

Output
idle_timeout True
received R

Costs and limits

The fixture waits about 20 milliseconds for the empty receive. Repeated timeouts or tiny reads can still waste CPU and connections without a total deadline.

Common Mistakes

  • An idle timeout is not an overall request deadline.
  • One recv is not one application message.
  • Always close both socket owners after a failed read.

Connected lessons

Test this boundary.

python
socket-idle-timeout
Storage details