skip to content
szczecin 53.43N 14.55E ./start-project

php-nats-jetstream-client 2.39: fast-ingest batch publishing

(php, nats, release-notes) 22 min read by Bartosz Pachołek

2.39.0 adds fastPublisher(), the fast-ingest half of NATS ADR-50: many messages into one stream without an ack per message. We measured it on a server and a cluster, broke a batch on purpose and ran older servers. Plus 2.38.1's permission fix.

idct/php-nats-jetstream-client 2.39.0, our free NATS and JetStream client for PHP, adds a third way to write into a stream. $js->fastPublisher() is the fast-ingest half of NATS's ADR-50: the client sends many messages without waiting for an acknowledgement per message, and the server sets the pace with an ack every so many messages. It needs nats-server 2.14 or later and a stream created with allow_batched, and nothing else in the client changes.

Our last post on the client covered 2.38.0, so this one also covers 2.38.1, a patch release that makes a pull consumer run or a Key-Value getAll() fail at once when the server refuses it for lack of permission. We ran every example below on PHP 8.5.9 with 2.38.0, 2.38.1 and 2.39.0 from Packagist, against nats-server 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.3 in Docker, plus a three-node 2.15.3 cluster. The output is pasted as it came out.

Why a third way to publish

Until now the client had two ways to put messages into a stream. publish() sends one message and waits for its PubAck. You can keep many of them in flight as futures, but every message still gets its own reply, and the client and the server track each one. ADR-50, the NATS design record behind this release, says it plainly: async publishing "pays a very high cost for managing acknowledgements both in client and server". batch(), added for NATS 2.12, is the other way, and it solves a different problem: an atomic batch is stored whole or not at all, and the server caps it at 1,000 messages by default.

Fast ingest gives up the atomicity and keeps the speed. One batch has a control inbox of its own. The client puts the batch's state into each message's reply subject, the server answers with a flow ack every flow messages, and the client stops to wait only when too many acks are outstanding: one to three, as ADR-50 allows. The server can lower the flow when it is busy, which matters when many publishers write at once. A batch has no size limit, and every message is stored as it arrives.

GitHub release page of php-nats-jetstream-client v2.39.0: the fast-ingest batch publisher fastPublisher() for NATS 2.14+ and the allow_batched stream field

What 2.39.0 adds:

  • $js->fastPublisher(flow: 100, maxOutstandingAcks: 2, continueOnGap: false, ackTimeoutMs: null, onError: null) returns a FastPublisher. One publisher is one batch, used from one fiber.
  • add($subject, $payload, $headers) sends a message at once and returns a FastPubAck with its batchSequence and the highest ackSequence the server has confirmed. The first call waits for the server to start the batch; later calls wait only when too many acks are outstanding.
  • commit() stores a last message and returns the batch's PubAck, with batchId and batchCount. close() ends the batch without one.
  • FastBatchException, a JetStreamException, carries the PubAck a batch ended with, or the batch sequence a notice is about.
  • allow_batched joins the version-gated stream fields: creating a stream with it fails with an UnsupportedFeatureException on a server older than 2.14.

The release notes say the behaviour follows Synadia's Orbit Go jetstreamext.FastPublisher (v0.4.0) and ADR-50 at revision 11.

Upgrading

bash
composer require idct/php-nats-jetstream-client:^2.39

For 2.39.0 there is nothing to change: everything is new API, and publish(), batch() and the Object Store uploads work as before. The one change in behaviour since 2.38.0 comes from 2.38.1, and only for users the server refuses: a pull consumer run (handle()), a directGetBatch(), a Key-Value getAll() and an Object Store list() now throw a PermissionViolationException. That exception is a NatsException, not a JetStreamException, so code that catches only JetStreamException around these calls needs a second catch. The last section shows both versions side by side.

The full record is in the changelog at v2.39.0.

A proof of concept you can run

One Docker Compose project: a standalone server per release, a three-node 2.15.3 cluster, and a 2.15.3 server with two users for the permission demo.

yaml
# A standalone server per release, a 2.15.3 cluster of three, and a server with users.
name: fast-ingest

x-cluster: &cluster
  image: nats:2.15.3-alpine

services:
  s210:
    image: nats:2.10-alpine     # 2.10.29
    command: [-js, -n, s210]
    ports: ["14910:4222"]
  s211:
    image: nats:2.11-alpine     # 2.11.17
    command: [-js, -n, s211]
    ports: ["14911:4222"]
  s212:
    image: nats:2.12-alpine     # 2.12.15
    command: [-js, -n, s212]
    ports: ["14912:4222"]
  s214:
    image: nats:2.14-alpine     # 2.14.10
    command: [-js, -n, s214]
    ports: ["14914:4222"]
  s215:
    image: nats:2.15.3-alpine
    command: [-js, -n, s215]
    ports: ["14915:4222"]

  c1:
    <<: *cluster
    command: [-js, -n, c1, --cluster_name, ingest, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14921:4222"]
  c2:
    <<: *cluster
    command: [-js, -n, c2, --cluster_name, ingest, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14922:4222"]
  c3:
    <<: *cluster
    command: [-js, -n, c3, --cluster_name, ingest, --cluster, "nats://0.0.0.0:6222",
              --routes, "nats://c1:6222,nats://c2:6222,nats://c3:6222"]
    ports: ["14923:4222"]

  perm:
    image: nats:2.15.3-alpine
    command: [-c, /etc/nats/perm.conf]
    volumes: ["./perm.conf:/etc/nats/perm.conf:ro"]
    ports: ["14930:4222"]
text
# perm.conf: an admin, and a worker that may not pull from ORDERS/audit
# and may not read the settings bucket with Direct Get.
server_name: perm
port: 4222

jetstream {}

authorization {
  users = [
    { user: admin, password: demo }
    {
      user: worker, password: demo
      permissions: {
        publish: {
          allow: ["$JS.API.>"]
          deny: [
            "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit",
            "$JS.API.DIRECT.GET.KV_settings",
            "$JS.API.DIRECT.GET.KV_settings.>"
          ]
        }
        subscribe: ["_INBOX.>"]
      }
    }
  ]
}
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.39"
    }
}

Every script loads a few helpers. brief() prints an exception as one line, and say() wraps long lines so they fit here:

php
<?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;

/** 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();
}

/** 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";
}

The commands, in the order of this post. We ran fastingest.php, gaps.php and older.php in a 2.39.0 install, and refused.php in a 2.38.0 install and a 2.38.1 install:

bash
(cd servers && docker compose up -d)
composer install
php fastingest.php nats://127.0.0.1:14915
php fastingest.php nats://127.0.0.1:14921 3
php gaps.php
php older.php
php refused.php

How much faster

fastingest.php writes the same 20,000 small JSON metrics into a fresh stream three times: with publish() awaited one by one, with publish() in windows of 100 futures, and with fastPublisher() at its defaults. It times each run and asks the stream how many messages it holds afterwards:

php
<?php
// fastingest.php: the same messages into one stream three ways, timed.
// Usage: php fastingest.php <server URL> [replicas] [messages]
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\JetStream\JetStreamContext;

use function Amp\Future\await;

/** A small JSON metric, about 40 bytes. */
function payload(int $i): string
{
    $cpu = $i * 7 % 1000 / 10;

    return sprintf('{"host":"web-%02d","cpu":%5.1f,"i":%06d}', $i % 16, $cpu, $i);
}

$url = $argv[1] ?? 'nats://127.0.0.1:14915';
$replicas = (int) ($argv[2] ?? 1);
$count = (int) ($argv[3] ?? 20000);

$client = connect($url);
$js = $client->jetStream();
printf("%s, client %s\n", server($client), clientVersion());
printf("%d messages of %d bytes, ", $count, strlen(payload(1)));
printf("stream with %d replica(s)\n\n", $replicas);

$runs = [
    'publish(), one at a time' => function (JetStreamContext $js, int $count): string {
        for ($i = 1; $i <= $count; $i++) {
            $js->publish('metrics.cpu', payload($i))->await();
        }

        return '';
    },
    'publish(), 100 in flight' => function (JetStreamContext $js, int $count): string {
        for ($i = 1; $i <= $count; $i += 100) {
            $window = [];
            for ($j = $i; $j <= min($i + 99, $count); $j++) {
                $window[] = $js->publish('metrics.cpu', payload($j));
            }
            await($window);
        }

        return '';
    },
    'fastPublisher()' => function (JetStreamContext $js, int $count): string {
        $fast = $js->fastPublisher();       // flow 100, 2 outstanding acks
        $seen = [];
        for ($i = 1; $i < $count; $i++) {
            $seen[$fast->add('metrics.cpu', payload($i))->await()->ackSequence] = true;
        }
        $ack = $fast->commit('metrics.cpu', payload($count))->await();
        $seen = array_keys($seen);
        $first = implode(', ', array_slice($seen, 0, 9));

        return "  commit: batchCount {$ack->batchCount}, stream seq {$ack->seq}\n"
            . "  ackSequence as add() saw it: $first ... " . end($seen);
    },
];

$config = ['allow_batched' => true, 'num_replicas' => $replicas];
foreach ($runs as $label => $run) {
    fresh($js, 'METRICS', ['metrics.>'], $config);
    $start = hrtime(true);
    $extra = $run($js, $count);
    $seconds = (hrtime(true) - $start) / 1e9;
    $stored = $js->getStream('METRICS')->await()->messages();
    printf("%-25s %6.2f s %7.0f msg/s", $label, $seconds, $count / $seconds);
    printf("  stored %d\n", $stored);
    if ($extra !== '') {
        echo $extra, "\n";
    }
}

$client->disconnect()->await();

On the standalone 2.15.3 server:

text
s215, nats-server 2.15.3, client v2.39.0
20000 messages of 40 bytes, stream with 1 replica(s)

publish(), one at a time    3.54 s    5657 msg/s  stored 20000
publish(), 100 in flight    2.75 s    7276 msg/s  stored 20000
fastPublisher()             1.00 s   20077 msg/s  stored 20000
  commit: batchCount 20000, stream seq 20000
  ackSequence as add() saw it: 0, 100, 200, 300, 400, 500, 600, 700, 800 ... 19800

On the cluster, into a stream with three replicas (php fastingest.php nats://127.0.0.1:14921 3):

text
c1, nats-server 2.15.3, client v2.39.0
20000 messages of 40 bytes, stream with 3 replica(s)

publish(), one at a time    6.74 s    2969 msg/s  stored 20000
publish(), 100 in flight    2.96 s    6754 msg/s  stored 20000
fastPublisher()             1.54 s   12973 msg/s  stored 20000
  commit: batchCount 20000, stream seq 20000
  ackSequence as add() saw it: 0, 100, 200, 300, 400, 500, 600, 700, 800 ... 19800

Bar chart of 20,000 messages into one stream: fastPublisher() at 20,077 msg/s against 5,657 and 7,276 for publish() on one server, 12,973 against 2,969 and 6,754 on an R3 cluster

  • About 3.5 times the one-by-one rate on one server, 4.4 times on the cluster. Against 100 publishes in flight, the gain is 2.8 times and 1.9 times. Every run stored all 20,000 messages.
  • Replication costs the waiting publisher most. One by one, every publish waits for the replicated write before its ack comes back, so the rate nearly halved on three replicas. The fast publisher lost about a third.
  • The flow acks are visible. ackSequence moved in steps of 100, the flow we asked for, from the first ack on. ADR-50 lets the server start a batch at a lower flow and raise it; with a single publisher on the stream, ours started at 100.

Take the numbers as a comparison on one machine, not as a benchmark. One PHP process, localhost, Docker, 40-byte payloads and one run each. A second run on the standalone server gave 5,728, 7,227 and 21,931 msg/s, and nats-server 2.14.10 gave 5,570, 7,482 and 19,733. Across a real network every awaited ack costs a round trip, which hits the one-by-one run hardest; we did not measure that here.

When a message is refused: the two gap modes

Fast ingest is not all-or-nothing, so you choose what a lost message, or a message that fails a per-message check, does to the rest of the batch. In gap mode fail, the default, it ends the batch, and every message before it is stored in order. In gap mode ok (continueOnGap: true) the batch goes on, and your onError callback gets the notice.

gaps.php sends a batch of six. The fourth message carries Nats-Expected-Last-Subject-Sequence: 0, "this subject has no message yet", which is false, because the script stored one on that subject before the batch:

php
<?php
// gaps.php: a batch of six whose fourth message fails its Nats-Expected-* check,
// once in gap mode fail (the default) and once in gap mode ok.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\FastBatchException;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14915');
$js = $client->jetStream();
echo server($client), ', client ', clientVersion(), "\n";

// Message 4 says "acct-7 has no message yet", which is false: it fails with 10071.
$batch = [
    ['ledger.acct-1', []],
    ['ledger.acct-2', []],
    ['ledger.acct-3', []],
    ['ledger.acct-7', ['Nats-Expected-Last-Subject-Sequence' => '0']],
    ['ledger.acct-4', []],
    ['ledger.acct-5', []],
];

foreach ([false, true] as $continueOnGap) {
    fresh($js, 'LEDGER', ['ledger.>'], ['allow_batched' => true]);
    $js->publish('ledger.acct-7', 'opened')->await();   // stream seq 1, before the batch

    echo "\ngap mode ", $continueOnGap ? 'ok' : 'fail', "\n";
    $fast = $js->fastPublisher(
        continueOnGap: $continueOnGap,
        onError: function (FastBatchException $e): void {
            say("  onError: message {$e->batchSequence}: " . brief($e));
        },
    );

    try {
        foreach ($batch as $i => [$subject, $headers]) {
            $n = $i + 1;
            if ($n < count($batch)) {
                $ack = $fast->add($subject, "entry $n", $headers)->await();
                echo "  add($n, $subject) returned, ackSequence {$ack->ackSequence}\n";
                continue;
            }
            $ack = $fast->commit($subject, "entry $n", $headers)->await();
            echo "  commit($n, $subject): batchCount {$ack->batchCount}, ",
                "stream seq {$ack->seq}\n";
        }
    } catch (FastBatchException $e) {
        say("  call $n threw " . brief($e));
        echo '  its pubAck: batchCount ', $e->pubAck?->batchCount, ', stream seq ',
            $e->pubAck?->seq, "\n";
    }

    $stored = [];
    $last = $js->getStream('LEDGER')->await()->messages();
    for ($seq = 1; $seq <= $last; $seq++) {
        $message = $js->getStreamMessage('LEDGER', $seq)->await();
        $stored[] = "$seq " . substr($message->subject, 7) . " '$message->payload'";
    }
    say('  stream: ' . implode(', ', $stored));
}

$client->disconnect()->await();
text
s215, nats-server 2.15.3, client v2.39.0

gap mode fail
  add(1, ledger.acct-1) returned, ackSequence 0
  add(2, ledger.acct-2) returned, ackSequence 0
  add(3, ledger.acct-3) returned, ackSequence 0
  add(4, ledger.acct-7) returned, ackSequence 0
  add(5, ledger.acct-4) returned, ackSequence 0
  call 6 threw FastBatchException: Fast batch 07dab03c5c7c759e402586a7 ended at
      batch sequence 3 before its commit: Fast batch 07dab03c5c7c759e402586a7: message 4
      was refused: wrong last sequence: 1
  its pubAck: batchCount 3, stream seq 4
  stream: 1 acct-7 'opened', 2 acct-1 'entry 1', 3 acct-2 'entry 2', 4 acct-3
      'entry 3'

gap mode ok
  add(1, ledger.acct-1) returned, ackSequence 0
  add(2, ledger.acct-2) returned, ackSequence 0
  add(3, ledger.acct-3) returned, ackSequence 0
  add(4, ledger.acct-7) returned, ackSequence 0
  add(5, ledger.acct-4) returned, ackSequence 0
  onError: message 4: FastBatchException (err_code 10071): Fast batch
      1f3801f1ef88bcb5286ecc1f: message 4 was refused: wrong last sequence: 1
  commit(6, ledger.acct-5): batchCount 6, stream seq 6
  stream: 1 acct-7 'opened', 2 acct-1 'entry 1', 3 acct-2 'entry 2', 4 acct-3
      'entry 3', 5 acct-4 'entry 5', 6 acct-5 'entry 6'
  • In gap mode fail, the error came at the commit, not at add(4). add() does not wait for the server unless too many acks are outstanding, so it does not read the server's replies either. Messages 4 and 5 were sent, and the FastBatchException came at the next call that waited. Its pubAck says what happened: the batch ended at batch sequence 3, and stream sequence 4 is the last message stored. Message 5 was sent after the end and is not in the stream. In a long batch, expect the exception at the next stall or at the commit, and trust pubAck->batchCount, not the number of add() calls that returned.
  • In gap mode ok, nothing stopped. onError got message 4 with err_code 10071, "wrong last sequence: 1", in the commit's fiber. The commit reports batchCount 6 while the stream holds five of the six: batchCount is the batch sequence of the commit, not the number of messages stored, as the README warns.

Which mode to pick follows from the data. ADR-50 names both uses: Object Store chunks cannot have gaps, because a gap is a hole in a file, while a publisher of metrics can lose a sample and go on.

Older servers

The publisher never reads the server version from INFO. It sends the first message and lets the reply decide, like the rest of the client since 2.37. older.php shows what that means on each release: first a stream created with allow_batched, then a fast batch into a plain stream without it:

php
<?php
// older.php: allow_batched and a fast batch on every server release.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

foreach ([14910, 14911, 14912, 14914, 14915] as $port) {
    $client = connect("nats://127.0.0.1:$port");
    $js = $client->jetStream();
    echo server($client), "\n";

    // 1. A stream that asks for fast ingest.
    try {
        $js->deleteStream('FI')->await();
    } catch (JetStreamException) {
        // not there
    }
    try {
        $info = $js->createStream('FI', ['fi.>'], ['allow_batched' => true])->await();
        say('  createStream(allow_batched): created, allow_batched '
            . show($info->raw['config']['allow_batched'] ?? null));
    } catch (JetStreamException $e) {
        say('  createStream(allow_batched): ' . brief($e));
    }
    try {
        $js->getStream('FI')->await();
        echo "  stream FI exists now: yes\n";
    } catch (JetStreamException) {
        echo "  stream FI exists now: no\n";
    }

    // 2. A plain stream, without allow_batched, and a fast batch into it.
    fresh($js, 'FI', ['fi.>']);
    try {
        $ack = $js->fastPublisher()->add('fi.x', 'one')->await();
        say("  add() on a plain stream: batchSequence {$ack->batchSequence}");
    } catch (JetStreamException $e) {
        say('  add() on a plain stream: ' . brief($e));
    }
    echo '  messages in FI: ', $js->getStream('FI')->await()->messages(), "\n";

    $client->disconnect()->await();
}
text
s210, nats-server 2.10.29
  createStream(allow_batched): UnsupportedFeatureException: The "allow_batched"
      feature requires NATS server 2.14+, and the server (connected server reports
      2.10.29) ignored the field: stream "FI" exists without it (it may have existed
      before this request: inspect it before changing or deleting it)
  stream FI exists now: yes
  add() on a plain stream: UnsupportedFeatureException: Fast-ingest batch publish
      requires NATS server 2.14+: the server stored the message as a plain publish
      (stream "FI", seq 1) instead of starting a batch (connected server 2.10.29)
  messages in FI: 1
s211, nats-server 2.11.17
  createStream(allow_batched): UnsupportedFeatureException: The "allow_batched"
      feature requires NATS server 2.14+, and the server (connected server reports
      2.11.17) ignored the field: stream "FI" exists without it (it may have existed
      before this request: inspect it before changing or deleting it)
  stream FI exists now: yes
  add() on a plain stream: UnsupportedFeatureException: Fast-ingest batch publish
      requires NATS server 2.14+: the server stored the message as a plain publish
      (stream "FI", seq 1) instead of starting a batch (connected server 2.11.17)
  messages in FI: 1
s212, nats-server 2.12.15
  createStream(allow_batched): 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")
  stream FI exists now: no
  add() on a plain stream: UnsupportedFeatureException: Fast-ingest batch publish
      requires NATS server 2.14+: the server stored the message as a plain publish
      (stream "FI", seq 1) instead of starting a batch (connected server 2.12.15)
  messages in FI: 1
s214, nats-server 2.14.10
  createStream(allow_batched): created, allow_batched true
  stream FI exists now: yes
  add() on a plain stream: JetStreamException (err_code 10205): batch publish is
      disabled
  messages in FI: 0
s215, nats-server 2.15.3
  createStream(allow_batched): created, allow_batched true
  stream FI exists now: yes
  add() on a plain stream: JetStreamException (err_code 10205): batch publish is
      disabled
  messages in FI: 0
  • 2.14.10 and 2.15.3 create the stream with allow_batched, and refuse a fast batch into a plain stream with err_code 10205, storing nothing.
  • 2.12.15 refuses the unknown field, so no stream is created and the client maps the refusal to an UnsupportedFeatureException.
  • 2.10.29 and 2.11.17 ignore the field in their default mode. The client sees that the field is missing from the server's answer and throws, but by then the stream exists without it. The release notes say to check or delete such a stream before you try again; the README's fast-ingest section does not say so yet, which issue #322 tracks.
  • Before 2.14, the first message is stored. A 2.10 to 2.12 server takes the first fast-ingest message for a plain publish and stores it, so add() throws an UnsupportedFeatureException that names the stream and the sequence, and sends nothing more. On an old server you get one stray message and an exception, not a batch stored without its rules.

What is not settled yet

The same issue #322 holds an open question about failures. A stalled add(), one that waits for acks, can fail on a connection error. The publisher stays open, and that call's message is already part of the batch. Another failure that leaves the batch open, an appended message the client could not send, can also be a ConnectionException, and there the message is not in the batch:

Issue 322 of php-nats-jetstream-client: a stalled add() that fails on a connection error leaves its message in the batch, so a ConnectionException alone does not say whether to resend

Until that is settled, the release notes give the rule for the stalled case: its message is already in the batch, so do not send it again, or it is stored twice. A ConnectionException alone does not tell you which case you are in. Two more gaps, both from the README and the issues: an opt-in fast-ingest mode for Object Store uploads is not there yet (issue #321), and the publisher sends no keep-alive pings while your code is idle. The server abandons a batch after 10 seconds without a message, keeps what it stored, and answers the next call with err_code 10208.

We did not lose a message on purpose, and we did not change a stream's leader in the middle of a batch. Both would test the gap mode further; the refused message above goes through the same gap-mode handling in the client.

2.38.1: a refused pull fails at once

When a user may not publish to the subject a call needs, nats-server answers with -ERR 'Permissions Violation for Publish to ...', keeps the connection open, and never answers the call itself. 2.30.0 taught request() to notice, and 2.36.1 did the same for fetchBatch(). Issue #260 named the calls that still waited, and 2.38.1 fixes them: the pull consumer run, PullConsumerIterator::handle(), and the batched Direct Get, which KeyValueBucket::getAll() and ObjectStoreBucket::list() read through.

refused.php uses the server with two users from the compose file. The admin creates a stream with a consumer and two messages, and a bucket with two keys. The worker may not pull from the consumer and may not use Direct Get on the bucket:

php
<?php
// refused.php: a pull consumer run and Key-Value reads by a user who may not make them.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Core\NatsMessage;
use IDCT\NATS\Exception\JetStreamException;
use IDCT\NATS\JetStream\JetStreamContext;
use Revolt\EventLoop;

$url = 'nats://127.0.0.1:14930';

// The admin sets up a stream with a consumer, and a bucket with two keys.
$admin = connect($url, username: 'admin', password: 'demo');
$ajs = $admin->jetStream();
fresh($ajs, 'ORDERS', ['orders.>']);
$ajs->createConsumer('ORDERS', 'audit', 'orders.>')->await();
$ajs->publish('orders.eu.1', 'first')->await();
$ajs->publish('orders.eu.2', 'second')->await();
try {
    $ajs->deleteStream('KV_settings')->await();
} catch (JetStreamException) {
    // first run
}
$ajs->keyValue('settings')->create()->await();
$ajs->keyValue('settings')->put('theme', 'dark')->await();
$ajs->keyValue('settings')->put('lang', 'pl')->await();
echo server($admin), ', client ', clientVersion(), "\n";

// The worker may not pull from ORDERS/audit, nor Direct Get from the bucket.
$js = connect($url, username: 'worker', password: 'demo')->jetStream();

$try = function (string $what, \Closure $call): void {
    $start = hrtime(true);
    try {
        $result = $call();
        say(sprintf('%-28s %s  returned %s', $what, since($start), show($result)));
    } catch (\Throwable $e) {
        say(sprintf('%-28s %s  %s', $what, since($start), brief($e)));
    }
};

$try('pull run, 1 pull, 1 s expiry', fn() => $js->pullConsumer('ORDERS', 'audit')
    ->setBatching(10)
    ->setExpiresMs(1000)
    ->setIterations(1)
    ->handle(fn(NatsMessage $m, JetStreamContext $js) => $js->ack($m)->await())
    ->await());
$try('pull run, no limit', function () use ($js): int {
    $consumer = $js->pullConsumer('ORDERS', 'audit')
        ->setBatching(10)
        ->setExpiresMs(1000);
    // A worker's loop, stopped from outside at 6 s.
    $timer = EventLoop::delay(6, fn() => $consumer->stop());
    try {
        return $consumer
            ->handle(fn(NatsMessage $m, JetStreamContext $js) => $js->ack($m)->await())
            ->await();
    } finally {
        EventLoop::cancel($timer);
    }
});
$try("kv get('theme')", fn() => $js->keyValue('settings')->get('theme')->await());
$try('kv getAll()', fn() => $js->keyValue('settings')->getAll()->await());

With 2.38.0:

text
perm, nats-server 2.15.3, client v2.38.0
pull run, 1 pull, 1 s expiry  2.003 s  returned 0
pull run, no limit            6.003 s  returned 0
kv get('theme')               0.001 s  PermissionViolationException: The server
      refused the request to "$JS.API.DIRECT.GET.KV_settings": Permissions Violation for
      Publish to "$JS.API.DIRECT.GET.KV_settings". No responder received it. Grant this
      connection's user permission to publish to "$JS.API.DIRECT.GET.KV_settings".
kv getAll()                   6.008 s  JetStreamException: Direct Get batch for
      stream "KV_settings" stalled: no progress for 6000 ms (received 0 message(s), no
      end-of-batch marker)

With 2.38.1:

text
perm, nats-server 2.15.3, client v2.38.1
pull run, 1 pull, 1 s expiry  0.001 s  PermissionViolationException: The server
      refused the pull to "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit": Permissions
      Violation for Publish to "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit". No message was
      delivered for it. Grant this connection's user permission to publish to
      "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit".
pull run, no limit            0.001 s  PermissionViolationException: The server
      refused the pull to "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit": Permissions
      Violation for Publish to "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit". No message was
      delivered for it. Grant this connection's user permission to publish to
      "$JS.API.CONSUMER.MSG.NEXT.ORDERS.audit".
kv get('theme')               0.000 s  PermissionViolationException: The server
      refused the request to "$JS.API.DIRECT.GET.KV_settings": Permissions Violation for
      Publish to "$JS.API.DIRECT.GET.KV_settings". No responder received it. Grant this
      connection's user permission to publish to "$JS.API.DIRECT.GET.KV_settings".
kv getAll()                   0.001 s  PermissionViolationException: The server
      refused the Direct Get batch request to "$JS.API.DIRECT.GET.KV_settings":
      Permissions Violation for Publish to "$JS.API.DIRECT.GET.KV_settings". No message
      was delivered for it. Grant this connection's user permission to publish to
      "$JS.API.DIRECT.GET.KV_settings".
  • 2.38.0 hid the refusal. The finite run returned 0 after 2 s, as if the stream were empty, though it holds two messages. The run without a limit, a worker's loop, delivered nothing for 6 s and returned 0 when stopped. getAll() gave up after 6 s with a "stalled" error that says nothing about permissions. Only get(), a plain request, failed at once.
  • 2.38.1 names it. All four calls threw a PermissionViolationException within 2 ms, naming the refused subject and the permission to grant.

The release notes list the limits. The refusal is matched by subject, so an unread refusal of an earlier publish to the same subject also ends the call. A refusal for a subject that the account maps to another one names the mapped subject and is not matched: such a run still pulls on, and such a batch still stalls.

Quality gates

From the 2.39.0 release notes: PHPStan level 8; 4491 unit tests (with data sets) on PHP 8.2 to 8.5, 65 more than in 2.38.1 and all of them for the fast-ingest publisher and allow_batched; 187 live integration tests against the nats-server 2.12 fixture stack, 12 of them skipped there because they need 2.14, and 184 passing in a second run against 2.14, where nothing may skip. In the review, the new FastIngestIntegrationTest also ran against nats-server 2.10.29, 2.11.17, 2.12.15 and 2.14.10. All 54 Behat scenarios and all 47 runnable examples pass, every changed line is covered and total coverage is 99.12%. The change was mutation-tested in CI before the merge: a covered MSI of 92.01% against a 90% floor, with the caveat the release states itself, that 5229 of the 10000 mutants were skipped as too slow and the score does not include them.

For 2.38.1: 4426 unit tests, 32 more than in 2.38.0, and two new test classes that fail on 2.38.0's code in 11 of 14 and 12 of 14 cases.

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.