php-nats-jetstream-client 2.42: fast Object Store uploads
(php, nats, release-notes) 30 min read by Bartosz Pachołek
2.42.0 adds putFast() and putStreamFast(): Object Store uploads as one NATS fast-ingest batch. We timed 64 MiB uploads at up to +50 ms round trip, found where small objects lose, and made uploads fail on purpose on nats-server 2.10 to 2.15.
idct/php-nats-jetstream-client 2.42.0, our free NATS and JetStream client for PHP, adds two Object Store methods: putFast() and putStreamFast(). They store an object the way put() and putStream() do, but send its chunks as one fast-ingest batch, so the client no longer waits for acknowledgements window by window. On NATS server 2.14 and later that makes large uploads faster, more so across a long round trip, and a streamed upload holds about one chunk in memory instead of a window of them. Both are opt-in: put() and putStream() are unchanged.
Our last post covered 2.41.0, and no release came out between the two. We ran every example below on PHP 8.5.9 with 2.42.0 from Packagist, against nats-server 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.3 in Docker, with the two small PHP proxies from our last posts: one adds a round trip, the other holds a server's replies for a moment. The output is pasted as it came out.
Three releases to get here
An Object Store object is a set of chunk messages, 128 KiB each by default, plus one meta message that names them. put() publishes every chunk as a JetStream message with its own acknowledgement: it sends a window of chunks, waits for all of their acknowledgements, then sends the next window. Across a network, each window costs a round trip of waiting.
Issue #321 asked whether uploads should use the fast-ingest publisher that 2.39.0 added, and said to measure first. The measurement found that the fixed window of 16 chunks was what slowed long round trips down, so 2.40.0 made the window a setting of up to 64 chunks. A fast upload also needed a safe way out when it fails halfway, and that is what settle() in 2.41.0 gave it: issue #327, the brief for this release, asked for settle() to land first. 2.42.0 is the upload itself, step 2 of #321.
A fast upload adds every chunk but the last to one fast-ingest batch (NATS ADR-50) and commits the batch with the last chunk. The server does not acknowledge each chunk. It sends a flow ack every 100 messages by default, and the client stops to wait only when the flow acks it is still waiting for reach a limit, two by default. The gap mode is always fail: the first lost or refused chunk ends the batch and the upload, because an object with a chunk missing is of no use. Everything after the chunks is put()'s: the digest, the meta record, and the lookup and purge of the previous revision.

What 2.42.0 adds:
putFast()takesput()'s parameters andputStreamFast()takesputStream()'s. Both then take the three settings offastPublisher(), with the same names, defaults and ranges:flow(default 100),maxOutstandingAcks(default 2) andackTimeoutMs(default: the request timeout). A value out of range fails the upload before anything is sent.new ObjectStoreConfig(allowBatched: true), or the optionallow_batched, creates a bucket that allows fast-ingest batches. The bucket needs it.enableFastIngest()gives an existing bucket the flag: it reads the stream's configuration, setsallow_batchedand writes it back, asseal()does.ApiErrCode::BATCH_PUBLISH_DISABLED(10205), the error a bucket without the flag answers with.
The handle's upload window from 2.40.0 does not apply to the new methods: the batch's flow control sets the pace.
Upgrading
composer require idct/php-nats-jetstream-client:^2.42
There is nothing to change in existing code. To use the new methods, the server must be 2.14 or later and the bucket must have the flag, as the runs below show. Require ^2.42 in composer.json when your code calls them, since older releases have neither the methods nor the config field. The other changes in this release are documentation: fastPublisher()'s description of onError now names settle(), and two internal docblocks of ObjectStoreBucket are corrected.
The full record is in the changelog at v2.42.0.
A proof of concept you can run
One Docker Compose project: a standalone server per release we ran, and a 2.15.3 server that abandons an idle fast-ingest batch after two seconds instead of ten.
# The servers of the 2.42 examples: one per nats-server release we ran, and a
# 2.15.3 server that abandons an idle fast-ingest batch after 2 s (idle.conf).
name: fast-upload
services:
s210:
image: nats:2.10-alpine # 2.10.29
command: [-js, -n, s210]
ports: ["15310:4222"]
s211:
image: nats:2.11-alpine # 2.11.17
command: [-js, -n, s211]
ports: ["15311:4222"]
s212:
image: nats:2.12-alpine # 2.12.15
command: [-js, -n, s212]
ports: ["15312:4222"]
s214:
image: nats:2.14-alpine # 2.14.10
command: [-js, -n, s214]
ports: ["15314:4222"]
s215:
image: nats:2.15.3-alpine
command: [-js, -n, s215]
ports: ["15315:4222"]
idle:
image: nats:2.15.3-alpine
command: [-c, /etc/nats/idle.conf, -js, -n, idle]
volumes: ["./idle.conf:/etc/nats/idle.conf:ro"]
ports: ["15316:4222"]
# The server abandons a fast-ingest batch after 2 s instead of the default 10 s,
# so that a slow producer shows quickly. Everything else is the default.
jetstream {
limits {
batch {
timeout: "2s"
}
}
}
{
"require": {
"php": "^8.2",
"idct/php-nats-jetstream-client": "^2.42"
}
}
Every script loads a few helpers. flagOf() reads the bucket stream's allow_batched, chunksIn() asks the server how many chunk messages the bucket's stream holds, and readBack() reads an object one chunk at a time and hashes it:
<?php
// lib.php: the helpers every script here shares.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\JetStreamContext;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreBucket;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreConfig;
/** The client version installed here, as Composer reports it. */
function clientVersion(): string
{
$version = InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client');
return (string) $version;
}
/** Connects to one server, quietly. */
function connect(string $url, mixed ...$options): NatsClient
{
$client = new NatsClient(new NatsOptions(...['servers' => [$url], ...$options]));
$client->connect()->await();
return $client;
}
/** "s215, nats-server 2.15.3": the name and version the server's INFO reports. */
function server(NatsClient $client): string
{
$info = $client->serverInfo();
return sprintf('%s, nats-server %s', $info?->serverName, $info?->version);
}
/** A new, empty bucket, with or without the allow_batched flag. */
function freshBucket(JetStreamContext $js, string $name, bool $fast): ObjectStoreBucket
{
$store = $js->objectStore($name);
try {
$store->deleteBucket()->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
$store->create(new ObjectStoreConfig(allowBatched: $fast))->await();
return $store;
}
/** The bucket stream's allow_batched flag, or "no stream" when there is none. */
function flagOf(JetStreamContext $js, string $bucket): string
{
try {
$info = $js->getStream('OBJ_' . $bucket)->await();
} catch (JetStreamException) {
return 'no stream';
}
return ($info->raw['config']['allow_batched'] ?? false) ? 'true' : 'false';
}
/** How many chunk messages the bucket's stream holds, whatever object they belong to. */
function chunksIn(NatsClient $client, string $bucket): int
{
$reply = $client->request(
'$JS.API.STREAM.INFO.OBJ_' . $bucket,
json_encode(['subjects_filter' => '$O.' . $bucket . '.C.>']),
)->await();
$subjects = json_decode($reply->payload, true)['state']['subjects'] ?? [];
return array_sum($subjects);
}
/** The SHA-256 of an object, read back one chunk at a time. */
function readBack(ObjectStoreBucket $store, string $name): string
{
$hash = hash_init('sha256');
$store->getToCallback($name, function (string $chunk) use ($hash): void {
hash_update($hash, $chunk);
})->await();
return hash_final($hash);
}
/** A producer that returns $count blocks of $block, then null. */
function blocks(string $block, int $count): \Closure
{
$sent = 0;
return function () use (&$sent, $block, $count): ?string {
return $sent++ < $count ? $block : null;
};
}
/** Seconds since $start (an hrtime(true) value), as "12.345 s". */
function since(int|float $start): string
{
return sprintf('%6.3f s', (hrtime(true) - $start) / 1e9);
}
/** An exception as one line: its short class name, err_code when it has one, message. */
function brief(\Throwable $e): string
{
$class = (new \ReflectionClass($e))->getShortName();
$code = $e instanceof JetStreamException && $e->getErrCode() !== null
? ' (err_code ' . $e->getErrCode() . ')'
: '';
return $class . $code . ': ' . $e->getMessage();
}
/** Prints a line, wrapped at 82 characters, continuation lines indented. */
function say(string $line): void
{
echo wordwrap($line, 82, "\n ", true), "\n";
}
delay-proxy.php, the same file as in our 2.40 post, sits between the client and a server and holds every block it reads for half the added round trip in each direction. It keeps reading meanwhile, so the link keeps its speed and only answers later:
<?php
// delay-proxy.php: a TCP proxy that adds a round trip to a NATS connection.
// php delay-proxy.php <listen port> <server host:port> <added round trip ms> <seconds>
// Each direction holds every block it reads for half the added round trip, in order,
// and keeps reading meanwhile, so the link stays as fast as before, only later.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Amp\Pipeline\Queue;
use Amp\Socket\BindContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\Socket;
use function Amp\async;
use function Amp\delay;
use function Amp\Socket\connect;
use function Amp\Socket\listen;
[, $port, $target, $rttMs, $seconds] = $argv;
function pass(Socket $from, Socket $to, float $hold): void
{
$queue = new Queue(4096);
async(function () use ($queue, $to): void {
try {
foreach ($queue->iterate() as [$due, $bytes]) {
$wait = $due - hrtime(true) / 1e9;
if ($wait > 0) {
delay($wait);
}
$to->write($bytes);
}
$to->end();
} catch (\Throwable) {
$to->close();
}
});
try {
while (($bytes = $from->read(limit: 65536)) !== null) {
$queue->push([hrtime(true) / 1e9 + $hold, $bytes]);
}
} catch (\Throwable) {
// the other side went away
}
$queue->complete();
}
// TCP_NODELAY on both legs, as the client sets it, so Nagle adds no wait of its own.
$server = listen("127.0.0.1:$port", (new BindContext())->withTcpNoDelay());
async(function () use ($server, $target, $rttMs): void {
while ($client = $server->accept()) {
$upstream = connect($target, (new ConnectContext())->withTcpNoDelay());
async(fn() => pass($client, $upstream, $rttMs / 2000));
async(fn() => pass($upstream, $client, $rttMs / 2000));
}
});
printf("127.0.0.1:%s -> %s, +%s ms round trip, for %s s\n",
$port, $target, $rttMs, $seconds);
delay((float) $seconds);
exit(0);
hiccup-proxy.php, the same file as in our 2.41 post, holds everything a server sends on a connection for a fixed time once the client publishes to the subject hiccup. Nothing is lost and the connection stays open:
<?php
// hiccup-proxy.php: a TCP proxy that holds the server's replies for a while.
// php hiccup-proxy.php <listen port> <server host:port> <hold s> <lifetime s>
// When the client publishes to the subject "hiccup", all the server sends on
// that connection in the next <hold> seconds is held, then passed on in order.
// Nothing is dropped and the connection stays open: the replies only come late.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Amp\Socket\BindContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\Socket;
use function Amp\async;
use function Amp\delay;
use function Amp\Socket\connect;
use function Amp\Socket\listen;
[, $port, $target, $hold, $seconds] = $argv;
function relay(Socket $client, Socket $server, float $hold): void
{
$until = 0.0; // hold the server's bytes until then (hrtime, seconds)
async(function () use ($client, $server, $hold, &$until): void {
try {
while (($bytes = $client->read()) !== null) {
if ($until === 0.0 && str_contains($bytes, ' hiccup ')) {
$until = hrtime(true) / 1e9 + $hold;
}
$server->write($bytes);
}
$server->end();
} catch (\Throwable) {
$server->close();
}
});
try {
while (($bytes = $server->read()) !== null) {
$wait = $until - hrtime(true) / 1e9;
if ($wait > 0) {
delay($wait);
}
$client->write($bytes);
}
$client->end();
} catch (\Throwable) {
$client->close();
}
}
$listener = listen("127.0.0.1:$port", (new BindContext())->withTcpNoDelay());
async(function () use ($listener, $target, $hold): void {
while ($client = $listener->accept()) {
$server = connect($target, (new ConnectContext())->withTcpNoDelay());
async(fn() => relay($client, $server, (float) $hold));
}
});
printf("127.0.0.1:%s -> %s, holds the replies for %s s after a hiccup, for %s s\n",
$port, $target, $hold, $seconds);
delay((float) $seconds);
exit(0);
The commands, in the order of this post, all in one 2.42.0 install:
(cd servers && docker compose up -d)
composer install
php delay-proxy.php 15302 127.0.0.1:15315 2 1800 &
php delay-proxy.php 15320 127.0.0.1:15315 20 1800 &
php delay-proxy.php 15350 127.0.0.1:15315 50 1800 &
php delay-proxy.php 15324 127.0.0.1:15314 20 1800 &
php hiccup-proxy.php 15330 127.0.0.1:15315 2 1800 &
php -d memory_limit=128M speed.php nats://127.0.0.1:15315
php -d memory_limit=128M speed.php nats://127.0.0.1:15302
php -d memory_limit=128M speed.php nats://127.0.0.1:15320
php -d memory_limit=128M speed.php nats://127.0.0.1:15350
php -d memory_limit=128M speed.php nats://127.0.0.1:15324
php sizes.php nats://127.0.0.1:15315
php sizes.php nats://127.0.0.1:15302
php sizes.php nats://127.0.0.1:15320
php flag.php nats://127.0.0.1:15315
php older.php nats://127.0.0.1:15310 nats://127.0.0.1:15311 nats://127.0.0.1:15312 \
nats://127.0.0.1:15314
php failing.php nats://127.0.0.1:15315
php idle.php nats://127.0.0.1:15316
php idle.php nats://127.0.0.1:15315
php hiccup.php nats://127.0.0.1:15330 nats://127.0.0.1:15315
How much faster
speed.php uploads a 64 MiB object three times with each method and prints the median time. The streamed methods run first, before the script builds the 64 MiB string that put() and putFast() take, so their process peak does not include it. For put() and putStream() it runs the default window of 16 and the largest, 64. It also prints the memory peak above the memory in use when the upload started, and the whole process's peak. Each upload gets a new name and is deleted afterwards, and at the end one more upload with each fast method is read back and compared:
<?php
// speed.php: time each upload method on a 64 MiB object, and the memory it takes.
// php -d memory_limit=128M speed.php <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
$url = $argv[1];
$mib = 64;
$runs = 3;
$client = connect($url);
$js = $client->jetStream();
freshBucket($js, 'bench', fast: true);
$block = random_bytes(65536); // one 64 KiB block, sent 1,024 times
$blocks = $mib * 16;
echo server($client), ', client ', clientVersion(), ', ', $url, "\n";
printf("%d MiB, 128 KiB chunks, median of %d runs, memory_limit %s\n",
$mib, $runs, ini_get('memory_limit'));
echo "method window time above start process peak\n";
$data = null;
$methods = [
['putStream', 16], ['putStream', 64], ['putStreamFast', null],
['put', 16], ['put', 64], ['putFast', null],
];
foreach ($methods as [$method, $window]) {
if ($method === 'put' && $data === null) {
$data = str_repeat($block, $blocks); // put() and putFast() take it whole
}
$store = $js->objectStore('bench', $window ?? 16);
$times = $above = $peaks = [];
for ($run = 1; $run <= $runs; $run++) {
$name = "blob-$method-$window-$run";
$producer = blocks($block, $blocks);
gc_collect_cycles();
memory_reset_peak_usage();
$base = memory_get_usage();
$start = hrtime(true);
$info = match ($method) {
'putStream' => $store->putStream($name, $producer)->await(),
'putStreamFast' => $store->putStreamFast($name, $producer)->await(),
'put' => $store->put($name, $data)->await(),
'putFast' => $store->putFast($name, $data)->await(),
};
$times[] = (hrtime(true) - $start) / 1e9;
$above[] = (memory_get_peak_usage() - $base) / 1048576;
$peaks[] = memory_get_peak_usage() / 1048576;
$store->delete($name)->await();
}
sort($times);
printf("%-14s %6s %8.3f s %9.1f MiB %10.1f MiB %d chunks\n", $method,
$window ?? '-', $times[1], max($above), max($peaks), $info->chunks);
}
// Upload once more with each fast method and read the object back chunk by chunk.
$store = $js->objectStore('bench');
$expected = hash('sha256', $data);
$store->putFast('check-1', $data)->await();
$store->putStreamFast('check-2', blocks($block, $blocks))->await();
echo 'read back: putFast() ',
readBack($store, 'check-1') === $expected ? 'identical' : 'DIFFERENT',
', putStreamFast() ',
readBack($store, 'check-2') === $expected ? 'identical' : 'DIFFERENT', "\n";
$js->objectStore('bench')->deleteBucket()->await();
$client->disconnect()->await();
On loopback, straight to the 2.15.3 server:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15315
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.178 s 9.0 MiB 13.4 MiB 512 chunks
putStream 64 0.160 s 36.1 MiB 40.5 MiB 512 chunks
putStreamFast - 0.090 s 0.8 MiB 5.3 MiB 512 chunks
put 16 0.175 s 9.0 MiB 77.7 MiB 512 chunks
put 64 0.160 s 36.0 MiB 104.7 MiB 512 chunks
putFast - 0.089 s 0.5 MiB 69.2 MiB 512 chunks
read back: putFast() identical, putStreamFast() identical
Through the proxy, with 20 ms added to every round trip:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15320
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.941 s 9.0 MiB 13.4 MiB 512 chunks
putStream 64 0.369 s 36.1 MiB 40.5 MiB 512 chunks
putStreamFast - 0.202 s 0.8 MiB 5.3 MiB 512 chunks
put 16 0.934 s 9.0 MiB 77.7 MiB 512 chunks
put 64 0.367 s 36.0 MiB 104.7 MiB 512 chunks
putFast - 0.219 s 0.5 MiB 69.2 MiB 512 chunks
read back: putFast() identical, putStreamFast() identical
With 50 ms:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15350
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 1.929 s 9.0 MiB 13.4 MiB 512 chunks
putStream 64 0.654 s 36.1 MiB 40.5 MiB 512 chunks
putStreamFast - 0.325 s 0.8 MiB 5.3 MiB 512 chunks
put 16 1.946 s 9.0 MiB 77.7 MiB 512 chunks
put 64 0.652 s 36.0 MiB 104.7 MiB 512 chunks
putFast - 0.351 s 0.5 MiB 69.2 MiB 512 chunks
read back: putFast() identical, putStreamFast() identical

- Even on loopback the fast methods take half the time.
putStreamFast()took 0.090 s against 0.178 s forputStream(), andputFast()0.089 s against 0.175 s forput(). A deeper window hardly helps there. - Across a round trip they beat the deepest window too. At +20 ms,
putStream()took 0.941 s at window 16, 0.369 s at window 64 and 0.202 s as a fast batch. At +50 ms the three were 1.929 s, 0.654 s and 0.325 s. - The round trips explain it. Take the loopback time away from the +50 ms time and divide by 50 ms: window 16 waited about 35 round trips, window 64 about 10, the fast batch about 5. 512 chunks at window 16 make 32 windows, at window 64 eight, plus the round trips of the meta record. A fast batch waits for the batch to start, for a flow ack now and then, for the commit and for the meta.
- The memory is the other half of the story. A streamed fast upload peaked 0.8 MiB above its start, against 9.0 MiB at window 16 and 36.1 MiB at window 64. The release notes give +0.7 MiB against +9.0 MiB; our figure is the highest of three runs.
putFast()holds the object, asput()does, plus about one chunk: the whole process peaked at 69.2 MiB, against 104.7 MiB forput()at window 64.
The release notes measured against nats-server 2.14.10, so we ran that release too, at +20 ms:
s214, nats-server 2.14.10, client v2.42.0, nats://127.0.0.1:15324
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.921 s 9.0 MiB 13.4 MiB 512 chunks
putStream 64 0.378 s 36.1 MiB 40.5 MiB 512 chunks
putStreamFast - 0.182 s 0.8 MiB 5.3 MiB 512 chunks
put 16 0.912 s 9.0 MiB 77.7 MiB 512 chunks
put 64 0.387 s 36.0 MiB 104.7 MiB 512 chunks
putFast - 0.218 s 0.5 MiB 69.2 MiB 512 chunks
read back: putFast() identical, putStreamFast() identical
They give 0.945 s for put() and 0.209 s for a fast batch at +20 ms; we got 0.912 s and 0.218 s. Take all of these numbers as a comparison on one machine, not a benchmark: one PHP process, Docker on localhost, an added delay instead of a real network, and three runs per point. We did not measure TLS, a replicated stream, many uploads at once or CPU use, and neither did the release.
Small objects pay a round trip
A fast upload costs fixed round trips that put() does not: the first chunk waits for the batch to start, and the commit waits for its PubAck. sizes.php uploads objects from 128 KiB to 32 MiB with put() and putFast() in turns, five times each, and prints the medians and their ratio:
<?php
// sizes.php: put() against putFast() by object size, median of 5 runs each.
// php sizes.php <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
$url = $argv[1];
$runs = 5;
$client = connect($url);
$js = $client->jetStream();
$store = freshBucket($js, 'sizes', fast: true);
echo server($client), ', client ', clientVersion(), ', ', $url, "\n";
printf("put() at the default window of 16, median of %d runs\n", $runs);
echo " object chunks put() putFast() putFast / put\n";
foreach ([128, 512, 1024, 2048, 4096, 8192, 16384, 32768] as $kib) {
$data = random_bytes($kib * 1024);
$times = ['put' => [], 'putFast' => []];
for ($run = 1; $run <= $runs; $run++) {
foreach (['put', 'putFast'] as $method) { // taking turns, so drift hits both
$start = hrtime(true);
$info = $store->$method("o-$kib-$run-$method", $data)->await();
$times[$method][] = (hrtime(true) - $start) / 1e9;
$store->delete("o-$kib-$run-$method")->await();
}
}
sort($times['put']);
sort($times['putFast']);
[$slow, $fast] = [$times['put'][2], $times['putFast'][2]];
printf("%5d KiB %7d %8.3f s %10.3f s %13.2f\n",
$kib, $info->chunks, $slow, $fast, $fast / $slow);
}
$store->deleteBucket()->await();
$client->disconnect()->await();
At +20 ms:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15320
put() at the default window of 16, median of 5 runs
object chunks put() putFast() putFast / put
128 KiB 1 0.045 s 0.046 s 1.02
512 KiB 4 0.047 s 0.069 s 1.47
1024 KiB 8 0.047 s 0.069 s 1.47
2048 KiB 16 0.052 s 0.072 s 1.40
4096 KiB 32 0.079 s 0.075 s 0.96
8192 KiB 64 0.135 s 0.082 s 0.61
16384 KiB 128 0.251 s 0.102 s 0.41
32768 KiB 256 0.464 s 0.145 s 0.31
At +2 ms:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15302
put() at the default window of 16, median of 5 runs
object chunks put() putFast() putFast / put
128 KiB 1 0.007 s 0.008 s 1.18
512 KiB 4 0.009 s 0.013 s 1.43
1024 KiB 8 0.011 s 0.013 s 1.22
2048 KiB 16 0.013 s 0.014 s 1.08
4096 KiB 32 0.021 s 0.020 s 0.93
8192 KiB 64 0.041 s 0.028 s 0.70
16384 KiB 128 0.076 s 0.051 s 0.66
32768 KiB 256 0.153 s 0.089 s 0.58
On loopback:
s215, nats-server 2.15.3, client v2.42.0, nats://127.0.0.1:15315
put() at the default window of 16, median of 5 runs
object chunks put() putFast() putFast / put
128 KiB 1 0.001 s 0.001 s 1.46
512 KiB 4 0.003 s 0.003 s 1.03
1024 KiB 8 0.004 s 0.003 s 0.82
2048 KiB 16 0.006 s 0.005 s 0.80
4096 KiB 32 0.011 s 0.008 s 0.74
8192 KiB 64 0.024 s 0.014 s 0.61
16384 KiB 128 0.047 s 0.025 s 0.53
32768 KiB 256 0.086 s 0.048 s 0.56
- At +20 ms the break-even is near 4 MiB, as the release notes say: the ratio is 0.96 there. From 512 KiB to 2 MiB,
putFast()took one round trip longer, about 0.07 s against 0.05 s. From 8 MiB up it pulled away, to a ratio of 0.31 at 32 MiB. - A single chunk is the exception. At 128 KiB the ratio is 1.02: the only chunk is also the last, so it goes out as the commit, and there is no batch start to wait for.
- At +2 ms the picture is the same, break-even near 4 MiB. On loopback the fast upload wins from 1 MiB, and below that both take a millisecond or so, where the ratio means little.
So the choice can follow the object's size: a fast upload for objects of several MiB and up, put() for small ones when the server is far away. Both methods work on the same bucket handle, as long as the bucket has the flag.
The bucket needs the flag
The server takes a fast-ingest batch only into a stream with allow_batched. flag.php uploads into a bucket created as before, then tries both ways to give a bucket the flag:
<?php
// flag.php: a fast upload into a bucket without the allow_batched flag, then the
// two ways to give a bucket the flag.
// php flag.php <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreConfig;
$client = connect($argv[1]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
$data = random_bytes(1 << 20); // 1 MiB: 8 chunks of 128 KiB
say("\n1. A bucket created as before, without the flag");
$store = freshBucket($js, 'plain', fast: false);
say(' allow_batched: ' . flagOf($js, 'plain'));
try {
$store->putFast('a.bin', $data)->await();
say(' putFast(): stored');
} catch (\Throwable $e) {
say(' putFast(): ' . brief($e));
say(' previous: ' . brief($e->getPrevious()));
}
$info = $store->info('a.bin')->await();
say(' chunks in the stream: ' . chunksIn($client, 'plain')
. ', info(): ' . ($info === null ? 'null' : $info->chunks . ' chunks'));
say("\n2. create() on the same bucket, now with the flag");
try {
$store->create(new ObjectStoreConfig(allowBatched: true))->await();
say(' created');
} catch (\Throwable $e) {
say(' ' . brief($e));
}
say("\n3. enableFastIngest() on the existing bucket");
$store->enableFastIngest()->await();
say(' allow_batched: ' . flagOf($js, 'plain'));
$info = $store->putFast('a.bin', $data)->await();
say(" putFast(): {$info->chunks} chunks, {$info->size} bytes, read back "
. (readBack($store, 'a.bin') === hash('sha256', $data) ? 'identical' : 'DIFFERENT'));
say("\n4. A new bucket with the flag from the start");
$store = freshBucket($js, 'fast', fast: true);
say(' allow_batched: ' . flagOf($js, 'fast'));
$block = substr($data, 0, 65536);
$info = $store->putStreamFast('b.bin', blocks($block, 16))->await();
say(" putStreamFast(): {$info->chunks} chunks, {$info->size} bytes, read back "
. (readBack($store, 'b.bin') === hash('sha256', str_repeat($block, 16))
? 'identical' : 'DIFFERENT'));
$client->disconnect()->await();
s215, nats-server 2.15.3, client v2.42.0
1. A bucket created as before, without the flag
allow_batched: false
putFast(): JetStreamException (err_code 10205): Object Store bucket "plain"
does not allow fast-ingest uploads (batch publish is disabled): create the bucket
with new ObjectStoreConfig(allowBatched: true) (or the option allow_batched), or
call enableFastIngest() on the existing bucket
previous: JetStreamException (err_code 10205): batch publish is disabled
chunks in the stream: 0, info(): null
2. create() on the same bucket, now with the flag
JetStreamException (err_code 10058): stream name already in use with a
different configuration
3. enableFastIngest() on the existing bucket
allow_batched: true
putFast(): 8 chunks, 1048576 bytes, read back identical
4. A new bucket with the flag from the start
allow_batched: true
putStreamFast(): 8 chunks, 1048576 bytes, read back identical
- Without the flag the upload fails at once and stores nothing. The
JetStreamExceptionnames the bucket and both ways to set the flag, and carries the server's own 10205, "batch publish is disabled", as its previous exception. create()cannot add the flag to a bucket that exists. The server refuses a stream with the same name and a different configuration (10058).enableFastIngest()is the way, and the upload works right after it.- A new bucket can have the flag from the start.
ObjectStoreConfigsendsallow_batchedonly when it is true, because a 2.12 server refuses the field whatever its value.
Older servers
older.php runs the same three steps on each server: create a bucket with the flag, give another bucket the flag with enableFastIngest(), and upload into it with putFast():
<?php
// older.php: what the flag and a fast upload do on each server release.
// php older.php <server URL> [<server URL> ...]
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreConfig;
$data = random_bytes(1 << 20); // 1 MiB: 8 chunks of 128 KiB
foreach (array_slice($argv, 1) as $url) {
$client = connect($url);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
foreach (['flagged', 'later'] as $bucket) {
try {
$js->objectStore($bucket)->deleteBucket()->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
}
try {
$js->objectStore('flagged')
->create(new ObjectStoreConfig(allowBatched: true))->await();
say(' create() with the flag: created');
} catch (\Throwable $e) {
say(' create() with the flag: ' . brief($e));
}
say(' allow_batched: ' . flagOf($js, 'flagged'));
$later = freshBucket($js, 'later', fast: false);
try {
$later->enableFastIngest()->await();
say(' enableFastIngest(): done');
} catch (\Throwable $e) {
say(' enableFastIngest(): ' . brief($e));
}
say(' allow_batched: ' . flagOf($js, 'later'));
$start = hrtime(true);
try {
$info = $later->putFast('a.bin', $data)->await();
say(' putFast(): ' . $info->chunks . ' chunks stored, ' . trim(since($start)));
} catch (\Throwable $e) {
say(' putFast(): ' . brief($e));
}
$info = $later->info('a.bin')->await();
say(' chunks in the stream: ' . chunksIn($client, 'later')
. ', info(): ' . ($info === null ? 'null' : $info->chunks . ' chunks'));
echo "\n";
$client->disconnect()->await();
}
s210, nats-server 2.10.29, client v2.42.0
create() with the flag: UnsupportedFeatureException: The "allow_batched" feature
requires NATS server 2.14+, and the server (connected server reports 2.10.29)
ignored the field: stream "OBJ_flagged" exists without it (it may have existed
before this request: inspect it before changing or deleting it)
allow_batched: false
enableFastIngest(): UnsupportedFeatureException: The "allow_batched" feature
requires NATS server 2.14+, and the server (connected server reports 2.10.29)
ignored the field: stream "OBJ_later" exists without it (it may have existed
before this request: inspect it before changing or deleting it)
allow_batched: false
putFast(): UnsupportedFeatureException: Fast-ingest batch publish requires NATS
server 2.14+: the server stored the message as a plain publish (stream
"OBJ_later", seq 1) instead of starting a batch (connected server 2.10.29)
chunks in the stream: 0, info(): null
s211, nats-server 2.11.17, client v2.42.0
create() with the flag: UnsupportedFeatureException: The "allow_batched" feature
requires NATS server 2.14+, and the server (connected server reports 2.11.17)
ignored the field: stream "OBJ_flagged" exists without it (it may have existed
before this request: inspect it before changing or deleting it)
allow_batched: false
enableFastIngest(): UnsupportedFeatureException: The "allow_batched" feature
requires NATS server 2.14+, and the server (connected server reports 2.11.17)
ignored the field: stream "OBJ_later" exists without it (it may have existed
before this request: inspect it before changing or deleting it)
allow_batched: false
putFast(): UnsupportedFeatureException: Fast-ingest batch publish requires NATS
server 2.14+: the server stored the message as a plain publish (stream
"OBJ_later", seq 1) instead of starting a batch (connected server 2.11.17)
chunks in the stream: 0, info(): null
s212, nats-server 2.12.15, client v2.42.0
create() with the flag: UnsupportedFeatureException (err_code 10025): The
"allow_batched" feature requires NATS server 2.14+, but the connected server
reports 2.12.15. (invalid JSON: json: unknown field "allow_batched")
allow_batched: no stream
enableFastIngest(): UnsupportedFeatureException (err_code 10025): The
"allow_batched" feature requires NATS server 2.14+, but the connected server
reports 2.12.15. (invalid JSON: json: unknown field "allow_batched")
allow_batched: false
putFast(): UnsupportedFeatureException: Fast-ingest batch publish requires NATS
server 2.14+: the server stored the message as a plain publish (stream
"OBJ_later", seq 1) instead of starting a batch (connected server 2.12.15)
chunks in the stream: 0, info(): null
s214, nats-server 2.14.10, client v2.42.0
create() with the flag: created
allow_batched: true
enableFastIngest(): done
allow_batched: true
putFast(): 8 chunks stored, 0.005 s
chunks in the stream: 8, info(): 8 chunks
- 2.10 and 2.11 create the stream without the flag, because they do not know the field and drop it. The client sees that and throws an
UnsupportedFeatureException, which also warns that the stream may have existed before the call. 2.12 refuses the field with 10025 and creates nothing. enableFastIngest()fails on all three, and the bucket keepsallow_batchedfalse.- A fast upload leaves nothing behind. A server before 2.14 does not know a batch, so it stored the first chunk as a plain message (sequence 1). The client saw a plain PubAck where a batch should have started, purged that chunk and threw. The stream holds no chunk and there is no object. On 2.14.10 the same three steps worked.
When an upload fails
A failed fast upload ends its batch with settle(), purges every chunk stored under the new object's ID and throws its own error. Three ways to fail, each run for real.
A producer that throws
failing.php stores an object, then overwrites it with putStreamFast() from a producer that throws when it is asked for its 41st block of 64 KiB, after 2.5 MiB:
<?php
// failing.php: an overwrite whose producer fails halfway, on a bucket with the flag.
// php failing.php <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
$client = connect($argv[1]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
$store = freshBucket($js, 'reports', fast: true);
$first = random_bytes(1 << 20); // revision 1: 1 MiB, 8 chunks
$info = $store->putFast('report.bin', $first)->await();
say("revision 1: {$info->chunks} chunks, nuid {$info->nuid}");
// Revision 2 comes from a producer that fails after 40 blocks of 64 KiB (20 chunks).
$sent = 0;
$block = random_bytes(65536);
$producer = function () use (&$sent, $block): ?string {
if (++$sent > 40) {
throw new \RuntimeException('disk read failed at block ' . $sent);
}
return $block;
};
$start = hrtime(true);
try {
$store->putStreamFast('report.bin', $producer)->await();
say('revision 2: stored');
} catch (\Throwable $e) {
say('revision 2: ' . brief($e) . ', after ' . trim(since($start)));
}
$info = $store->info('report.bin')->await();
say("info(): {$info->chunks} chunks, nuid {$info->nuid}");
say('chunks in the stream: ' . chunksIn($client, 'reports'));
say('read back: ' . (readBack($store, 'report.bin') === hash('sha256', $first)
? 'identical to revision 1' : 'DIFFERENT'));
// The same overwrite with a producer that does not fail.
$info = $store->putStreamFast('report.bin', blocks($block, 48))->await();
say("revision 3: {$info->chunks} chunks, nuid {$info->nuid}");
say('chunks in the stream: ' . chunksIn($client, 'reports'));
$client->disconnect()->await();
s215, nats-server 2.15.3, client v2.42.0
revision 1: 8 chunks, nuid ae4e374fea839d6d213bac
revision 2: RuntimeException: disk read failed at block 41, after 0.006 s
info(): 8 chunks, nuid ae4e374fea839d6d213bac
chunks in the stream: 8
read back: identical to revision 1
revision 3: 24 chunks, nuid 8dae1ea954432db506ee7b
chunks in the stream: 24
The upload threw the producer's own RuntimeException. The chunks it had sent are gone, and the object is still revision 1, with the same ID, the same eight chunks and the same bytes, because a fast upload writes the meta record only after the commit. The next overwrite went through, and once it did, revision 1's chunks were purged as usual: 24 chunks for a 3 MiB object.
A producer that pauses
The server abandons a fast-ingest batch that has had no message for its batch timeout, 10 seconds by default, and there is no keep-alive. idle.php streams 2 MiB from producers that pause, on the server whose timeout is two seconds and on a server with the default:
<?php
// idle.php: producers that pause, against the server's batch timeout.
// php idle.php <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use function Amp\delay;
$client = connect($argv[1]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
$store = freshBucket($js, 'slow', fast: true);
$block = random_bytes(65536);
/** 32 blocks of 64 KiB (16 chunks) with a pause of $pause s before the given blocks. */
function pausing(string $block, float $pause, array $before): \Closure
{
$sent = 0;
return function () use (&$sent, $block, $pause, $before): ?string {
if (++$sent > 32) {
return null;
}
if (in_array($sent, $before, true)) {
delay($pause); // the event loop runs on meanwhile
}
return $block;
};
}
$cases = [
'three pauses of 1.5 s' => pausing($block, 1.5, [9, 17, 25]),
'one pause of 3 s' => pausing($block, 3.0, [9]),
'one pause of 11 s' => pausing($block, 11.0, [9]),
];
foreach ($cases as $label => $producer) {
$name = str_replace(' ', '-', $label) . '.bin';
$start = hrtime(true);
try {
$info = $store->putStreamFast($name, $producer)->await();
say(since($start) . " $label: stored, {$info->chunks} chunks");
} catch (\Throwable $e) {
say(since($start) . " $label: " . brief($e));
}
say(' chunks in the stream: ' . chunksIn($client, 'slow'));
}
$client->disconnect()->await();
With the two-second timeout:
idle, nats-server 2.15.3, client v2.42.0
4.514 s three pauses of 1.5 s: stored, 16 chunks
chunks in the stream: 16
3.011 s one pause of 3 s: JetStreamException (err_code 10208): batch publish ID
unknown
chunks in the stream: 16
11.022 s one pause of 11 s: JetStreamException (err_code 10208): batch publish ID
unknown
chunks in the stream: 16
With the default:
s215, nats-server 2.15.3, client v2.42.0
4.513 s three pauses of 1.5 s: stored, 16 chunks
chunks in the stream: 16
3.009 s one pause of 3 s: stored, 16 chunks
chunks in the stream: 32
11.019 s one pause of 11 s: JetStreamException (err_code 10208): batch publish ID
unknown
chunks in the stream: 32
- The timeout counts from the last message, not from the start. Three pauses of 1.5 s, 4.5 s in all, passed on the server with a two-second timeout. One pause of 3 s failed there with 10208, "batch publish ID unknown", and passed on the default server, where a pause of 11 s failed the same way.
- Nothing was left behind. After each failure the stream held only the chunks of the uploads that had succeeded before it.
A producer that reads from a slow source, another network service for instance, should read ahead into a buffer, or use putStream(), which has no batch for the server to abandon.
A server that answers late
hiccup.php streams 4 MiB through the hiccup proxy with an ack timeout of 500 ms. Halfway through, the producer publishes to hiccup, so the proxy holds the server's replies for two seconds. A second connection, straight to the server, counts the bucket's chunks every 50 ms:
<?php
// hiccup.php: a fast upload whose server answers late, through hiccup-proxy.php.
// A second connection, straight to the server, watches the bucket meanwhile.
// php hiccup.php <proxy URL> <server URL>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use function Amp\async;
use function Amp\delay;
$client = connect($argv[1]);
$watcher = connect($argv[2]);
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), ', through ', $argv[1], "\n";
$store = freshBucket($js, 'late', fast: true);
$block = random_bytes(65536);
$sent = 0;
$producer = function () use (&$sent, $block, $client): ?string {
if (++$sent > 64) {
return null; // 4 MiB, 32 chunks
}
if ($sent === 33) {
$client->publish('hiccup', '')->await(); // the proxy holds replies now
}
return $block;
};
$start = hrtime(true);
$watching = true;
$watch = async(function () use (&$watching, $watcher, $start): void {
$last = -1;
while ($watching) {
$count = chunksIn($watcher, 'late');
if ($count !== $last) {
say(since($start) . " the server holds $count chunks of the bucket");
$last = $count;
}
delay(0.05);
}
});
try {
$store->putStreamFast('late.bin', $producer, ackTimeoutMs: 500)->await();
say(since($start) . ' putStreamFast(): stored');
} catch (\Throwable $e) {
say(since($start) . ' putStreamFast(): ' . brief($e));
}
$watching = false;
$watch->await();
$info = $store->info('late.bin')->await();
say(since($start) . ' chunks in the stream: ' . chunksIn($client, 'late')
. ', info(): ' . ($info === null ? 'null' : $info->chunks . ' chunks'));
$client->disconnect()->await();
$watcher->disconnect()->await();
s215, nats-server 2.15.3, client v2.42.0, through nats://127.0.0.1:15330
0.001 s the server holds 0 chunks of the bucket
0.052 s the server holds 32 chunks of the bucket
1.024 s the server holds 0 chunks of the bucket
2.009 s putStreamFast(): TimeoutException: Fast batch 13bcf540f851eed8bd9da24d:
no PubAck for the commit at batch sequence 32 within 500 ms; ack sequence 0
2.045 s chunks in the stream: 0, info(): null
The server had every chunk and the commit after 0.052 s: the upload had in fact succeeded. Only its PubAck was late. The commit's wait ran out after 500 ms and settle()'s after 500 ms more, and at 1.024 s the purge had removed all 32 chunks. The upload threw once the purge's reply came through the proxy. That is what the release notes mean by "up to twice the ack timeout": the purge goes out after the two waits, whether the server answered or not.
The result is clean, if cautious: no object and no orphaned chunks, so the upload can simply be retried. If the server cannot be reached at all, the purge fails too, and the chunks stay under an ID that no meta record names, as after a failed put().
Quality gates
From the 2.42.0 release notes: PHPStan level 8; 4636 unit tests on PHP 8.2 to 8.5, 39 more than in 2.41.0, of which 37 are for the two upload methods; 210 live integration tests against the nats-server 2.12 fixture stack, 25 of them skipped there because they need 2.14, and 206 passing in a second run against 2.14, where nothing may skip. The new live tests read uploads of 0, 1 and 8 chunks back with each method and cover an overwrite, a producer that fails, a bucket without the flag, enableFastIngest() and an older server. All 54 Behat scenarios and all 47 runnable examples pass, every changed line is covered and total coverage is 99.16%. In the review, 22 wrong versions of the new code were tried one at a time, and each turned at least one test red. The developer also ran the fast-ingest live tests against release binaries of nats-server 2.14.10 and 2.15.3.
Get it
The client is free under the BSD-3-Clause license and needs PHP 8.2 or later. The php-nats-jetstream-client software page has the overview, and the source, issues and full changelog are on GitHub. If you run Symfony Messenger on NATS, the symfony-nats-messenger transport is built on this client.