Why a Quiet TCP Stream Needs Its Own Heartbeat in Go
A long-lived stream over TCP can be completely dead and your Go code will not notice. The read blocks, no error arrives, and the goroutine sits there for hours. Nothing has crashed; the link has simply gone quiet, and TCP does not tell you the difference between "nothing to say" and "nobody there".
This bites hardest on gRPC-style streams: a server pushing occasional events, a client waiting for them. Most of the time nothing is sent. That is exactly the traffic pattern that lets a broken path hide.
How a connection dies without telling you
TCP only reports a failure when it tries to send something and gets no answer. An idle connection sends nothing, so it learns nothing. Several things can kill the path silently:
- A NAT or stateful firewall expires its table entry after some minutes of silence and drops the packets that follow.
- The peer machine loses power, or a mobile client changes network, with no FIN or RST ever sent.
- A cable or radio link dies somewhere in the middle.
- The remote process is alive but wedged, so the kernel still ACKs everything.
The reader sees none of this. Read blocks, and a blocked Read with no deadline is allowed to block forever.
Surely TCP keepalive handles this?
Partly, and the partly is the trap. Keepalive is a kernel feature that sends empty probes on an idle connection. On Linux the defaults are two hours of idle time before the first probe, then probes every 75 seconds, giving up after 9 (see tcp(7)). That is far too slow for a NAT that forgets you after five minutes.
Go helps here: since Go 1.13, net.Dialer enables keepalive with a 15 second period by default, and listeners do the same for accepted connections. So you probably have faster probes already. It is still not enough, for three reasons:
- It only proves the remote kernel is alive, not that your peer's code is making progress.
- The effective detection time is tied to kernel settings and platform quirks, not to what your protocol needs.
- Proxies and load balancers terminate TCP themselves. Your keepalive probes reach the proxy, which cheerfully answers them while the backend behind it is long gone.
That last one is worth sitting on for a second. With a proxy in the path there are two TCP connections, and keepalive on one says nothing about the other.
Detour: what gRPC does about this
gRPC solved this at the application layer with HTTP/2 PING frames. In grpc-go the client side is keepalive.ClientParameters: Time (idle period before pinging), Timeout (how long to wait for the ack), and PermitWithoutStream.
The sharp edge is on the server. Its enforcement policy has a MinTime that defaults to five minutes. A client that pings more often gets a GOAWAY with "too_many_pings". So a keen client with a 10 second ping against a default server does not get faster failure detection; it gets disconnected. Both ends have to agree.
If you are rolling your own framed protocol, you get to make the same decision yourself.
The fix: a heartbeat plus a read deadline
The pattern has two halves. One side sends a tiny frame on a timer. The other side resets a read deadline every time any frame arrives. If the deadline fires, the peer is presumed dead and you close the connection.
Here is a length-prefixed reader where a zero-length frame is the heartbeat:
const (
pingEvery = 15 * time.Second
idleLimit = 45 * time.Second // three missed pings
maxFrame = 1 << 20
)
func readLoop(c net.Conn, handle func([]byte)) error {
var hdr [4]byte
for {
if err := c.SetReadDeadline(time.Now().Add(idleLimit)); err != nil {
return err
}
if _, err := io.ReadFull(c, hdr[:]); err != nil {
return err // includes the timeout: peer is silent
}
n := binary.BigEndian.Uint32(hdr[:])
if n == 0 {
continue // heartbeat, deadline reset on next loop
}
if n > maxFrame {
return errors.New("frame too large")
}
buf := make([]byte, n)
if _, err := io.ReadFull(c, buf); err != nil {
return err
}
handle(buf)
}
}
And the writer side. Writes from the heartbeat goroutine and from real traffic must not interleave, so they share a mutex:
type writer struct {
mu sync.Mutex
c net.Conn
}
func (w *writer) send(p []byte) error {
w.mu.Lock()
defer w.mu.Unlock()
if err := w.c.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
return err
}
frame := make([]byte, 4+len(p))
binary.BigEndian.PutUint32(frame, uint32(len(p)))
copy(frame[4:], p)
_, err := w.c.Write(frame)
return err
}
func (w *writer) heartbeat(ctx context.Context) error {
t := time.NewTicker(pingEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
if err := w.send(nil); err != nil {
return err
}
}
}
}
Each side runs both halves, so each side proves to the other that it is still there. Run readLoop and heartbeat under one errgroup or close the connection when either returns; otherwise the survivor keeps going against a corpse.
Details that are easy to get wrong
- Set the deadline to a multiple of the ping interval, not the interval itself. One late packet should not kill a healthy link. Three intervals is a reasonable start.
- Reset the deadline on any received frame, not just heartbeats. Real traffic proves liveness too.
- Keep the write deadline. A dead peer with a full send buffer blocks
Writejust as a silent one blocksRead. - Pick the ping interval below the shortest idle timeout in the path. Home routers, cloud load balancers and carrier-grade NAT often sit somewhere between one and five minutes.
- Skip a ping if you sent real data recently. It is a small saving, but it matters on metered links.
Testing it without pulling a cable
You can simulate the silent failure on Linux with a firewall rule on the server that drops the client's packets without rejecting them. A DROP (not REJECT) matches what a forgetful NAT does, and no RST ever comes back.
Start the stream, add the rule, and time how long until your read loop returns. It should be close to idleLimit. Without the heartbeat code, it will be however long the kernel takes to give up, which for an idle receiver may be never.
One thing worth leaving in your head: the heartbeat does not make the network reliable. It just converts "hang forever" into "error within 45 seconds", which is the only thing your reconnect logic can act on.