Skip to content

Bound socket writes with a default send timeout - #89

Open
joshk wants to merge 1 commit into
CuatroElixir:mainfrom
joshk:fix/default-send-timeout
Open

joshk wants to merge 1 commit into
CuatroElixir:mainfrom
joshk:fix/default-send-timeout

Conversation

@joshk

@joshk joshk commented Oct 18, 2026

Copy link
Copy Markdown

Closes #85

Problem

As described in #85, writes to the socket have no timeout. The path is Impl.push_message/2 → Mint.WebSocket.stream_request_body/3 → :gen_tcp.send/2 / :ssl.send/2, and Mint doesn't set :send_timeout.

When the peer stops reading (a stalled server, a dead load balancer path, a zero TCP window), the send buffers fill and the write blocks indefinitely. The connection process is then stuck inside the send. It can't process the heartbeat tick that would detect the dead connection, or the client's :DOWN, or anything else. It never self-heals, and its mailbox keeps growing.

I reproduced this against main with a peer that completes the upgrade and then stops reading:

  • With a 200 ms heartbeat interval and no heartbeat ever acknowledged, there was still no :heartbeat_timeout after 3 seconds.
  • The connection process's stack was in :prim_inet.send/4 via Mint.WebSocket.stream_request_body/3.
  • After the client process had exited, the connection process was still alive and stuck, holding the unsent payload.

Changes

Following option (b) from #85:

The default of 30 seconds matches the default heartbeat interval, so a stalled write is noticed within about two heartbeat intervals. [Happy to derive it from :heartbeat_interval_msec instead if you'd prefer.]

Compatibility

  • Writes that previously blocked forever now disconnect after 30 seconds.
  • A very large push over a very slow link could hit the timeout; it's configurable, and 0 restores the old behaviour.

How this was found, and AI use

I found this during a review of Slipstream's memory and timeout behaviour that I did with Claude Code, before I saw #85. Claude reproduced the blocked send against main and wrote this change and its tests. [@oliver-kriska offered a PR for #85; I'm happy to defer to theirs if it's already in progress.]

Closes CuatroElixir#85

Writes to the socket (`Mint.WebSocket.stream_request_body/3` ->
`:gen_tcp.send/2` / `:ssl.send/2`) had no timeout. When the peer stops
reading (a stalled server, a dead load balancer path, a zero TCP window)
the send buffers fill and the write blocks indefinitely. The connection
process is then stuck inside the send: it can no longer process the
heartbeat tick which would detect the dead connection, the client's
`:DOWN`, or any other message, so it never self-heals and its mailbox
grows without bound.

This adds a `:send_timeout_msec` option (default 30 seconds, `0` to
disable) which sets the `:send_timeout` and `:send_timeout_close`
transport options. A write which times out closes the socket and the
client gets `handle_disconnect/2` with `{:send_failure, reason}`, which
reconnects by default. Transport options given explicitly in
`:mint_opts` take precedence over these defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@oliver-kriska

Copy link
Copy Markdown

@joshk nothing in progress, somehow I'm more busy than I wanted but at least I can share some of my data. I will ask claude to give you data what I gathered from our production, or some summary of it which can be useful.

@oliver-kriska

Copy link
Copy Markdown

@joshk thanks for picking this up. Here is what we observed in production, plus a few notes from running the PR locally.

What we saw in production

Setup: one long-lived WSS client per node, multiplexing multiple topics. The incident ran Slipstream 1.2.2, Mint 1.9.0, MintWebSocket 1.0.5 and OTP 29.0.2.

We have eight memory-watchdog samples from 2026-06-30 and 07-01. In each one, Slipstream.Connection was the largest recorded process, at roughly 0.58–2.55 GiB of process memory (Process.info(:memory)). Three of the samples caught it waiting in a synchronous TLS send:

:gen.do_call/4 ← :gen_statem.call/3 ← :tls_sender.call/2 ← :ssl.send/2 ← Mint.WebSocket…

That is the same synchronous-send boundary your test reaches, through TLS rather than plain TCP. A snapshot shows where the process was waiting, not how long that particular call stayed blocked. These were watchdog reports, not confirmed kernel OOM kills.

Corrections to #85

We filed #85, and a few things in it were overstated:

  • The workaround snippet omitted protocols: [:http1]. The PR preserves explicit transport options correctly. Separately, the snippet we posted in Connection can block indefinitely on a stalled send (no send_timeout), defeating heartbeat self-heal and growing the process heap until OOM #85 dropped the default [protocols: [:http1]], because a supplied :mint_opts replaces that default instead of merging into it. Against our endpoint, that allowed HTTP/2 negotiation and failed the upgrade with %Mint.WebSocketError{reason: :extended_connect_disabled}. Could the PR description drop "the existing workaround from Connection can block indefinitely on a stalled send (no send_timeout), defeating heartbeat self-heal and growing the process heap until OOM #85 keeps working unchanged"? A short docs note would also help, for example "passing :mint_opts replaces the default, so include protocols: [:http1]".
  • The memory mechanism. Our application stored large structs in socket assigns, and Slipstream forwards the socket in JoinTopic commands. Local experiments showed substantial amplification during join bursts. We haven't established the full allocation and retention mechanism behind the production numbers. The connection's message queue was 0–5 in all eight samples.
  • Which frame blocked. We did not establish which frame was blocked in production; the issue's claim that it was the heartbeat is unproven. What does hold is that a later heartbeat timeout cannot interrupt a send that is already blocked.

Since we set a send timeout ourselves

We run protocols: [:http1] plus send_timeout: 15_000, send_timeout_close: true. From 2026-09-20 to 10-20, on three nodes:

count
successful connects (including restarts) 321
successful joins ~50k
disconnect closed_by_remote 260
disconnect heartbeat_timeout 2
disconnect other reasons 6
recorded send_failure disconnects 0

That is a quiet-run baseline. It is not production evidence that the timeout recovered a stalled send.

On OTP-20257 (fixed in 29.0.4, missing tcp_closed notification on the inet-driver TCP path): Slipstream handles the error the send returns, so that path doesn't depend on the tcp_closed notification. Over WSS, the returned reason isn't guaranteed to be :timeout; tls_sender can also return :closed.

Notes from running the PR locally

On OTP 29.0.5 / Elixir 1.20.4, the focused tests passed 201 consecutive runs with one scheduler (+S 1:1) and 12 CPU burners. Disabling the timeout makes the integration test fail its 2-second disconnect assertion.

CI hasn't run on this PR yet. When it does, I expect at least this failure:

0. The lint job will fail to compile on Elixir 1.20. CI runs mix compile --warnings-as-errors with MIX_ENV=test on OTP 29 / Elixir 1.20, and test/support is compiled in that env. Elixir 1.20.4 warns on test/support/fake_websocket_server.ex:176:

warning: the variable "len" is accessed inside size(...) of a bitstring but it was defined outside of the match. You must precede it with the pin operator
    <<payload::binary-size(len), rest::binary>> = data

{payload, rest} = :erlang.split_binary(data, len) compiles cleanly and avoids the pin syntax across the whole Elixir matrix (1.14–1.20). The same helper is in #90/#91/#93, so they need the same fix.

Two more suggestions:

  1. Could the write ordering be explicit? In the normal run, the 8 MB push is queued and the 100 ms heartbeat is the write that actually blocks. If a heartbeat tick lands between join and push, the run can take the unacked-heartbeat close path instead. In a 150 ms-delay variant, it then had not delivered a disconnect callback after eight seconds.

    heartbeat_interval_msec: 0 plus two explicit writes removes that dependency. A second push doesn't work as a drop-in: GoodExample pushes through a synchronous call and exits before handling the disconnect, which is the Return errors from push/5 instead of exiting the caller #90 territory. Joins to two new, distinct topics do work. This version passed 51/51 runs, and 101/101 with +S 1:1 and 12 CPU burners, and it still fails with send_timeout_msec: 0:

    test "a peer which stops reading causes a disconnect" do
      uri =
        Server.start(
          fn sock ->
            Server.handshake(sock)
            {:ok, _opcode, join, _rest} = Server.recv_frame(sock)
            [join_ref, ref, topic, "phx_join", _params] = Jason.decode!(join)
            Server.reply(sock, join_ref, ref, topic, "ok")
            # never read from the socket again
            Process.sleep(:infinity)
          end,
          recbuf: 1_024
        )
    
      client =
        start_supervised!(
          {@client,
           pid: self(),
           uri: uri,
           # no heartbeat, so the writes below are the only ones
           heartbeat_interval_msec: 0,
           send_timeout_msec: 300,
           mint_opts: [protocols: [:http1], transport_opts: [sndbuf: 1_024]]}
        )
    
      assert_receive {@client, :connected}
      GenServer.cast(client, {:join, @topic, %{}})
      assert_receive {@client, :joined, @topic, %{}}
    
      # with an empty send queue, the first write is queued and returns; the
      # next write then blocks until the send timeout
      big = %{"data" => String.duplicate("a", 8_000_000)}
      GenServer.cast(client, {:join, "rooms:big", big})
      GenServer.cast(client, {:join, "rooms:small", %{}})
    
      assert_receive {@client, :disconnected,
                      {:send_failure, %Mint.TransportError{reason: :timeout}}},
                     2_000
    end

    It also exercises the general send_failure branch in Pipeline and the transport-error clause in Impl.push_message/2, so their coveralls-ignore markers could go. The current test reaches the heartbeat's error branch instead.

  2. A stalled-WSS check, even a manual one. Our sampled production path was :ssl.send/2 → :tls_sender, and accepting the options via :ssl.getopts/2 doesn't show that a stalled send actually times out.

— Oliver's Claude & Amp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Connection can block indefinitely on a stalled send (no send_timeout), defeating heartbeat self-heal and growing the process heap until OOM

2 participants