Timeouts

Requests · Practical · 8 min

Without a timeout, one stuck server can hang your program forever.

By default Requests has no timeout: if the server accepts the connection and then never answers, requests.get waits indefinitely. Production code should pass timeout= on every call. Linters such as Bandit and Ruff flag calls without it.

timeout can be a single number or a (connect, read) tuple, in seconds:

  • The connect timeout limits establishing the TCP (and TLS) connection. A value slightly above a multiple of 3 seconds, such as 3.05, is a common recommendation because TCP retransmits after 3 seconds.
  • The read timeout limits how long to wait between bytes from the server once connected. It is not a limit on the total download time: a server trickling one byte every few seconds can keep a request alive far longer than the read timeout.

When they fire, you get requests.ConnectTimeout or requests.ReadTimeout, both subclasses of requests.Timeout. A connect timeout is safe to retry, since the request never reached the server. A read timeout is ambiguous for non-idempotent methods like POST: the server may already have processed the request.

If you need a hard deadline for the whole operation, enforce it around the request: stream the body and check elapsed time, or run the call in a worker with a deadline. HTTPX offers a more granular timeout configuration if this matters a lot.

Note that timeout=None explicitly means wait forever.

Example

import time
import requests

try:
    requests.get("https://httpbin.org/delay/3", timeout=1)
except requests.ReadTimeout as e:
    print("read timeout")          # read timeout

t = time.perf_counter()
r = requests.get("https://httpbin.org/delay/1", timeout=(3.05, 5))
print(r.status_code, round(time.perf_counter() - t))  # 200 1

for exc in (requests.ConnectTimeout, requests.ReadTimeout):
    print(exc.__name__, issubclass(exc, requests.Timeout))
# ConnectTimeout True
# ReadTimeout True

Remember

  • Requests waits forever unless you pass timeout=
  • timeout=(connect, read); read limits the gap between bytes, not total time
  • Connect timeouts are safe to retry; read timeouts may mean the server acted

Watch out for

  • Believing timeout=10 caps a large download at 10 seconds.

Check yourself

  1. A server sends one byte every 4 seconds for a minute. With timeout=5, what happens?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: requests.readthedocs.io/en/latest/user/advanced/#timeouts