{"slug": "debug-network-error-in-python-requests", "title": "Debug Network Error in Python Requests", "summary": "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.", "body_md": "# Connection Refused, Timeouts and Unreachable Hosts: What Every Software Engineer Should Know\n\nBy [Abdesslem Amri](https://www.workflows.guru/contact#about) - Published \n\nI 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).\n\nPython 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.\n\nThis 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.\n\n## The Request Lifecycle\n\nBefore 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**.\n\nEvery 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.\n\nIf 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.\n\n## Setup the Environment\n\nIn my examples I have used Python 3.15, **requests** 2.34.2 and **urllib3** 2.8.0. To set up your environment, run:\n\n```\n1uv venv --python 3.152source .venv/bin/activate3uv pip install requests==2.34.2 urllib3==2.8.0\n```\n\nThe outputs were captured on macOS. Linux uses different errno numbers for the same errors (for example **111** instead of **61** for connection refused).\n\n## Exceptions in Python Requests\n\nBefore 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:\n\n``` python\n1>>> 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']\n```\n\nThese exceptions are inherited from each other, so you can catch them at different levels of specificity. For example:\n\n```\n1RequestException2├── ConnectionError3│   └── ConnectTimeout4└── Timeout5    ├── ConnectTimeout6    └── ReadTimeout\n```\n\nBecause **ConnectTimeout** inherits from both **ConnectionError** and **Timeout**, an **except ConnectionError** block also catches connect timeouts.\n\n## Connection refused\n\nI 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.\n\nThis 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.\n\n### What happens on the wire\n\nYour 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.\n\n### Reproduce it\n\nMake sure that nothing is listening on port 9999 on your machine, and try this code:\n\n```\n1import requests2\n3try:4    requests.get(\"http://127.0.0.1:9999/health\", timeout=3)5except requests.exceptions.ConnectionError as exc:6    print(exc)\n```\n\nYou should get this output:\n\n```\n1HTTPConnectionPool(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\"))\n```\n\nThe part that matters is **[Errno 61] Connection refused** (**[Errno 111]** on Linux).\n\n### In which scenarios this may happen\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\n### How to debug it\n\nTest the port from the client side, using nc you can run this command:\n\n``` bash\n1$ 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\n```\n\n## Connection timeout\n\nUnlike the connection refused error, in the connection timeout the **SYN** got no answer at all, so the client waited until its connect timeout expired.\n\n### What happens on the wire\n\nYour 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.\n\n### Reproduce it\n\n**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:\n\n```\n1import time2import requests3\n4start = 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)\n```\n\nYou should get this output:\n\n```\n1ConnectTimeout 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)'))\n```\n\nThe 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.\n\n### In which scenarios this may happen\n\n**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**.\n\n**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.\n\n**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.\n\n**A network partition.** A broken link or a bad route somewhere in the middle swallows the packets.\n\nSo if you see timeouts, start with firewalls and security groups. If you see refused, start with the service itself.\n\n### How to handle it\n\nThe 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.\n\n## Read timeout\n\n**In one sentence:** the connection succeeded and the request was sent, but the server didn't send any bytes back within the read timeout.\n\n### What happens on the wire\n\nThe 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**.\n\nThe server has no idea the client left. It keeps working, finishes the job, and writes a response into a closed connection.\n\n### Reproduce it\n\nStart 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:\n\n```\n1# slow_server.py: accepts the connection, then takes 10 s to answer2import time3from http.server import BaseHTTPRequestHandler, HTTPServer4\n5\n6class 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\n13\n14HTTPServer((\"127.0.0.1\", 8001), SlowHandler).serve_forever()\n```\n\nIn a second terminal, call it with a 2 second read timeout:\n\n```\n1import time2import requests3\n4start = 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)\n```\n\nYou will see an output similar to this:\n\n```\n1ReadTimeout after 2.0s2HTTPConnectionPool(host='127.0.0.1', port=8001): Read timed out. (read timeout=2)\n```\n\nAnd in the server logs, eight seconds after the client gave up:\n\n```\n1127.0.0.1 - - [20/Nov/2026 14:07:17] \"GET /report HTTP/1.1\" 200 -\n```\n\nThe 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.\n\n### Why it happens in real systems\n\n**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.\n\n**The server is overloaded.** All its worker threads are busy, so your request waits in a queue before anyone even looks at it.\n\n**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.\n\n**Your timeout is too tight.** Some endpoints are legitimately slow. A 2-second timeout on a 5-second export endpoint fails every time.\n\n### The read timeout is not a total timeout\n\nThis surprises almost everyone: **the read timeout limits the silence between two bytes, not the duration of the whole response.**\n\nI 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.\n\n### How to handle it\n\n**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.\n\n**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.\n\n**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.\n\n## Unreachable: Network is unreachable and No route to host\n\nThis 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.\n\n### What happens on the wire\n\n**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.\n\n**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.\n\n### Reproduce it\n\nThe reproduce the case B find an unused address on your local network, such as **192.168.1.250**:\n\n```\n1import requests2\n3try:4    requests.get(\"http://192.168.1.250/\", timeout=5)5except requests.exceptions.ConnectionError as exc:6    print(exc)\n```\n\nYou will get a output similar to this:\n\n```\n1HTTPConnectionPool(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\"))\n```\n\nTo 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.\n\n```\n1HTTPConnectionPool(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\"))\n```\n\n### Why it happens in real systems\n\n**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.\n\n**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.\n\n**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.\n\n**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.\n\nIf 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.\n\n### How to handle it\n\nRetrying 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.\n\n## Key takeaways\n\n1. **Always set a timeout.****requests** waits forever by default, and one silent dependency can freeze your whole service.\n2. **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.\n3. **The read timeout limits silence, not duration.** Add your own deadline when total time matters.\n4. **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.\n5. **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.", "url": "https://wpnews.pro/news/debug-network-error-in-python-requests", "canonical_source": "https://www.workflows.guru/blogs/debugging-network-errors", "published_at": "2026-12-02 23:02:38+00:00", "updated_at": "2026-12-02 23:18:12.134335+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Abdesslem Amri", "Python", "requests", "urllib3", "Illumio"], "also_reported_by": [], "takeaway": "Classify a requests failure by lifecycle stage — DNS, routing or TCP handshake errors like connection refused and connect timeout are always safe to retry even for POST, while read timeouts after the request was sent are only safe for idempotent operations.", "recommendation": {"advice": "Log which request stage failed and retry only pre-send failures (DNS, routing, handshake) for non-idempotent calls; treat read timeouts as possibly-completed work.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/debug-network-error-in-python-requests", "markdown": "https://wpnews.pro/news/debug-network-error-in-python-requests.md", "text": "https://wpnews.pro/news/debug-network-error-in-python-requests.txt", "jsonld": "https://wpnews.pro/news/debug-network-error-in-python-requests.jsonld"}}