By Abdesslem Amri - 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:
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:
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(<HTTPConnection(host='10.255.255.5', port=80) at 0x108afbcb0>, 'Connection to 10.255.255.5 timed out. (connect timeout=3)'))
The tuple timeout=(3, 10) means a 3-second connect timeout and a 10-second read timeout. The call failed after exactly 3 seconds: the connect timeout.
In which scenarios this may happen
A firewall or security group drops the traffic. This is the number one cause in cloud environments. A missing inbound rule in an AWS security group, a network ACL, or a corporate firewall silently discards your SYN.
The IP address is wrong or stale. A cached DNS answer points to a machine that was replaced, or the config has an old IP. Many cloud networks don't answer for addresses with no host behind them. They drop the packets.
The server is overloaded. When a Linux server's queue of pending connections is full, it drops new SYN packets instead of refusing them. From the client's side, a server that's drowning looks exactly like a server behind a firewall.
A network partition. A broken link or a bad route somewhere in the middle swallows the packets.
So if you see timeouts, start with firewalls and security groups. If you see refused, start with the service itself.
How to handle it
The request never reached the server, so retrying is safe for every method. Use exponential backoff with jitter, because an overloaded server dropping SYN s needs breathing room, not a retry storm. Keep the connect timeout short: a healthy server in the same region completes the handshake in milliseconds, so 3 seconds is generous. Persistent connect timeouts usually mean a configuration problem that no amount of retrying will fix.
Read timeout #
In one sentence: the connection succeeded and the request was sent, but the server didn't send any bytes back within the read timeout.
What happens on the wire
The handshake completes. Your client sends GET /report. The server receives it and starts working. Your client waits for the first byte of the response. When the read timeout expires, the client closes the connection and raises ReadTimeout.
The server has no idea the client left. It keeps working, finishes the job, and writes a response into a closed connection.
Reproduce it
Start a local server that accepts connections but takes times to answer, the following code will create a simple server that take 10 seconds to respond:
1# slow_server.py: accepts the connection, then takes 10 s to answer2import time3from http.server import BaseHTTPRequestHandler, HTTPServer4
5
6class SlowHandler(BaseHTTPRequestHandler):7 def do_GET(self):8 time.sleep(10)9 self.send_response(200)10 self.end_headers()11 self.wfile.write(b"report ready")12
13
14HTTPServer(("127.0.0.1", 8001), SlowHandler).serve_forever()
In a second terminal, call it with a 2 second read timeout:
1import time2import requests3
4start = time.monotonic()5try:6 requests.get("http://127.0.0.1:8001/report", timeout=(3, 2))7except requests.exceptions.ReadTimeout as exc:8 print(f"{type(exc).__name__} after {time.monotonic() - start:.1f}s")9 print(exc)
You will see an output similar to this:
1ReadTimeout after 2.0s2HTTPConnectionPool(host='127.0.0.1', port=8001): Read timed out. (read timeout=2)
And in the server logs, eight seconds after the client gave up:
1127.0.0.1 - - [20/Nov/2026 14:07:17] "GET /report HTTP/1.1" 200 -
The client see a failure and the server see a success. That's what makes read timeouts dangerous and sometimes very hard to debug if you can not interpret well the your errors.
Why it happens in real systems
The endpoint is slow. A missing database index, a report that scans a big table, or a call that grew slower as the data grew.
The server is overloaded. All its worker threads are busy, so your request waits in a queue before anyone even looks at it.
A dependency is slow. The server is itself waiting on another service, which is waiting on a third. A read timeout is often the first visible symptom of a cascading failure further down the chain.
Your timeout is too tight. Some endpoints are legitimately slow. A 2-second timeout on a 5-second export endpoint fails every time.
The read timeout is not a total timeout
This surprises almost everyone: the read timeout limits the silence between two bytes, not the duration of the whole response.
I tested this with a server that sends a 8 byte body one byte per second. With timeout=(3, 2), the call returned 200 OK after 8.0 seconds without any error. If you need a hard limit on the total time you have to enforce it yourself. You can stream the response and check the time as bytes arrive.
How to handle it
Retry only idempotent requests. A GET, PUT or DELETE can be repeated safely. A POST that creates an order or charges a card cannot, because the first attempt may have succeeded. For non-idempotent operations, send an idempotency key (a unique ID per logical operation that the server uses to drop duplicates), then retry safely.
Set read timeouts per endpoint. A health check deserves 1 second. A report export may deserve 60. One global value is either too short for slow endpoints or too long for fast ones.
Move long work out of the request. If an endpoint routinely takes longer than a reasonable timeout, make it asynchronous: return 202 Accepted with a job ID and let the client poll.
Unreachable: Network is unreachable and No route to host #
This error means that there is no path to the destination, either because your own machine has no route to it, or because a router on the way says the host can't be reached.
What happens on the wire
Case A: Network is unreachable ( ENETUNREACH**).** Before sending anything, your kernel looks up the destination IP in its routing table. If no route matches and there's no default gateway, the connect() call fails right away. No packet ever leaves the machine.
Case B: No route to host ( EHOSTUNREACH**).** A packet does leave, but the network reports back that the host can't be reached. A router sends an ICMP destination unreachable message, or, on your local network, nobody answers the ARP request for that IP address because no machine owns it.
Reproduce it
The reproduce the case B find an unused address on your local network, such as 192.168.1.250:
1import requests2
3try:4 requests.get("http://192.168.1.250/", timeout=5)5except requests.exceptions.ConnectionError as exc:6 print(exc)
You will get a output similar to this:
1HTTPConnectionPool(host='192.168.1.250', port=80): Max retries exceeded with url: / (Caused by NewConnectionError("HTTPConnection(host='192.168.1.250', port=80): Failed to establish a new connection: [Errno 65] No route to host"))
To see case A, disconnect from every network and request any IP address directly. With no default route, the call fails instantly with [Errno 51] Network is unreachable on macOS, or [Errno 101] on Linux.
1HTTPConnectionPool(host='1.1.1.1', port=80): Max retries exceeded with url: / (Caused by NewConnectionError("HTTPConnection(host='1.1.1.1', port=80): Failed to establish a new connection: [Errno 51] Network is unreachable"))
Why it happens in real systems
The VPN is down. Internal ranges like 10.0.0.0/8 are often routed only through the VPN. When the tunnel drops, those routes disappear and every internal call becomes network is unreachable.
A container has no network. A container started with --network none, or attached to a Docker network that can't reach the target, only knows its own loopback interface.
A hostname resolves only to IPv6. If DNS returns only an IPv6 address and your host has no IPv6 route, the connection fails immediately. When both IPv4 and IPv6 addresses exist, urllib3 silently falls back to the next one, which hides the problem until the day the IPv4 record disappears.
The host is down on your local network. For a target on the same subnet, an unanswered ARP request turns into no route to host after a few seconds.
If there's no route, or the route points at an interface that's down, you've found the problem. For case B, traceroute 10.9.0.12 shows which hop sends the unreachable message back.
How to handle it
Retrying rarely helps. A missing route is a configuration problem. Fail fast, log the destination IP, and alert. The one exception is a laptop or a device that changes networks, where a short retry can outlast a reconnect.
Key takeaways #
- **Always set a timeout.**requests waits forever by default, and one silent dependency can freeze your whole service.
- Refused means nobody's there, timeout means nobody answered. Refused points at the service or its port. Connect timeouts point at firewalls, wrong IPs, or an overloaded server.
- The read timeout limits silence, not duration. Add your own deadline when total time matters.
- Before you retry, ask whether the request reached the app. Connection-stage failures are always safe to retry. Read timeouts are only safe for idempotent requests or with an idempotency key.
- Classify, don't just catch. Three of these errors share one exception class. Unwrap the cause, log a clear label, and your 3 a.m. self will thank you.