pingora icon indicating copy to clipboard operation
pingora copied to clipboard

SSE (Server-Sent Events) response body not flushed to downstream on macOS

Open janpoem opened this issue 8 months ago • 4 comments

Description

When proxying SSE (Server-Sent Events) responses through Pingora on macOS, the response body chunks are received from upstream but never flushed to the downstream client. The same setup works correctly on Linux.

Environment

  • macOS: Darwin 24.6.0 (Apple Silicon, aarch64)
  • Linux: Ubuntu 22.04 x86_64 (works correctly)
  • Pingora version: 0.8.0
  • Rust: stable

Steps to Reproduce

  1. Set up a simple upstream server that serves SSE responses (Content-Type: text/event-stream, Transfer-Encoding: chunked)
  2. Configure Pingora as a reverse proxy forwarding to this upstream
  3. Send a GET request to the proxy endpoint from macOS

Expected Behavior

SSE events should be streamed to the client in real-time as they arrive from upstream.

Actual Behavior (macOS only)

  • Pingora successfully connects to upstream and receives the response headers
  • Upstream body chunks are received (confirmed via response_body_filter logging)
  • However, no data reaches the downstream client — curl shows no output
  • After curl timeout, the connection is reset with: Fail to proxy: Downstream ConnectionClosed ... Prematurely before response body is complete
  • Debug logs show the downstream socket's BufWriter has written: 0 despite data being in the buffer

Debug Log Evidence

[DEBUG] Detected streaming response: text/event-stream
[DEBUG] Streaming chunk: 937 bytes, eof: false     ← data received from upstream
[DEBUG] Streaming chunk: 318 bytes, eof: false     ← more data received
[ERROR] Fail to proxy: Downstream ConnectionClosed
        context: Prematurely before response body is complete
        status: 0                                   ← 0 bytes written downstream

The BufWriter state at connection close:

BufStream { inner: BufReader { reader: BufWriter {
  writer: ..., buffer: 0/1460, written: 0           ← 1460 bytes buffered, 0 written
}}}

Analysis

The issue appears to be in the HTTP/1.1 downstream write path. Pingora's do_write_chunked_body in body.rs does call stream.flush() after each chunk write. However, on macOS, the data appears to remain in the BufWriter's buffer (1460 bytes = typical TCP MSS) without being flushed to the socket.

This suggests a platform-specific difference in how AsyncWrite::flush() behaves on macOS vs Linux TCP sockets, possibly related to:

  • TCP_NODELAY not being set on the downstream socket
  • macOS TCP stack buffering behavior differences
  • BufWriter not propagating flush to the underlying TCP stream

Workarounds Attempted (none worked on macOS)

  • session.set_keepalive(None)
  • Custom response_body_filter returning Ok(None) (no delay)
  • Custom upstream_response_filter setting chunked encoding headers
  • Removing all custom filters (bare Pingora proxy) — still fails on macOS

Impact

  • Normal HTTP requests (GET, POST with complete responses) work fine on macOS
  • Only streaming/long-lived responses (SSE, potentially WebSocket) are affected
  • Linux works perfectly — this is macOS-only

Notes

macOS is commonly used for development. While Pingora is primarily designed for Linux production deployments, macOS development support would significantly improve the developer experience.


Reported by siyuan — discovered while building gateway-rs

janpoem avatar Mar 20 '26 02:03 janpoem

Unable to reproduce: SSE streams correctly through Pingora on macOS (Apple Silicon)

I tried to reproduce this on current master and could not get the body to stall. SSE events stream through the proxy in real time with no added latency. Here is the setup and what I tested.

Environment

OS macOS 26.5.1 (build 25F80), Darwin kernel 25.5.0
CPU / arch Apple M4 Pro (Mac16,7), arm64
Pingora master @ d9e6d7a (workspace version 0.8.0)
Rust rustc 1.96.0 (ac68faa20)
tokio 1.52.3
mio 1.2.1
curl 8.7.1 (LibreSSL/SecureTransport)
Python (test origin) 3.14.5

Setup

A reverse proxy with no custom filters, forwarding to a minimal SSE origin:

struct SseProxy;
#[async_trait]
impl ProxyHttp for SseProxy {
    type CTX = ();
    fn new_ctx(&self) {}
    async fn upstream_peer(&self, _s: &mut Session, _c: &mut ()) -> Result<Box<HttpPeer>> {
        Ok(Box::new(HttpPeer::new("127.0.0.1:8191", false, String::new())))
    }
}

The origin sends a chunked text/event-stream response with Content-Type: text/event-stream and Transfer-Encoding: chunked, emitting one event per second and flushing after each one.

Results

  1. Real curl -N through the proxy. Events arrive one per second:
[18:04:26] data: {"seq":0}
[18:04:27] data: {"seq":1}
[18:04:28] data: {"seq":2}
[18:04:29] data: {"seq":3}
[18:04:30] data: {"seq":4}
  1. Raw-socket client timestamping each recv(), to remove any client/tooling buffering. Each event reaches the client in the same second the origin sends it:
Event Origin sent Client received
seq=0 18:05:57 18:05:57
seq=1 18:05:58 18:05:58
seq=2 18:05:59 18:05:59
seq=3 18:06:00 18:06:00
  1. A Rust integration test (real pingora_proxy::ProxyHttp server, tokio TCP SSE origin, TCP client). It passes, and the first event is forwarded within the same millisecond the origin emits it.

I also tested the HTTP/1.1 downstream write path directly with unit tests against HttpSession: chunked body write plus flush, small events that fit in the ~1460-byte L4 write buffer, large events that exceed it, and the batched response_duplex_vec header+body path. All flushed correctly to a real TCP client.

A buffering caveat that may explain the original report

When I saw what looked like a stall, the cause was buffering on the client/observer side, not in Pingora:

  • A client that issues a single read() and inspects it usually gets only the response headers in that first read. The first body chunk arrives in a later read. Asserting on the first read alone looks like no body was sent.
  • Piping curl output through grep or while read introduces line/pipe buffering that batches the output and hides the real-time delivery.

Given that current master streams correctly on macOS / Apple Silicon, the original report may have been affected by client-side buffering, or resolved by the HTTP/1.x downstream write-path changes that landed after the issue was filed (March 2026).

If you can share a self-contained repro (origin, proxy, and the exact client command, ideally curl -N or a raw socket reader with timestamps), I will re-test on this hardware.

JulienEllie avatar Jun 07 '26 01:06 JulienEllie

I've encountered the same issue. I developed an LLM proxy using Pingora. Streaming output works fine with curl -N, but when using Codex, the LLM response only appears in Codex after each "flushing". I'm not sure where to make adjustments. It feels like the phenomenon described in this article: https://community.cloudflare.com/t/sse-endpoint-breaks-after-recent-update-cloudflare-buffers-text-event-stream-desp/810790

shenshouer avatar Jun 10 '26 08:06 shenshouer

Tried to reproduce this on Apple Silicon and could not, in three configurations.

Setup: a plain pass-through ProxyHttp (no filters, no modules beyond the defaults) listening on plain TCP, upstream is a minimal socket server emitting one SSE event per second, client is curl -sN with per-line arrival timestamps.

Hardware Apple Silicon, Darwin 25.5.0
Tested current main (chunked upstream), current main (Connection: close unframed upstream), released 0.8.0 from crates.io (chunked upstream)
Result every event arrived 20-35 ms after the upstream emitted it, in all three cases — indistinguishable from connecting to the upstream directly

Since @JulienEllie also could not reproduce on master, two things about the original report stand out:

  1. "Upstream body chunks are received (confirmed via response_body_filter logging)" — this means the proxy had a custom response_body_filter. A filter that accumulates chunks and only emits at end_of_stream (the pattern in examples/modify_response.rs) produces exactly this symptom for SSE, because end of stream never comes: chunks visible in the filter, zero bytes to the client, then the client times out. That behavior would be OS-independent though, so if Linux truly worked with byte-identical proxy code and config, this isn't it.
  2. An enabled response compression module buffers small chunks similarly.

@janpoem could you share the ProxyHttp impl (especially any body filters or modules) and the pingora feature flags you built with? If a plain pass-through proxy also fails on your machine with the setup above, that would isolate it to the environment rather than the proxy code.

nbarbier-265 avatar Aug 20 '26 21:08 nbarbier-265

Built a self-contained repro against main (4487f7b) and ran it on Linux: https://github.com/aron-intframe/pingora-841-sse-repro

--- body chunk arrivals (ms): [303, 604, 905, 1208, 1508]
VERDICT: STREAMED (each event delivered as it was produced)

Two details in the report look misread, both worth ruling out before hunting a platform bug.

  1. buffer: 0/1460 is tokio's BufWriter Debug, printed as {len}/{capacity}. Measured on tokio 1.53.1:
after 937 bytes:  buffer: 937/1460, written: 0
after flush():    buffer: 0/1460, written: 0

So buffer: 0/1460, written: 0 is an empty, already-flushed writer, not 1460 bytes stuck.

  1. status: 0 is res.error_code. The comment directly above that log line (pingora-proxy/src/lib.rs:1389) reads "final error will have > 0 status unless downstream connection is dead". It is not a byte count.

TCP_NODELAY is also already unconditional on every accepted downstream stream (apply_stream_settings -> Stream::set_nodelay, listeners/l4.rs:433), and poll_write/poll_flush in protocols/l4/stream.rs carry no #[cfg(target_os)] branch at all; the only platform splits in that file are poll_read/set_rx_timestamp for rx timestamping.

I have no Darwin machine, so the macOS failure itself is unverified here. Could you run cargo run --bin sse-repro on your 24.6.0 box and paste the arrival lines? SSE_REPRO_WITHHOLD=1 flips the verdict to NOT STREAMED, so the harness does fail when a stream is withheld.

aron-intframe avatar Sep 24 '26 20:09 aron-intframe