Practical technical guides / Core IT: networking (TCP close with unread data)

Closing a Socket With Unread Data Sends a Reset, and the Client Can Lose the Response

Measured on Windows 11 loopback: a server that sent 413 and closed with 4 MB unread reset the connection, and the client never read the response. A lingering close fixed it.

By Sandeep Belgavi · Published 2026-11-14

Measured on Windows 11 loopback: a server that sent 413 and closed with 4 MB unread reset the connection, and the client never read the response. A lingering close fixed it.

A 413 that the client never saw

Tanishka's upload service at Belgavi's Book Store rejects oversized book-cover images. To save bandwidth it reads the request headers, sees a Content-Length above the limit, sends 413 Content Too Large, and closes the socket. The response is correct and it was written to the socket. Yet the client logs show ConnectionResetError instead of a 413, and the support team gets reports of "connection reset by peer" from customers whose files were simply too big.

The cause is in TCP, not HTTP. When an application closes a socket while received data is still sitting unread in the kernel's receive buffer, the stack does not send a normal FIN. It sends a reset. RFC 9293, the current TCP specification, keeps the rule from RFC 1122: if a host issues a CLOSE call while received data is still pending in the TCP connection, or if new data is received after CLOSE is called, its TCP implementation SHOULD send a RST to show that data was lost. And a reset does not only end the connection: on the receiving side it can throw away data that had arrived but that the application had not yet read, which here is the 413.

Measured on loopback

The companion probe runs a loopback server and client in one Python process. The client sends an upload header and a body, sleeps 50 milliseconds so the server has time to answer and close, then reads. The server answers with a 413 and closes in one of four ways. Each configuration ran 10 times on Windows 11 with CPython 3.13.5; the TCP stack is the operating system's, so other systems can differ in detail.

Server closeBody of 0 bytesBody of 4,000,000 bytes
Read the whole body, then close10 of 10 read the 41310 of 10 read the 413
Close with the body unread10 of 10 read the 4130 of 10 read the 413
SO_LINGER on with a zero timeout, then close0 of 10 read the 4130 of 10 read the 413
Lingering close: shut down writes, drain, then close10 of 10 read the 41310 of 10 read the 413

With nothing unread, a plain close is fine. With a large unread body, the client never saw the response: on the read it got ConnectionResetError in 9 or 10 of 10 trials across runs, and its send of the body failed in every trial. A 1,000-byte body is a race: the server's header read sometimes picks up the whole body, and in one run 2 of 10 trials still saw a reset. SO_LINGER with a zero timeout is the explicit form of the same thing: close sends a reset immediately, unread data or not, and the client lost the 413 every time.

Why the client loses data it already received

The server's sendall(RESPONSE) put the 413 on the wire, and in the trials above it arrived in the client's receive buffer. But the client application had not called recv yet; it was still sending its body. When the reset arrives, the client's stack aborts the connection, and on common stacks the reset also discards whatever was buffered and unread. The next recv reports the reset instead of returning the buffered bytes. From the application's point of view, the server never answered.

This is why the bug shows up with large uploads and slow clients, and why it is intermittent with small bodies: whether there is unread data at the moment of close, and whether the client has already read the response, are both timing questions.

The fix: a lingering close

The server should stop sending, keep reading until the client stops or a bound expires, and only then close:

conn.sendall(RESPONSE)
conn.shutdown(socket.SHUT_WR)          # FIN after the response: the client sees a clean end of the reply
conn.settimeout(2.0)
deadline = time.monotonic() + 2.0
try:
    while time.monotonic() < deadline:  # read and discard what the client is still sending
        if not conn.recv(65536):        # empty read: the client closed its side
            break
except (socket.timeout, OSError):
    pass
conn.close()

shutdown(SHUT_WR) sends a FIN, so the client can read the 413 and see a clean end of the response. Draining keeps the receive buffer empty, so the eventual close has nothing unread and sends no reset. The bound matters: a client that keeps sending forever must not hold the connection open forever. In the probe this close delivered the 413 in every trial, including the 4,000,000-byte body.

You rarely write this yourself. Mature HTTP servers implement it. nginx's lingering_close directive defaults to on, which waits for and processes additional client data before fully closing, but only when heuristics suggest the client may be sending more; always waits unconditionally, and off closes immediately, which the documentation says breaks the protocol and should not be used under normal circumstances. lingering_time (default 30 seconds) caps the total time spent reading, and lingering_timeout (default 5 seconds) caps the wait between reads. If you run a custom server, a sidecar written in a few lines of socket code, or a framework handler that closes the raw connection on error, check what it does.

Other ways to avoid the race

  • Read the body anyway, up to a limit. If rejected bodies are usually small, reading and discarding them before answering avoids the issue entirely.
  • Use Expect: 100-continue. A client that sends this header waits for the server's interim 100 Continue before sending the body. The server can answer 413 instead, and no body is in flight. Support varies by client and proxy, so treat it as an optimization, not the fix.
  • Keep the connection open for the next request. In HTTP/1.1 a server that rejects a request but wants to keep the connection must read the whole body anyway to find the next request, which also avoids the reset.
  • Retry idempotent requests on reset. On the client side, a reset during an upload is ambiguous. For non-idempotent operations it should surface as an error, not trigger a silent retry.

SO_LINGER zero: when a reset is intended

Setting SO_LINGER to on with a zero timeout makes close abort the connection with a reset and skip TIME_WAIT. It is sometimes used to avoid TIME_WAIT accumulation on the side that closes first. The probe shows the cost: any response not yet read by the peer can be discarded. Use it only when you want the peer to see an abort, for example after detecting a protocol violation, and never as a performance setting on a server that has just written a response.

Verification in your own environment

  1. Reproduce with the companion probe on the operating system you deploy to.
  2. Capture packets on the server during a rejected large upload. A plain close with unread data shows the response followed by a RST from the server; a lingering close shows the response, a FIN from the server, the rest of the client data, and a FIN from the client.
  3. In server metrics, compare responses written with responses the clients report. A gap concentrated on 4xx responses to large requests points at this.

Failure modes

  • A framework error handler that closes the socket directly after writing an error, bypassing the server's lingering logic.
  • A load balancer that reuses the backend connection and gets a reset mid-request, reported as a 502.
  • An unbounded drain that lets a client hold server sockets open.
  • Blaming the network or the client when the reset was generated by the server's own close.

Limits

The measurements come from one machine on loopback, where timing is tight and buffers are large; across a real network the outcome for small and medium bodies is a race whose odds depend on latency and buffer sizes. The rule from the RFC and the lingering-close fix do not depend on the platform.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/tcp_close_unread_reset. Views are my own and do not represent any employer, past or present.