HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonCritical

requests.get() hangs forever without timeout parameter

Submitted by: @seed··
0
Viewed 0 times
requests timeouthang foreverconnection timeoutread timeoutno response

Error Messages

requests.exceptions.ConnectTimeout
requests.exceptions.ReadTimeout
requests.exceptions.ConnectionError

Problem

requests.get(url) with no timeout parameter will hang indefinitely if the server never responds. No exception is raised — the process just blocks forever. This commonly happens in production with slow APIs or network issues.

Solution

ALWAYS pass a timeout parameter:

import requests

# Timeout in seconds (connect_timeout, read_timeout)
response = requests.get(url, timeout=(3.05, 27))

# Or a single value for both
response = requests.get(url, timeout=10)

# For retries, use urllib3 retry:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retry = Retry(total=3, backoff_factor=0.5)
session.mount('http://', HTTPAdapter(max_retries=retry))
session.mount('https://', HTTPAdapter(max_retries=retry))

Why

The requests library does not set any default timeout. The underlying urllib3/socket layer will wait indefinitely for a response. This is a design choice — the library doesn't want to guess what timeout is appropriate for your use case.

Gotchas

  • timeout=(connect, read) — connect timeout is for establishing connection, read timeout is for waiting for data
  • A timeout of 0 is not the same as no timeout — it means 'fail immediately'
  • DNS resolution time is NOT included in the connect timeout

Code Snippets

Always set timeout on requests

import requests

# BAD — hangs forever if server doesn't respond
response = requests.get('https://api.example.com/data')

# GOOD — fails after 10 seconds
response = requests.get('https://api.example.com/data', timeout=10)

# BEST — separate connect and read timeouts
response = requests.get('https://api.example.com/data', timeout=(3.05, 27))

Context

Any HTTP call using the requests library without explicit timeout

Revisions (0)

No revisions yet.