php-nats-jetstream-client 2.40: a deeper upload window
(php, nats, release-notes) 21 min read by Bartosz Pachołek
2.40.0 lets an Object Store upload keep up to 64 chunks in flight instead of 16. We timed 64 MiB uploads through a proxy that adds a round trip, on nats-server 2.10 to 2.15, and measured what the window costs in memory. Plus 2.39.1's inbox prefix fix.
idct/php-nats-jetstream-client 2.40.0, our free NATS and JetStream client for PHP, lets an Object Store upload keep more chunks in flight. put() and putStream() have always sent an object in windows of 16 chunks and waited for all 16 acknowledgements before sending more. Over a link with a long round trip, that wait sets the speed, not the server. The window is now a setting of the bucket handle, from 1 to 64, and the default stays 16.
Our last post on the client covered 2.39.0, so this one also covers 2.39.1, a patch release that makes every JetStream inbox follow NatsOptions::inboxPrefix. We ran every example below on PHP 8.5.9 with 2.39.0, 2.39.1 and 2.40.0 from Packagist, against nats-server 2.10.29, 2.14.10 and 2.15.3 in Docker, with a small PHP proxy that adds a round trip. The output is pasted as it came out.
Why the window matters
An Object Store object is a stream of chunks, 128 KiB each by default, plus one meta message that names them. Every chunk is a JetStream publish, and every publish gets an acknowledgement. Until 2.40.0 the client published 16 chunks, then waited for all 16 acknowledgements before it published the next 16. On loopback that wait costs next to nothing. Across a network it costs one round trip per window: a 64 MiB object is 512 chunks, so 32 windows, so 32 round trips spent waiting, whatever the server could take.
The release came out of a question. Issue #321 asked whether Object Store 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 was what slowed long round trips down, and issue #328 turned that into this release. A fast-ingest upload is tracked on its own in #327. It would need nats-server 2.14, so on older servers a deeper window is the only way to speed an upload up.

What 2.40.0 adds:
$js->objectStore('assets', 64): the second argument ofobjectStore()is the upload window of that handle, from 1 to 64.new ObjectStoreBucket(..., uploadWindow: 64): the same setting as the new last argument of the constructor.ObjectStoreBucket::DEFAULT_UPLOAD_WINDOW(16) andObjectStoreBucket::MAX_UPLOAD_WINDOW(64), public constants.- A
JetStreamExceptionfor any other value, before anything is sent: "Object Store upload window must be between 1 and 64 chunks, got N".
A handle is cheap, so you can keep the default for most uploads and take a second handle with a deeper window for the large ones.
Upgrading
composer require idct/php-nats-jetstream-client:^2.40
For 2.40.0 there is nothing to change: the argument is optional and its default is the window every earlier release used. Two things are worth knowing before you pass it, and both show up in the runs below. A deeper window costs PHP memory, so check memory_limit before you raise it for put() of large objects. And 2.39 ignores the argument without a word, so require ^2.40 in composer.json when your code sets a window.
2.39.1 changes behaviour only for a connection with a custom inboxPrefix: its JetStream and Key-Value inboxes now start with that prefix, so subscribe grants and account exports that name _INBOX.JS.* or _INBOX.KV.* need <prefix>.> instead. The last section shows it.
The full record is in the changelog at v2.40.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 whose worker user may subscribe only under acc.>.
# A standalone server per release we ran, and a 2.15.3 server whose
# worker user may subscribe only under its own inbox prefix.
name: upload-window
services:
s210:
image: nats:2.10-alpine # 2.10.29
command: [-js, -n, s210]
ports: ["15010:4222"]
s214:
image: nats:2.14-alpine # 2.14.10
command: [-js, -n, s214]
ports: ["15014:4222"]
s215:
image: nats:2.15.3-alpine
command: [-js, -n, s215]
ports: ["15015:4222"]
prefix:
image: nats:2.15.3-alpine
command: [-c, /etc/nats/prefix.conf]
volumes: ["./prefix.conf:/etc/nats/prefix.conf:ro"]
ports: ["15030:4222"]
# prefix.conf: an admin, and a worker who may subscribe only under "acc.>".
server_name: prefix
port: 4222
jetstream {}
authorization {
users = [
{ user: admin, password: demo }
{
user: worker, password: demo
permissions: {
publish: ["$JS.API.>", "$JS.ACK.>", "$JS.FC.>"]
subscribe: ["acc.>"]
}
}
]
}
{
"require": {
"php": "^8.2",
"idct/php-nats-jetstream-client": "^2.40"
}
}
Every script loads a few helpers. windowOf() reads the window a handle will use, and says so when the release has no setting:
<?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\Models\StreamInfo;
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreBucket;
/** 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);
}
/** Deletes the stream if it is there, then creates it. */
function fresh(
JetStreamContext $js, string $name, array $subjects, array $options = [],
): StreamInfo
{
try {
$js->deleteStream($name)->await();
} catch (JetStreamException) {
// first run: nothing to delete
}
return $js->createStream($name, $subjects, $options)->await();
}
/** The upload window a bucket handle will use: 2.39 and older have no setting. */
function windowOf(ObjectStoreBucket $store): string
{
if (!property_exists($store, 'uploadWindow')) {
return '16 (fixed)';
}
return (string) (new \ReflectionProperty($store, 'uploadWindow'))->getValue($store);
}
/** A PHP value as it would read in JSON, enum cases by name. */
function show(mixed $value): string
{
if ($value instanceof \UnitEnum) {
return $value->name;
}
if (is_array($value) && array_is_list($value)) {
return '[' . implode(', ', $value) . ']';
}
return json_encode($value, JSON_UNESCAPED_SLASHES);
}
/** 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";
}
To add a round trip without root rights or tc, delay-proxy.php sits between the client and a server. It holds every block it reads for half the added round trip in each direction, in order, and keeps reading meanwhile, so the link keeps its speed and only answers later. It runs as a separate PHP process, so it does not share the client's event loop:
<?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);
The commands, in the order of this post. We ran the proxies and window.php in a 2.40.0 install, then window.php and refuse.php once more in a 2.39.1 install, and prefix.php in a 2.39.0 install and a 2.39.1 install:
(cd servers && docker compose up -d)
composer install
php delay-proxy.php 15102 127.0.0.1:15015 2 900 &
php delay-proxy.php 15120 127.0.0.1:15015 20 900 &
php delay-proxy.php 15150 127.0.0.1:15015 50 900 &
php delay-proxy.php 15220 127.0.0.1:15010 20 900 &
php delay-proxy.php 15420 127.0.0.1:15014 20 900 &
php -d memory_limit=128M window.php nats://127.0.0.1:15015
php -d memory_limit=128M window.php nats://127.0.0.1:15102
php -d memory_limit=128M window.php nats://127.0.0.1:15120
php -d memory_limit=128M window.php nats://127.0.0.1:15150
php -d memory_limit=128M window.php nats://127.0.0.1:15220 16 64
php -d memory_limit=128M window.php nats://127.0.0.1:15420 16 64
php refuse.php
php prefix.php
How much faster
window.php uploads a 64 MiB object with putStream() and then with put(), three times at each window, and prints the median time. It also prints two memory figures: the 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, so no upload pays for purging the one before. At the end it uploads once more and reads the object back chunk by chunk:
<?php
// window.php: time put() and putStream() of a 64 MiB object at several upload windows.
// php window.php <server URL> [window ...]
declare(strict_types=1);
require __DIR__ . '/lib.php';
$url = $argv[1];
$windows = array_map('intval', array_slice($argv, 2)) ?: [8, 16, 32, 64];
$mib = 64;
$runs = 3;
$client = connect($url);
$js = $client->jetStream();
try {
$js->objectStore('bench')->deleteBucket()->await();
} catch (\Throwable) {
// first run: no bucket yet
}
$js->objectStore('bench')->create()->await();
$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;
foreach (['putStream', 'put'] as $method) {
if ($method === 'put') {
$data = str_repeat($block, $blocks); // put() takes the object whole
}
foreach ($windows as $window) {
$store = $js->objectStore('bench', $window);
$times = $above = $peaks = [];
for ($run = 1; $run <= $runs; $run++) {
$name = "blob-$window-$run";
$sent = 0;
$producer = function () use (&$sent, $block, $blocks): ?string {
return $sent++ < $blocks ? $block : null;
};
gc_collect_cycles();
memory_reset_peak_usage();
$base = memory_get_usage();
$start = hrtime(true);
$info = $method === 'put'
? $store->put($name, $data)->await()
: $store->putStream($name, $producer)->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);
// 2.39 and older take no window: say which one the uploads really used.
$used = windowOf($store) === (string) $window
? ''
: ', window ' . windowOf($store);
printf("%-9s %3d %8.3f s %9.1f MiB %10.1f MiB %d chunks%s\n", $method,
$window, $times[1], max($above), max($peaks), $info->chunks, $used);
}
}
// Upload once more at the last window, read it back chunk by chunk, compare.
// (get() returns the object whole: next to $data it would not fit in 128M.)
$expected = hash('sha256', $data);
$store->put('check', $data)->await();
$hash = hash_init('sha256');
$reader = function (string $chunk) use ($hash): void {
hash_update($hash, $chunk);
};
$js->objectStore('bench')->getToCallback('check', $reader)->await();
echo 'read back at window ', windowOf($store), ': ',
hash_final($hash) === $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.40.0, nats://127.0.0.1:15015
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 8 0.233 s 4.5 MiB 8.8 MiB 512 chunks
putStream 16 0.180 s 9.0 MiB 13.4 MiB 512 chunks
putStream 32 0.169 s 18.0 MiB 22.4 MiB 512 chunks
putStream 64 0.170 s 36.0 MiB 40.5 MiB 512 chunks
put 8 0.212 s 4.5 MiB 72.9 MiB 512 chunks
put 16 0.185 s 9.0 MiB 77.4 MiB 512 chunks
put 32 0.168 s 18.0 MiB 86.4 MiB 512 chunks
put 64 0.164 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical
Through the proxy, with 2 ms added to every round trip:
s215, nats-server 2.15.3, client v2.40.0, nats://127.0.0.1:15102
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 8 0.424 s 4.5 MiB 8.8 MiB 512 chunks
putStream 16 0.314 s 9.0 MiB 13.3 MiB 512 chunks
putStream 32 0.267 s 18.0 MiB 22.4 MiB 512 chunks
putStream 64 0.251 s 36.0 MiB 40.5 MiB 512 chunks
put 8 0.420 s 4.5 MiB 72.9 MiB 512 chunks
put 16 0.302 s 9.0 MiB 77.4 MiB 512 chunks
put 32 0.267 s 18.0 MiB 86.5 MiB 512 chunks
put 64 0.246 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical
With 20 ms:
s215, nats-server 2.15.3, client v2.40.0, nats://127.0.0.1:15120
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 8 1.641 s 4.5 MiB 8.8 MiB 512 chunks
putStream 16 0.908 s 9.0 MiB 13.3 MiB 512 chunks
putStream 32 0.562 s 18.0 MiB 22.4 MiB 512 chunks
putStream 64 0.383 s 36.1 MiB 40.5 MiB 512 chunks
put 8 1.629 s 4.5 MiB 72.9 MiB 512 chunks
put 16 0.924 s 9.0 MiB 77.4 MiB 512 chunks
put 32 0.565 s 18.0 MiB 86.5 MiB 512 chunks
put 64 0.379 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical
With 50 ms:
s215, nats-server 2.15.3, client v2.40.0, nats://127.0.0.1:15150
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 8 3.591 s 4.5 MiB 8.8 MiB 512 chunks
putStream 16 1.922 s 9.0 MiB 13.4 MiB 512 chunks
putStream 32 1.074 s 18.0 MiB 22.4 MiB 512 chunks
putStream 64 0.660 s 36.1 MiB 40.5 MiB 512 chunks
put 8 3.592 s 4.5 MiB 72.9 MiB 512 chunks
put 16 1.906 s 9.0 MiB 77.4 MiB 512 chunks
put 32 1.071 s 18.0 MiB 86.5 MiB 512 chunks
put 64 0.655 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical

- On loopback the window hardly matters. 16, 32 and 64 all land between 0.16 and 0.19 s. Only 8 is clearly slower.
- The longer the round trip, the more a deep window pays. Going from 16 to 64 cut
putStream()from 0.314 s to 0.251 s at +2 ms, from 0.908 s to 0.383 s at +20 ms and from 1.922 s to 0.660 s at +50 ms.put()moved the same way. - The arithmetic explains most of it. 512 chunks at window 16 wait 32 times, at window 64 eight times. At +50 ms that is 1.6 s and 0.4 s of waiting. Add the loopback time of about 0.17 s and you get 1.78 s and 0.57 s, against 1.922 s and 0.660 s measured: the waits are most of the story, not all of it. Every doubling of the window halves the waits, so the gain from 32 to 64 is smaller than from 8 to 16.
- Memory grows with the window, exactly. The peak above the start is 4.5 MiB at window 8 and doubles with every doubling: about 0.56 MiB per chunk in flight, 4.5 times the chunk size, as the release notes say. For
put()it comes on top of the object, whichput()holds whole: the process peaked at 104.5 MiB at window 64. Every run stayed undermemory_limit128M.
One more thing came out of the memory limit. Our first version of the script read the object back with get() while it still held the 64 MiB string for put(), and PHP stopped with "Allowed memory size of 134217728 bytes exhausted" inside ObjectStoreBucket. get() returns the object whole, so it needs another copy's worth of memory. The script now reads back with getToCallback(), one chunk at a time, and every read-back came out identical.
The window is a client-side setting, so the server's release should not matter. It did not. With 20 ms added, 2.10.29, a server with no fast-ingest upload at all:
s210, nats-server 2.10.29, client v2.40.0, nats://127.0.0.1:15220
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.950 s 9.0 MiB 13.3 MiB 512 chunks
putStream 64 0.392 s 36.1 MiB 40.5 MiB 512 chunks
put 16 0.923 s 9.0 MiB 77.4 MiB 512 chunks
put 64 0.381 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical
And 2.14.10, the release the README's table was measured on:
s214, nats-server 2.14.10, client v2.40.0, nats://127.0.0.1:15420
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.944 s 9.0 MiB 13.3 MiB 512 chunks
putStream 64 0.372 s 36.1 MiB 40.5 MiB 512 chunks
put 16 0.915 s 9.0 MiB 77.4 MiB 512 chunks
put 64 0.387 s 36.0 MiB 104.5 MiB 512 chunks
read back at window 64: identical
Our numbers sit close to the README's: it gives 0.950 s and 0.348 s for putStream() at +20 ms on 2.14.10, and a whole-process peak of 78.2 MiB and 105.3 MiB for put(). Take all of them as a comparison on one machine, not a benchmark: one PHP process, localhost and Docker, an added delay instead of a real network, and three runs per point. We did not measure TLS, a replicated stream or CPU use, and neither did the release.
A lesson from the proxy itself: our first version did not set TCP_NODELAY, and a +20 ms run with it took 2.168 s at window 16, against 0.908 s above. Nagle's algorithm on the proxy's sockets held back small writes, the acknowledgements among them. The client sets TCP_NODELAY on its own socket; anything you put between it and the server should do the same.
What 2.39 does with the same script
The same window.php in the 2.39.1 install, through the +20 ms proxy, asking for windows 16 and 64:
s215, nats-server 2.15.3, client v2.39.1, nats://127.0.0.1:15120
64 MiB, 128 KiB chunks, median of 3 runs, memory_limit 128M
method window time above start process peak
putStream 16 0.938 s 9.0 MiB 13.3 MiB 512 chunks, window 16 (fixed)
putStream 64 0.943 s 9.0 MiB 13.3 MiB 512 chunks, window 16 (fixed)
put 16 0.944 s 9.0 MiB 77.3 MiB 512 chunks, window 16 (fixed)
put 64 0.951 s 9.0 MiB 77.4 MiB 512 chunks, window 16 (fixed)
read back at window 16 (fixed): identical
PHP lets you pass more arguments to a method than it declares, so objectStore('bench', 64) on 2.39.1 returns a handle with the fixed window of 16 and says nothing. The times show it: 64 ran as slowly as 16. That is why composer.json should require ^2.40 once your code sets a window.
refuse.php asks for windows inside and outside the range, through objectStore() and through the constructor's named argument:
<?php
// refuse.php: upload windows inside and outside 1 to 64, asked for in both ways.
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NATS\JetStream\ObjectStore\ObjectStoreBucket;
$client = connect('nats://127.0.0.1:15015');
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";
foreach ([0, 1, 64, 65] as $window) {
try {
$store = $js->objectStore('assets', $window);
say(sprintf("objectStore('assets', %d): a handle, window %s",
$window, windowOf($store)));
} catch (\Throwable $e) {
say(sprintf("objectStore('assets', %d): %s", $window, brief($e)));
}
}
try {
$store = new ObjectStoreBucket($client, $js, 'assets', uploadWindow: 128);
say('new ObjectStoreBucket(..., uploadWindow: 128): window ' . windowOf($store));
} catch (\Throwable $e) {
say('new ObjectStoreBucket(..., uploadWindow: 128): ' . brief($e));
}
$client->disconnect()->await();
With 2.40.0:
s215, nats-server 2.15.3, client v2.40.0
objectStore('assets', 0): JetStreamException: Object Store upload window must be
between 1 and 64 chunks, got 0
objectStore('assets', 1): a handle, window 1
objectStore('assets', 64): a handle, window 64
objectStore('assets', 65): JetStreamException: Object Store upload window must be
between 1 and 64 chunks, got 65
new ObjectStoreBucket(..., uploadWindow: 128): JetStreamException: Object Store
upload window must be between 1 and 64 chunks, got 128
With 2.39.1:
s215, nats-server 2.15.3, client v2.39.1
objectStore('assets', 0): a handle, window 16 (fixed)
objectStore('assets', 1): a handle, window 16 (fixed)
objectStore('assets', 64): a handle, window 16 (fixed)
objectStore('assets', 65): a handle, window 16 (fixed)
new ObjectStoreBucket(..., uploadWindow: 128): Error: Unknown named parameter
$uploadWindow
2.40.0 refuses 0, 65 and 128 when the handle is made, before any upload starts, and accepts both ends of the range. 2.39.1 takes every value through objectStore() and ignores it, while the named argument fails at once with PHP's own Error, because the parameter does not exist there.
One gap is still open, and the release notes name it. In the review, the default of objectStore() was changed to 64 and then to 1, and the unit suite stayed green both times: nothing pins it yet. The constructor's default is pinned. A test for the other one is tracked in issue #333.
2.39.1: every inbox follows inboxPrefix
NatsOptions::inboxPrefix sets the prefix of the inboxes a client subscribes to. request() always used it, but nine places in JetStream and Key-Value built their own inboxes on a fixed _INBOX. prefix: the fetch, the pull consumer, the batched Direct Get, push and ordered consumers, watches, and the Key-Value keys() and history(). A user who may subscribe only under its own prefix could not use any of them. 2.39.1 gives all of them the connection's prefix, and with the default prefix no subject changes.
prefix.php uses the third server from the compose file. The admin creates a stream with two consumers and two messages, and a bucket with two keys, one of them written twice. The worker connects with inboxPrefix: 'acc' and may subscribe only under acc.>:
<?php
// prefix.php: JetStream and KV reads by a user who may subscribe under "acc.>" only.
declare(strict_types=1);
require __DIR__ . '/lib.php';
use Amp\CancelledException;
use Amp\TimeoutCancellation;
use IDCT\NATS\Core\NatsMessage;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\JetStreamContext;
use IDCT\NATS\JetStream\KeyValue\KeyValueEntry;
use IDCT\NATS\JetStream\KeyValue\KeyWatchOptions;
$url = 'nats://127.0.0.1:15030';
// The admin sets up a stream with two consumers, and a bucket with two keys.
$admin = connect($url, username: 'admin', password: 'demo');
$ajs = $admin->jetStream();
fresh($ajs, 'ORDERS', ['orders.>'], ['allow_direct' => true]);
$ajs->createConsumer('ORDERS', 'fetcher', 'orders.>')->await();
$ajs->createConsumer('ORDERS', 'runner', 'orders.>')->await();
$ajs->publish('orders.eu.1', 'first')->await();
$ajs->publish('orders.eu.2', 'second')->await();
try {
$ajs->keyValue('settings')->deleteBucket()->await();
} catch (JetStreamException) {
// first run
}
$kv = $ajs->keyValue('settings');
$kv->create(['max_msgs_per_subject' => 5])->await();
$kv->put('theme', 'light')->await();
$kv->put('theme', 'dark')->await();
$kv->put('lang', 'pl')->await();
echo server($admin), ', client ', clientVersion(), "\n";
// The worker connects with inboxPrefix "acc", the only place it may subscribe.
$worker = connect($url, username: 'worker', password: 'demo', inboxPrefix: 'acc');
$js = $worker->jetStream();
$try = function (string $what, \Closure $call): void {
$start = hrtime(true);
try {
$result = $call();
say(sprintf('%-22s %s %s', $what, since($start), $result));
} catch (\Throwable $e) {
say(sprintf('%-22s %s %s', $what, since($start), brief($e)));
}
};
$try('fetchBatch()', fn() => count(
$js->fetchBatch('ORDERS', 'fetcher', 10, 1000)->await(),
) . ' messages');
$try('pull run, 1 pull', fn() => $js->pullConsumer('ORDERS', 'runner')
->setBatching(10)
->setExpiresMs(1000)
->setIterations(1)
->handle(fn(NatsMessage $m, JetStreamContext $js) => $js->ack($m)->await())
->await() . ' messages');
$try('directGetBatch()', fn() => count(
$js->directGetBatch('ORDERS', ['seq' => 1, 'batch' => 10])->await(),
) . ' messages');
$try('kv keys()', fn() => show($js->keyValue('settings')->keys(2.0)->await()));
$try("kv history('theme')", fn() => count(
$js->keyValue('settings')->history('theme', 2.0)->await(),
) . ' entries');
$try('kv watch(), 1 s', function () use ($js, $worker): string {
$seen = [];
$sid = $js->keyValue('settings')->watch(
function (KeyValueEntry $entry) use (&$seen): void {
$seen[] = $entry->key;
},
'>',
new KeyWatchOptions(),
)->await();
// A watch delivers while the application reads: one second of processIncoming().
$until = hrtime(true) + 1_000_000_000;
while (hrtime(true) < $until) {
try {
$worker->processIncoming(new TimeoutCancellation(0.25))->await();
} catch (CancelledException) {
// nothing came in this quarter of a second
}
}
$js->stopOrderedConsumer($sid)->await();
return count($seen) . ' entries ' . show($seen);
});
With 2.39.0:
prefix, nats-server 2.15.3, client v2.39.0
fetchBatch() 0.001 s ConnectionException: JetStream pull fetch failed:
the server rejected its reply-inbox subscription
"_INBOX.JS.FETCH.8980b21a8ed732896f7835ba": 'Permissions Violation for
Subscription to "_INBOX.JS.FETCH.8980b21a8ed732896f7835ba"'
pull run, 1 pull 0.003 s JetStreamException: Pull consumer reply inbox
"_INBOX.JS.PULL.55264232dc0597f80bf283a4.*" was rejected by server permissions:
'Permissions Violation for Subscription to
"_INBOX.JS.PULL.55264232dc0597f80bf283a4.*"'. Grant the account subscribe
permission for the pull reply-inbox wildcard "_INBOX.JS.PULL.>" (or the configured
inbox prefix) to use pull consumers.
directGetBatch() 0.000 s ConnectionException: Direct Get batch for stream
"ORDERS" failed: the server rejected its reply-inbox subscription
"_INBOX.JS.DGET.bb0b5b3089439383811495a0": 'Permissions Violation for Subscription
to "_INBOX.JS.DGET.bb0b5b3089439383811495a0"'
kv keys() 2.010 s JetStreamException: Key enumeration stalled: no
progress for 2.000 s (collected 0 key(s), replay not caught up)
kv history('theme') 2.005 s JetStreamException: Key history for "theme"
stalled: no progress for 2.000 s (collected 0 revision(s), replay not caught up)
kv watch(), 1 s 1.005 s 0 entries []
With 2.39.1:
prefix, nats-server 2.15.3, client v2.39.1
fetchBatch() 1.002 s 2 messages
pull run, 1 pull 1.003 s 2 messages
directGetBatch() 0.001 s 2 messages
kv keys() 0.002 s [theme, lang]
kv history('theme') 0.001 s 2 entries
kv watch(), 1 s 1.244 s 2 entries [theme, lang]
- On 2.39.0 nothing worked. The fetch, the pull run and the batched Direct Get failed at once, each naming an
_INBOX.subject the worker never asked for.keys()andhistory()waited out the two-second progress timeout we gave them and reported a stall. The watch received nothing and raised nothing, the hardest failure of the six to notice. - On 2.39.1 all six worked. The fetch and the pull run took a second because they asked for ten messages and waited out their one-second expiry for the rest; the stream holds two.
If your grants name the old subjects, change them before you upgrade: grant or export <prefix>.>. The release notes warn that <prefix>.*.* is not enough. It covers the request inbox, but the JetStream inboxes have four or five tokens. The same release simplifies account imports: one stream export of <prefix>.> per importing account replaces the four _INBOX.* exports, which every client of the library shared.
Quality gates
From the 2.40.0 release notes: PHPStan level 8; 4532 unit tests on PHP 8.2 to 8.5, 19 more than in 2.39.1, of which 16 are for the upload window and 3 are guard tests for the batched Direct Get (#323, tests only); 195 live integration tests against the nats-server 2.12 fixture stack, 12 of them skipped there because they need 2.14, and 192 passing in a second run against 2.14, where nothing may skip. The new live test uploads with put() and putStream() at window 64 across more than two windows and reads both objects back byte for byte. All 54 Behat scenarios and all 47 runnable examples pass, and every changed line is covered. In the review, 15 wrong versions of the change were put into the code one at a time and 12 of them turned the tests red; of the other three, one was checked by reading and two are the default gap of #333.
For 2.39.1: 4513 unit tests, 22 more than in 2.39.0, and seven new live tests that connect as a user who may subscribe only under acc.>. In the review they also ran against nats-server 2.10.29 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.