Debug Network Error in Python Requests A debugging guide by Abdesslem Amri explains that Python requests network failures — connection refused, connect timeout, read timeout and unreachable hosts — each occur at a distinct stage of the request lifecycle (DNS resolution, routing, or the TCP three-way handshake), and that misdiagnosing them leads to wasted production troubleshooting. The guide, built on Python 3.15, requests 2.34.2 and urllib3 2.8.0, shows that failures before the request is sent are always safe to retry, even for POST, while failures after sending can only be retried for idempotent operations. Amri cites a production case where a service's 'Connection refused' error was wrongly attributed to micro-segmentation and an Illumio flow-opening request, when the host was reachable but no process was listening on the port. Connection Refused, Timeouts and Unreachable Hosts: What Every Software Engineer Should Know By Abdesslem Amri https://www.workflows.guru/contact about - Published I wanted to write this blog because I see the same network errors over and over in production and they are always misdiagnosed. I will use Python requests to reproduce these issues. Only images are AI generated, the content is based on real debugging experience . Python requests have different exceptions: such as Connection refused , connection timeout , read timeout and unreachable each happen at a different stage of a request, and each one means something different. Once you know and understand them, you will know where to look when something goes wrong in production. This blog walks through each error with example code to reproduce, the usual causes, how to debug it, and how to handle it in your code. The Request Lifecycle Before digging into the errors let's start by understanding the request lifecycle. Before a single byte of your HTTP request reaches the server's code, your machine has to do three things. It resolves the hostname to an IP address DNS . It finds a path to that IP routing . Then it opens a TCP connection with the three-way handshake: your machine sends a SYN , the server replies SYN-ACK , and your machine answers ACK . Every network error in this blog fails at one of those stages, and the stage helps you understand what went wrong and how to handle it. If it failed during DNS, routing or the handshake, the server's code never saw it. Retrying is always safe, even for a POST . If it failed after the request was sent, the server may have done the work, so you can only retry operations that are safe to repeat. Setup the Environment In my examples I have used Python 3.15, requests 2.34.2 and urllib3 2.8.0. To set up your environment, run: 1uv venv --python 3.152source .venv/bin/activate3uv pip install requests==2.34.2 urllib3==2.8.0 The outputs were captured on macOS. Linux uses different errno numbers for the same errors for example 111 instead of 61 for connection refused . Exceptions in Python Requests Before moving to the errors, let's examine the exceptions used in requests. The requests library wraps lower-level exceptions from urllib3 and the standard library's OSError . This wrapping creates a hierarchy of exceptions that can be caught and handled in your code. Here is the list of exceptions in requests: python 1 from requests import exceptions2 dir exceptions 3 'Any', 'BaseHTTPError', 'ChunkedEncodingError', 'CompatJSONDecodeError', 'ConnectTimeout', 'ConnectionError',4'ContentDecodingError', 'FileModeWarning', 'HTTPError', 'InvalidHeader', 'InvalidJSONError', 'InvalidProxyURL',5'InvalidSchema', 'InvalidURL', 'JSONDecodeError', 'MissingSchema', 'ProxyError', 'ReadTimeout', 'RequestException',6'RequestsDependencyWarning', 'RequestsWarning', 'RetryError', 'SSLError','StreamConsumedError', 'TYPE CHECKING',7'Timeout', 'TooManyRedirects', 'URLRequired', 'UnrewindableBodyError' These exceptions are inherited from each other, so you can catch them at different levels of specificity. For example: 1RequestException2├── ConnectionError3│ └── ConnectTimeout4└── Timeout5 ├── ConnectTimeout6 └── ReadTimeout Because ConnectTimeout inherits from both ConnectionError and Timeout , an except ConnectionError block also catches connect timeouts. Connection refused I wrote this blog because of this specific error. One of our services was failing with Connection refused and my collegues was thinking about a micro segmentation issue and that we should request a new flow opening using Illumio. This error occurs when the host is up and reachable, but no process is listening on that port, so the host's kernel rejects the connection immediately. What happens on the wire Your client sends a SYN to port 9999. The packet arrives, the server's kernel sees that no socket is listening on that port, and it sends back a TCP RST reset . Notice that the server's application code is not involved at all. Reproduce it Make sure that nothing is listening on port 9999 on your machine, and try this code: 1import requests2 3try:4 requests.get "http://127.0.0.1:9999/health", timeout=3 5except requests.exceptions.ConnectionError as exc:6 print exc You should get this output: 1HTTPConnectionPool host='127.0.0.1', port=9999 : Max retries exceeded with url: /health Caused by NewConnectionError "HTTPConnection host='127.0.0.1', port=9999 : Failed to establish a new connection: Errno 61 Connection refused" The part that matters is Errno 61 Connection refused Errno 111 on Linux . In which scenarios this may happen The service isn't running. It crashed, it's restarting during a deploy, or it never started because of a bad config. This is the most common cause by far. You're calling the wrong port. A typo in an environment variable, or a service that moved from 8080 to 8000 and a client that didn't follow. The server only listens on localhost. A process bound to 127.0.0.1 accepts connections from its own machine only. Calls to the machine's real IP are refused. Many dev servers default to this, so it's a classic works on my machine bug. Bind to 0.0.0.0 when other hosts or containers need to reach it. localhost means something else inside a container. In Docker, 127.0.0.1 is the container itself, not your laptop or the other container. Use the Compose service name, or host.docker.internal to reach the host. A Kubernetes Service has no ready pods. When every pod behind a Service fails its readiness probe, kube-proxy in its default iptables mode rejects new connections, and clients see connection refused. How to debug it Test the port from the client side, using nc you can run this command: bash 1$ nc -vvv 127.0.0.1 99992 3 network-errors abdesslem@abdesslems-mbp network-errors % nc -vvv 127.0.0.1 99994nc: connectx to 127.0.0.1 port 9999 tcp failed: Connection refused5 Connection timeout Unlike the connection refused error, in the connection timeout the SYN got no answer at all, so the client waited until its connect timeout expired. What happens on the wire Your client sends a SYN . Nothing comes back: no SYN-ACK , no RST , no error. The kernel retransmits the SYN a few times with growing delays, and eventually your client side timer fires. The client can't tell whether the packet was lost, dropped on purpose, or reached a server that is too busy to answer. Reproduce it 10.255.255.5 is a private address that goes nowhere. Packets to it vanish, which is exactly what a firewall with a DROP rule does: 1import time2import requests3 4start = time.monotonic 5try:6 requests.get "http://10.255.255.5/", timeout= 3, 10 7except requests.exceptions.ConnectTimeout as exc:8 print f"{type exc . name } after {time.monotonic - start:.1f}s" 9 print exc You should get this output: 1ConnectTimeout after 3.0s2HTTPConnectionPool host='10.255.255.5', port=80 : Max retries exceeded with url: / Caused by ConnectTimeoutError