Skip to content

cloudflare:sockets: first write after startTls() fails with "Network connection lost." when the pre-TLS reply was already buffered before read() was called #8882

Backlog

Description

@wovalle

What happens

A Postgres client over cloudflare:sockets does STARTTLS like this:

  1. connect(addr, { secureTransport: "starttls" }), await socket.opened
  2. await writer.write(SSLRequest)
  3. await reader.read(): the server answers one byte, S
  4. release the reader and writer locks, socket.startTls(), await secure.opened
  5. write the Postgres StartupMessage on the secure socket

If the S is already buffered when reader.read() is called in step 3, the write in step 5 rejects with Error: Network connection lost. (retryable: true). opened resolved normally on both the plain and the secure socket. If the read is called before the S arrives, nothing goes wrong, even when that read is awaited only later.

In production this happens on its own when two requests in one isolate open sockets 0–20 ms apart. The SSLRequest write's promise then resolves a few ms late, by which time the S has arrived. Sleeping between the write and the read forces it in a single request, every time.

Minimal repro

No dependencies. No credentials needed: the failure happens before authentication. PG_HOST/PG_PORT point at any Postgres that accepts SSLRequest.

import { connect } from "cloudflare:sockets";

const SSL_REQUEST = new Uint8Array([0, 0, 0, 8, 4, 210, 22, 47]);
const body = new TextEncoder().encode("user\0dummy\0database\0postgres\0\0");
const STARTUP = new Uint8Array(8 + body.length);
new DataView(STARTUP.buffer).setInt32(0, STARTUP.length);
new DataView(STARTUP.buffer).setInt32(4, 196608); // protocol 3.0
STARTUP.set(body, 8);

export default {
  async fetch(request, env) {
    const q = new URL(request.url).searchParams;
    const readFirst = q.get("order") === "read-first";
    const wait = Number(q.get("wait") ?? 0);
    const waitBeforeStartTls = q.get("at") === "before-starttls";
    let step = "connect";
    try {
      const plain = connect({ hostname: env.PG_HOST, port: Number(env.PG_PORT) }, { secureTransport: "starttls" });
      await plain.opened;
      const reader = plain.readable.getReader();
      const writer = plain.writable.getWriter();
      const early = readFirst ? reader.read() : undefined;
      await writer.write(SSL_REQUEST);
      if (wait && !waitBeforeStartTls) await scheduler.wait(wait); // let the "S" arrive first
      const { value } = await (early ?? reader.read());
      if (value?.[0] !== 0x53) throw new Error(`expected S, got ${value?.[0]}`);
      if (wait && waitBeforeStartTls) await scheduler.wait(wait);
      reader.releaseLock();
      writer.releaseLock();
      step = "startTls";
      const secure = plain.startTls();
      await secure.opened;
      step = "startup.write";
      await secure.writable.getWriter().write(STARTUP);
      step = "startup.read";
      const first = await secure.readable.getReader().read();
      await secure.close();
      return Response.json({ ok: true, first: String.fromCharCode(first.value[0]) });
    } catch (e) {
      return Response.json({ ok: false, step, error: String(e), retryable: e.retryable });
    }
  },
};
// wrangler.jsonc
{
  "name": "starttls-repro",
  "main": "worker.js",
  "compatibility_date": "2025-04-04",
  "compatibility_flags": ["nodejs_compat", "nodejs_compat_populate_process_env"],
  "workers_dev": true,
  "vars": { "PG_HOST": "your-postgres-host", "PG_PORT": "5432" }
}

How to run

npx wrangler deploy
curl 'https://starttls-repro.<subdomain>.workers.dev/?wait=20'                     # fails
curl 'https://starttls-repro.<subdomain>.workers.dev/?wait=20&at=before-starttls'  # ok
curl 'https://starttls-repro.<subdomain>.workers.dev/?order=read-first&wait=20'    # ok
curl 'https://starttls-repro.<subdomain>.workers.dev/'                             # ok

wait only has to be longer than the round trip to the server. 20 ms was enough with the Worker placed next to the database (about 2 ms away), and 300 ms from the default edge location (about 80 ms away). Failing response:

{"ok":false,"step":"startup.write","error":"Error: Network connection lost.","retryable":true}

A fuller version is available if useful. It has n parallel sockets per request, more variants, a rendezvous that makes two external requests meet in one isolate, and a Node driver that prints the tables below. The natural no-wait trigger needs that version, plus targeted placement next to the database.

Expected vs actual

  • Expected: the secure socket accepts the StartupMessage and the server answers (R, an authentication request for the dummy user). This is what happens with at=before-starttls and order=read-first.
  • Actual: when the S was buffered before read() was called, the first write on the secure socket rejects with Network connection lost. (retryable: true). secure.opened had already resolved.

Measurements

All runs below are from the standalone Worker, deployed on workers.dev on 2026-11-24 against one server, a pooler-fronted Postgres. Requests were sent one at a time ("solo") unless noted. Only that one server was tested. Still, the server cannot be the variable: "wait before the read" and "wait before startTls()" put the same bytes on the wire with the same timing, and only the first fails.

Minimal file above, 1 socket per request

Variant Placed next to the DB (wait = 20 ms) Default edge location (wait = 300 ms)
write, then read (no wait) 0 / 100 0 / 100
write, wait, then read 100 / 100 100 / 100
write, read, wait, then startTls() 0 / 100 0 / 100
read called, write, wait, then await the read 0 / 100 0 / 100

Fuller Worker, 5 sockets per request, 100 requests per variant, placed next to the DB

"Reply already buffered" means read() resolved with no I/O event between the call and the resolution (performance.now() did not advance).

Variant Sockets Dropped Reply already buffered Of those, dropped
write, then read 500 0 5 0
read first 500 0 7 0
write, wait 5 ms, read 500 499 500 499
write, wait 20 ms, read 500 500 500 500
write, wait 50 ms, read 500 500 500 500
write, read, wait 5 ms, startTls() 500 0 1 0
write, read, wait 20 ms, startTls() 500 0 3 0
write, read, wait 50 ms, startTls() 500 0 0 0

Every dropped socket failed at the StartupMessage write with Network connection lost. (retryable: true).

Compatibility date and flags, 1 socket per request, 100 requests per cell, placed

Variant 2025-04-04 + nodejs_compat, nodejs_compat_populate_process_env 2025-04-04, no flags 2026-11-24, no flags
write, then read 0 0 0
read posted, wait 20 ms, then await it 0 0 0
write, wait 20 ms, read 100 100 100
write, read, wait 20 ms, startTls() 0 0 0
write, wait 20 ms, read, opened not awaited 87 not run 91

Without await socket.opened, the failures fell exactly on the sockets whose reply was already buffered: 87 of 87, and 91 of 92. Not awaiting opened changes the timing, not the mechanism.

Natural trigger: two external requests in one isolate, no wait

Placed next to the DB. Bursts of 6 requests share a key. A request dials only once a second request with that key is in the same isolate, and the pair starts 0, 5, 10 or 20 ms apart. 5 sockets per request. Only paired requests are counted.

Order Paired requests Requests with a dropped socket Sockets Dropped Reply already buffered Of those, dropped
write, then read 200 4 1,000 5 25 5
read first 200 0 1,000 0 27 0

On read-first rows the timer starts after the write resolves. "Reply already buffered" there means the S had arrived by the time the write resolved, the closest read-first analogue, not that it was there when read() was called (it never is, since that read is called first).

An earlier run without placement, about 80 ms from the server, sent 2 requests per key instead of 6 and no start slots. Write-then-read and read-first each had 0 failures in 200 paired requests. The reply was never buffered.

Earlier harness numbers (a larger application Worker, same mechanism)

Measured before the standalone repro, on a preview deployment of the application where the bug was first seen:

Configuration Overlapped requests Requests with a dropped socket
Raw sockets, write then read 225 11
Raw sockets, read posted first, same run 228 0
Pool on top, write then read 160 45
Same pool, read posted first, same run 160 0
One request alone in the isolate 480 0
Two requests made by the Worker calling itself (ctx.exports loopback) 500 0
Two external requests started 50 ms apart — 0

In the harness, 495 of the 499 sockets whose SSLRequest write resolved in the same millisecond as the S arrived were dropped, against 0 of 17,693 other sockets. On the failing sockets the write took a median 3 ms to resolve, with the other request's events in between.

What triggers it and what does not

Condition Fails?
S already buffered when read() is called (forced with a wait, or by a second request delaying the write's resolution) yes
read() called before the S arrives, even if awaited much later no
Idle time between a normal read and startTls() no
One request alone, no wait no (0 of 480 in the harness, 0 of 100 here)
Two requests in one isolate via ctx.exports loopback no (harness, 0 of 500). Not explained, probably timing
Two external requests 50 ms apart no (harness)
Not awaiting socket.opened no in the natural form (the reply arrives after the read). Yes with a forced wait
Compatibility date 2025-04-04 vs 2026-11-24, with or without nodejs_compat no difference
Worker far from the server (about 80 ms) the natural form did not trigger. The forced form still fails 100 of 100 with a 300 ms wait
Local wrangler dev (wrangler 4.168.0, workerd 1.20261123.1) against a local TLS Postgres no. 0 failures in every variant, including forced waits where the reply was buffered on 481–485 of 500 sockets

Hypothesis (unverified)

ReadableStreamInternalController::read (src/workerd/api/streams/internal.c++) got a synchronous fast path in "Implement tryReadSync/tryWriteSync support" (ffca648, 2026-08-31). Its autogate was removed in "Remove the streams try sync autogate" (aa65c49, 2026-11-12). When data is already parked, the read returns an already-resolved promise. A read called before the data arrives can never take that path. That matches every row above: only reads that found the S buffered are followed by a dead secure socket. Socket::startTls is in src/workerd/api/sockets.c++. The guess is that taking the sync path leaves the plain stream in a state that the TLS upgrade does not account for.

Against it: local workerd 1.20261123.1 should already contain the autogate removal (judged from the commit and release dates, not checked in the binary), and it does not reproduce, even with the reply buffered. So the sync read alone does not drop the connection in the open-source runtime. The part that drops the upgraded connection seems to be in the production socket/TLS path, which is not in the public tree. This is an inference from the two results, not something I traced.

Context

Found through drizzle-orm's Postgres driver, which reads after the write. The driver-side report and workaround (post the read before the write): drizzle-team/drizzle-orm#6735

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions