Repository navigation
Description
Observed behavior
Client._force_flush writes b"".join(self._pending_messages), awaits self._connection.write(...) (which, on a TCP connection, awaits StreamWriter.drain()), and only then calls self._pending_messages.clear(). While that write waits for the socket to drain:
- a message that another task publishes meanwhile is appended to the list and then cleared without ever being written: it is lost;
- a
publish()that finds the buffer still full (512 messages or 1 MiB) calls_force_flushagain and writes the same, not yet cleared, batch once more.
With the script below (one publishing connection, the server paused briefly as a slow reader, a small kernel send buffer):
drop: about 290 small messages are published while three 750 KB messages drain; about 29 reach a subscriber.repeat: 5,000 tasks each publish one 600-byte message at once; the subscriber receives the first 512 messages 4,489 times each (2,298,368 deliveries) and none of the other 4,488.
In an application that publishes a few thousand JetStream messages concurrently over a slower link (nats-core 0.2.0, whose _force_flush and publish flush check are the same), the client wrote about 990,000 publish frames for 5,000 messages; the server then closed the connection as a slow consumer (Slow Consumer Detected: WriteDeadline of 10s exceeded) and the waiting publishes failed. Splitting the publishes into groups of 100, each awaited before the next, avoids it in that application.
Expected behavior
Each published message is written once, and the messages of one task are written in the order it published them, whatever other tasks do while a write drains.
A possible fix is to detach the batch before awaiting the write, so that concurrent callers find an empty or newer buffer:
async def _force_flush(self) -> None:
if not self._pending_messages or not self._connection.is_connected():
return
pending, self._pending_messages = self._pending_messages, []
self._pending_bytes = 0
await self._connection.write(b"".join(pending))With this change applied to 0.3.0, both modes of the script below deliver every message once (missing=0 repeated=0). The reconnect path already removes only the batch it wrote (#981); the same change in _force_flush fixes drop but not repeat, because the batch stays in the buffer while it drains. StreamWriter.write queues the bytes before drain() is awaited, so writes keep their order. What should happen to a detached batch whose write fails (put back in front of the buffer, or dropped as the connection is lost) is for the maintainers to decide.
Server and client version
nats-core 0.3.0 (_force_flush and the flush check in publish are the same on main at 569588f); nats-server 2.15.3.
Host environment
macOS 27.2.1 on Apple silicon, CPython 3.14.3.
Steps to reproduce
pip install nats-core==0.3.0
python flush_race.py "$(which nats-server)" drop
python flush_race.py "$(which nats-server)" repeatOutput:
mode=drop published=289 delivered=29 missing=260 repeated=0 most_copies=1
mode=repeat published=5000 delivered=2298368 missing=4488 repeated=512 most_copies=4489
Without the small send buffer, drop loses nothing on this host's loopback socket; repeat still loses and repeats messages (missing=904 to 2440 in three runs).
flush_race.py (nats-core and nats-server only)
"""Count what a subscriber receives when publishes overlap a flush that waits for the socket to drain.
Usage: python flush_race.py <nats-server binary> <mode>
mode "drop": one task publishes a 750 KB message every 20 ms while another publishes small
numbered messages every 2 ms; the server is paused 200 ms around each large
publish, as a busy server reads slowly.
mode "repeat": 5000 tasks each publish one numbered 600-byte message at once (more than the
512 pending messages that make publish() flush); the server is paused 300 ms
when the burst starts.
"""
import asyncio
import collections
import os
import signal
import socket
import subprocess
import sys
import tempfile
from nats.client import connect
def free_port() -> int:
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
async def main(server_bin: str, mode: str) -> None:
port = free_port()
with tempfile.TemporaryDirectory() as store:
server = subprocess.Popen(
[server_bin, "-a", "127.0.0.1", "-p", str(port), "-sd", store],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
for _ in range(100):
try:
subscriber = await connect(f"nats://127.0.0.1:{port}", allow_reconnect=False)
break
except OSError: # the server is still starting
await asyncio.sleep(0.05)
else:
raise RuntimeError("server did not start")
publisher = await connect(f"nats://127.0.0.1:{port}", allow_reconnect=False)
# A small kernel send buffer, as on a slow link, so a write waits for the transport to drain.
sock = publisher._connection._writer.transport.get_extra_info("socket")
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32 * 1024)
received: collections.Counter[int] = collections.Counter()
subscription = await subscriber.subscribe("numbered")
async def receive() -> None:
async for message in subscription:
received[int(message.data[:10])] += 1
receiver = asyncio.create_task(receive())
await subscriber.flush()
async def pause(ms: int) -> None:
os.kill(server.pid, signal.SIGSTOP)
await asyncio.sleep(ms / 1000)
os.kill(server.pid, signal.SIGCONT)
published = 0
if mode == "drop":
large = b"x" * 750_000
done = asyncio.Event()
async def publish_large() -> None:
for _ in range(3):
os.kill(server.pid, signal.SIGSTOP)
await publisher.publish("large", large)
await asyncio.sleep(0.2)
os.kill(server.pid, signal.SIGCONT)
await asyncio.sleep(0.02)
done.set()
async def publish_small() -> None:
nonlocal published
while not done.is_set():
await publisher.publish("numbered", b"%010d" % published)
published += 1
await asyncio.sleep(0.002)
await asyncio.gather(publish_large(), publish_small())
else:
padding = b"x" * 590
async def publish_one(number: int) -> None:
await publisher.publish("numbered", b"%010d" % number + padding)
published = 5000
await asyncio.gather(pause(300), *(publish_one(number) for number in range(published)))
await publisher.flush(timeout=10)
await asyncio.sleep(1)
receiver.cancel()
print(
f"mode={mode} published={published} delivered={sum(received.values())} "
f"missing={published - len(received)} repeated={sum(1 for n in received.values() if n > 1)} "
f"most_copies={max(received.values(), default=0)}"
)
finally:
os.kill(server.pid, signal.SIGCONT)
server.terminate()
server.wait()
if __name__ == "__main__":
asyncio.run(main(sys.argv[1], sys.argv[2]))
Activity
clemlesne commentedon Nov 25, 2026
Two additions, to settle the open point and make the change easy to review.
A batch whose write fails is dropped, not put back. This matches the other NATS clients. The legacy
natsclient empties its buffer before awaitingdrain()(nats/aio/client.py). nats.go resets its buffer after a write, failed or not (flush,flushPendingBuffer: "we don't want to take the risk of sending duplicates or partials"). Putting several detached batches back in front of the buffer would also need extra state to keep their order.Regression tests, in the style of the mock-server tests in
nats-core/tests/test_client.py:mainit receives 45,568 frames for 600 messages and 4,318 for 160.Both fail on
main(67834ba) and pass with the change. With the change, the nats-core and nats-jetstream suites show no new failures, and both modes offlush_race.pyreportmissing=0 repeated=0.The groups-of-100 workaround only helps with small messages. With JetStream publishes of about 16 KB, a group of 100 is already past the 1 MiB limit: about 30 of each 100 never reach the server, and their publishes time out.