CURL ERROR: Recv failure: Connection reset by peer

CURL ERROR: Recv failure: Connection reset by peer

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

CURL ERROR: Recv failure: Connection reset by peer

When debugging a CURLE_RECV_ERROR (Connection reset by peer), it is tempting to assume your client logic is flawed. However, the specific behavior described—where the error vanishes after a retry but returns after the server has been idle for 30 minutes or rebooted—points squarely at a network-level state mismatch rather than a code bug in your PHP script.

The verbose output reveals the smoking gun:

> Expect: 100-continue
...
* Recv failure: Connection reset by peer

Your client is sending an Expect: 100-continue header, which is standard practice for POST requests with large bodies. The server receives this and prepares to handle the request. However, the connection drops before the HTTP response can be fully transmitted or received. This behavior is characteristic of a TCP Keepalive timeout on the server side.

The Idle Connection Trap

The phenomenon you described—failure after 30 minutes of inactivity followed by success immediately after waking up—is the classic signature of intermediate network devices (routers, load balancers, or firewalls) terminating idle connections to conserve resources.

Here is what happens under the hood:

  1. Your PHP script initiates a TCP handshake and connects to 196.41.139.168.
  2. The connection remains open while your server prepares the PDF data.
  3. Once the request body is sent, there is no further traffic on this specific socket for approximately 30 minutes (or until the remote server reboots).
  4. During this idle window, a firewall or load balancer between you and the target executes a connection timeout policy. It silently closes the TCP connection to free up the port.
  5. When your client attempts to read the response (curl_exec), it tries to receive data on a socket that no longer exists at the network layer. The kernel detects this abrupt closure and returns CURLE_RECV_ERROR.

The fact that it works immediately after a reboot confirms this hypothesis: the reboot clears the connection tables, allowing a fresh handshake. Subsequent failures occur once that new session hits the idle threshold again.

Mitigation Strategies

You can resolve this by ensuring the connection remains active or by adapting your client to handle interruptions gracefully.

1. Disable Expect Header

The verbose log shows you already attempted to remove the Expect: 100-continue header, but your syntax was incorrect. You cannot simply pass 'Expect:' in an array; you must provide a value or omit it entirely. Furthermore, if the server is configured to close connections immediately upon receiving this header without processing the body, disabling it might be necessary.

In PHP cURL, set the header explicitly to remove it or do not set it at all:

// Remove the Expect header by overriding it with an empty value or omitting it
curl_setopt($c, CURLOPT_HTTPHEADER, array('Expect:')); 
// OR simply ensure you don't set it unless necessary for large payloads

If the server responds poorly to Expect, removing it is a valid trade-off. It adds minimal overhead and prevents the specific handshake that triggers the immediate drop in some misconfigured environments.

2. Implement TCP Keepalive on the Client

The most robust solution is to instruct your client to send periodic "I am still alive" packets before the intermediate firewall decides to kill the connection. This requires setting CURLOPT_TCP_KEEPALIVE and CURLOPT_TCP_KEEPIDLE.

Note that these options depend on the underlying cURL library version and OS support, but they are widely available in modern environments:

// Send keepalive probes every 30 seconds after the first minute of idle time
curl_setopt($c, CURLOPT_TCP_KEEPALIVE, true);
curl_setopt($c, CURLOPT_TCP_KEEPIDLE, 30); 
curl_setopt($c, CURLOPT_TCP_KEEPINTVL, 10); // Interval between probes

This forces the TCP stack to send ICMP Echo Requests (or equivalent TCP segments) periodically. If the remote endpoint or an intermediate firewall responds, the connection stays open even if no application-level data is flowing for 30 minutes.

3. Handle the Error Gracefully

If you cannot modify the server configuration or network hardware, your PHP code must be resilient to transient connection resets. Wrap your request logic in a retry loop. If curl_error returns "Connection reset by peer," wait briefly and attempt the request again. This mimics the behavior you observed when running the script twice: the first run fails (connection was killed), the second succeeds (fresh connection).

$maxRetries = 3;
for ($i = 0; $i < $maxRetries; $i++) {
    try {
        $pdf = curl_exec($c);
        if (curl_errno($c) === CURLE_OK) {
            break; // Success
        }
        
        $error = curl_error($c);
        if ($error !== 'Connection reset by peer') {
            throw new Exception('Curl error: ' . $error);
        }
        
        // Only retry on connection reset
        echo "Retrying request..."; 
    } catch (Exception $e) {
        break;
    }
}

Conclusion

The Recv failure: Connection reset by peer error in this context is not a bug in your PHP logic, but a symptom of TCP Keepalive timeouts on the network path. By disabling the Expect header if the server requires it, implementing client-side keepalives to prevent intermediate devices from dropping the socket, and adding retry logic for transient resets, you can ensure consistent behavior regardless of how long the remote server remains idle.

Our network