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

php-nats-jetstream-client 2.36: walk a subject by sequence

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

2.36.0 adds getNextMessageForSubject(): read a NATS stream one subject at a time, by sequence, with no consumer and no allow_direct. We ran it on five server versions and on a replicated stream whose leader stepped down mid-walk.

idct/php-nats-jetstream-client 2.36.0 is out, and it adds one call: getNextMessageForSubject(). It reads the first message stored on a subject at or after a stream sequence, and it tells you that message's sequence, so you can ask again from the next one and walk a single subject through a stream. It goes through the regular $JS.API.STREAM.MSG.GET API that the stream leader serves, so the stream needs no allow_direct, and nothing is created on the server: no consumer, no state to clean up.

Our last post on the client covered 2.35.0, and 2.36.0 is the only release since. We ran every example below on PHP 8.5.9 with 2.36.0 from Packagist and, for the comparison, 2.35.0, against nats-server 2.10.29, 2.11.17, 2.12.15, 2.14.10 and 2.15.1 in Docker. The release notes name one path that was not run live, clustered or replicated streams, so we also built a three-node cluster, walked a stream with three replicas and made its leader step down in the middle of the walk. The output is pasted as it came out.

Upgrading

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

Existing calls need no change: getStreamMessage() and getLastMessageForSubject() return what they returned before. Three things to know before you use the new call:

  • A 404 is not always the end of a walk. The end of a subject answers 404 with err_code 10037, "no message found". A stream that does not exist answers 404 too, with err_code 10059. Tell them apart with getErrCode(). The README's own walk snippet and examples/stream-message-get.php end on any 404; issue #302 is open to correct them, and we show the difference below.
  • The client does not check the server version. It does not need to: all five servers we ran answered the same way.
  • A replicated stream can answer 503 for a moment. While its leader changes, the call fails with err_code 10008. This is not in the release notes; we met it in the cluster run below.

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

Reading one subject before 2.36

Take a stream ORDERS on orders.> that stores the events of every order as they happen: orders.1001.created, orders.1002.created, orders.1001.paid and so on, interleaved. A support tool wants the history of order 1002, in order, and nothing else. On a stream without allow_direct, 2.35.0 gave you three ways to read stored messages, and none of them fits:

  • getLastMessageForSubject() returns only the last message, and only for a concrete subject.
  • The Direct Get calls read by subject, but only on a stream with allow_direct set.
  • getStreamMessage() reads by sequence, so you read every message of the stream and keep the ones you want.

The fourth way is a consumer filtered on orders.1002.>, which we come back to below. before.php asks the installed version for the first three, then sends the server's own request by hand:

php
<?php
// before.php: how the installed version reads the events of one order.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use Composer\InstalledVersions;
use IDCT\NATS\Exception\JetStreamException;

$client = connect('nats://127.0.0.1:14614');
$js = $client->jetStream();
orders($js); // nine events, no allow_direct

$version = InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client');
echo "php-nats-jetstream-client $version\n";
printf("getNextMessageForSubject(): %s\n",
    method_exists($js, 'getNextMessageForSubject') ? 'yes' : 'no');

echo "1. getLastMessageForSubject() on orders.1002.>:\n";
try {
    $js->getLastMessageForSubject('ORDERS', 'orders.1002.>')->await();
} catch (JetStreamException $e) {
    line('   refused: ' . describe($e));
}

echo "2. directGetLastMessageForSubject() on a stream without allow_direct:\n";
try {
    $js->directGetLastMessageForSubject('ORDERS', 'orders.1002.delivered')->await();
} catch (JetStreamException $e) {
    line('   ' . describe($e));
}

echo "3. getStreamMessage() for every sequence, keeping order 1002:\n";
$requests = 0;
foreach (range(1, count(EVENTS)) as $seq) {
    $message = $js->getStreamMessage('ORDERS', $seq)->await();
    $requests++;
    if (str_starts_with($message->subject, 'orders.1002.')) {
        printf("   %2d %s\n", $seq, $message->subject);
    }
}
echo "   $requests requests for 4 events\n";

echo "4. The server's own next_by_subj, as a raw request:\n";
$reply = $client->request('$JS.API.STREAM.MSG.GET.ORDERS',
    json_encode(['next_by_subj' => 'orders.1002.>', 'seq' => 3]))->await();
$stored = json_decode($reply->payload, true)['message'];
printf("   %2d %s\n", $stored['seq'], $stored['subject']);

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

With 2.35.0:

text
Connected to nats-2-14, nats-server 2.14.10
php-nats-jetstream-client v2.35.0
getNextMessageForSubject(): no
1. getLastMessageForSubject() on orders.1002.>:
   refused: 0, err_code -: getLastMessageForSubject requires a concrete (non-wildcard)
     subject
2. directGetLastMessageForSubject() on a stream without allow_direct:
   503, err_code -: JetStream Direct Get is unavailable on stream ORDERS (enable
     allow_direct on the stream, or use a server that supports Direct Get)
3. getStreamMessage() for every sequence, keeping order 1002:
    2 orders.1002.created
    5 orders.1002.paid
    8 orders.1002.shipped
    9 orders.1002.delivered
   9 requests for 4 events
4. The server's own next_by_subj, as a raw request:
    5 orders.1002.paid

With 2.36.0, only the version and the new method differ:

text
Connected to nats-2-14, nats-server 2.14.10
php-nats-jetstream-client v2.36.0
getNextMessageForSubject(): yes
1. getLastMessageForSubject() on orders.1002.>:
   refused: 0, err_code -: getLastMessageForSubject requires a concrete (non-wildcard)
     subject
2. directGetLastMessageForSubject() on a stream without allow_direct:
   503, err_code -: JetStream Direct Get is unavailable on stream ORDERS (enable
     allow_direct on the stream, or use a server that supports Direct Get)
3. getStreamMessage() for every sequence, keeping order 1002:
    2 orders.1002.created
    5 orders.1002.paid
    8 orders.1002.shipped
    9 orders.1002.delivered
   9 requests for 4 events
4. The server's own next_by_subj, as a raw request:
    5 orders.1002.paid

Step 4 is the point. nats-server answers next_by_subj on every version we tried, 2.10 included, and 2.35.0 could reach it with a raw request and a json_decode(). What 2.36.0 adds is the typed call, a result that carries the sequence and the store time, and two checks before anything is sent. The scan in step 3 needed nine requests for four events here; on a real stream it needs one per message stored.

GitHub release page of php-nats-jetstream-client v2.36.0: getNextMessageForSubject() walks a subject by stream sequence, on any stream

A proof of concept you can run

Five standalone servers, one per version, and a three-node cluster for the replicated stream:

yaml
services:
  nats-2-10:
    image: nats:2.10-alpine
    command: ["-js", "-n", "nats-2-10"]
    ports: ["14610:4222"]
  nats-2-11:
    image: nats:2.11-alpine
    command: ["-js", "-n", "nats-2-11"]
    ports: ["14611:4222"]
  nats-2-12:
    image: nats:2.12-alpine
    command: ["-js", "-n", "nats-2-12"]
    ports: ["14612:4222"]
  nats-2-14:
    image: nats:2.14-alpine
    command: ["-js", "-n", "nats-2-14"]
    ports: ["14614:4222"]
  nats-2-15:
    image: nats:2.15-alpine
    command: ["-js", "-n", "nats-2-15"]
    ports: ["14615:4222"]
  # A three-node cluster for a replicated stream.
  c1:
    image: nats:2.14-alpine
    command: ["-js", "-n", "c1", "--cluster_name", "walk", "--cluster",
      "nats://0.0.0.0:6222", "--routes", "nats://c2:6222,nats://c3:6222"]
    ports: ["14621:4222"]
  c2:
    image: nats:2.14-alpine
    command: ["-js", "-n", "c2", "--cluster_name", "walk", "--cluster",
      "nats://0.0.0.0:6222", "--routes", "nats://c1:6222,nats://c3:6222"]
    ports: ["14622:4222"]
  c3:
    image: nats:2.14-alpine
    command: ["-js", "-n", "c3", "--cluster_name", "walk", "--cluster",
      "nats://0.0.0.0:6222", "--routes", "nats://c1:6222,nats://c2:6222"]
    ports: ["14623:4222"]
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.36"
    }
}

Every script loads a few shared helpers. orders() creates a fresh ORDERS stream without allow_direct and publishes the nine events of three orders, and walk() is the loop the release describes: ask, keep the message, ask again from its sequence plus one, and stop at err_code 10037.

php
<?php
// lib.php: the helpers every script here shares.
declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

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\StoredMessage;

/** The events of three orders, interleaved as they would arrive. */
const EVENTS = [
    ['orders.1001.created', '{"total":120}'],
    ['orders.1002.created', '{"total":40}'],
    ['orders.1001.paid', '{"amount":120}'],
    ['orders.1003.created', '{"total":75}'],
    ['orders.1002.paid', '{"amount":40}'],
    ['orders.1001.shipped', '{"carrier":"dpd"}'],
    ['orders.1003.cancelled', '{"reason":"customer"}'],
    ['orders.1002.shipped', '{"carrier":"ups"}'],
    ['orders.1002.delivered', '{}'],
];

function connect(string $url): NatsClient
{
    $client = new NatsClient(new NatsOptions(servers: [$url]));
    $client->connect()->await();
    $info = $client->serverInfo();
    printf("Connected to %s, nats-server %s\n", $info?->serverName, $info?->version);

    return $client;
}

/** A fresh ORDERS stream, without allow_direct, holding EVENTS. */
function orders(JetStreamContext $js, array $options = []): void
{
    try {
        $js->deleteStream('ORDERS')->await();
    } catch (JetStreamException) {
        // first run: nothing to delete
    }
    $js->createStream('ORDERS', ['orders.>'], $options)->await();
    foreach (EVENTS as [$subject, $payload]) {
        $js->publish($subject, $payload)->await();
    }
}

/** Every message on $subject at or after $from, oldest first: one request per message. */
function walk(JetStreamContext $js, string $subject, int $from = 0): array
{
    $found = [];
    try {
        while (true) {
            $stored = $js->getNextMessageForSubject('ORDERS', $subject, $from)->await();
            $found[] = $stored;
            $from = $stored->sequence + 1;
        }
    } catch (JetStreamException $e) {
        if ($e->getErrCode() !== 10037) { // 10037: no message found, the end of the walk
            throw $e;
        }
    }

    return $found;
}

/** "5 orders.1002.paid {"amount":40}" for each message. */
function show(StoredMessage ...$messages): void
{
    foreach ($messages as $m) {
        printf("   %2d %-22s %s\n", $m->sequence, $m->subject, $m->payload);
    }
}

function describe(JetStreamException $e): string
{
    return sprintf('%d, err_code %s: %s', $e->getCode(), $e->getErrCode() ?? '-',
        $e->getMessage());
}

/** Prints $text wrapped at 86 columns, with the next lines indented. */
function line(string $text, string $indent = '     '): void
{
    echo wordwrap($text, 86, "\n" . $indent), PHP_EOL;
}

The commands, in the order of this post. before.php runs once in a 2.35.0 install and once in a 2.36.0 install; the rest need 2.36.0.

bash
docker compose up -d
composer install
php before.php
php walk.php
php errors.php
php cost.php
for p in 14610 14611 14612 14614 14615; do php servers.php nats://127.0.0.1:$p; done
php cluster.php

Walking one order

walk.php reads the history of order 1002 from a stream with no consumer and no Direct Get, then looks at the parts of the call that are easy to get wrong:

php
<?php
// walk.php: replay the events of one order, with no consumer and no allow_direct.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

$client = connect('nats://127.0.0.1:14614');
$js = $client->jetStream();
orders($js);
$info = $js->getStream('ORDERS')->await()->raw;
printf("ORDERS: %d messages, allow_direct %s, %d consumers\n", $info['state']['messages'],
    json_encode($info['config']['allow_direct'] ?? false),
    $info['state']['consumer_count']);

echo "1. Order 1002, from the start:\n";
show(...walk($js, 'orders.1002.>'));

echo "2. The start sequence counts:\n";
foreach ([4, 5, 6] as $start) {
    $next = $js->getNextMessageForSubject('ORDERS', 'orders.1002.>', $start)->await();
    printf("   from %d: %d %s\n", $start, $next->sequence, $next->subject);
}

echo "3. A wildcard in the middle, every shipment:\n";
show(...walk($js, 'orders.*.shipped'));

echo "4. The walk reads what is stored at each step:\n";
$all = [];
$from = 0;
try {
    while (true) {
        $stored = $js->getNextMessageForSubject('ORDERS', 'orders.1002.>', $from)
            ->await();
        $all[] = $stored;
        $from = $stored->sequence + 1;
        if (count($all) === 2) { // a refund comes in while we are reading
            $js->publish('orders.1002.refunded', '{"amount":40}',
                ['X-Source' => 'support'], msgId: 'refund-1002')->await();
        }
    }
} catch (JetStreamException $e) {
    if ($e->getErrCode() !== 10037) {
        throw $e;
    }
}
show(...$all);
printf("   %d events, the refund published after step 2 included\n", count($all));

echo "5. One StoredMessage in full:\n";
$refund = end($all);
printf("   subject    %s\n   sequence   %d\n   time       %s\n   payload    %s\n",
    $refund->subject, $refund->sequence, $refund->time, $refund->payload);
printf("   rawHeaders %s\n", json_encode($refund->rawHeaders, JSON_UNESCAPED_SLASHES));
$time = new DateTimeImmutable($refund->time);
printf("   as a PHP date: %s\n", $time->format('Y-m-d H:i:s.u T'));

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
ORDERS: 9 messages, allow_direct false, 0 consumers
1. Order 1002, from the start:
    2 orders.1002.created    {"total":40}
    5 orders.1002.paid       {"amount":40}
    8 orders.1002.shipped    {"carrier":"ups"}
    9 orders.1002.delivered  {}
2. The start sequence counts:
   from 4: 5 orders.1002.paid
   from 5: 5 orders.1002.paid
   from 6: 8 orders.1002.shipped
3. A wildcard in the middle, every shipment:
    6 orders.1001.shipped    {"carrier":"dpd"}
    8 orders.1002.shipped    {"carrier":"ups"}
4. The walk reads what is stored at each step:
    2 orders.1002.created    {"total":40}
    5 orders.1002.paid       {"amount":40}
    8 orders.1002.shipped    {"carrier":"ups"}
    9 orders.1002.delivered  {}
   10 orders.1002.refunded   {"amount":40}
   5 events, the refund published after step 2 included
5. One StoredMessage in full:
   subject    orders.1002.refunded
   sequence   10
   time       2026-11-28T21:43:37.011361151Z
   payload    {"amount":40}
   rawHeaders "NATS/1.0\r\nX-Source:support\r\nNats-Msg-Id:refund-1002\r\n\r\n"
   as a PHP date: 2026-11-28 21:43:37.011361 Z
  • The sequence is what makes the walk work. Each answer carries the stream sequence of the message, 2, 5, 8 and 9 here, and the next request starts one past it. The whole state of the walk is one integer in your code, so you can stop, store it and carry on later from the same place.
  • The start sequence counts. Asking from 5 returns the message at 5 itself; asking from 4 or 6 returns the next one on the subject. Forget the + 1 and the walk returns the same message forever.
  • The wildcard can sit anywhere. orders.*.shipped returns every shipment across all orders. getLastMessageForSubject() refuses wildcards, as step 1 of before.php showed; this call accepts them.
  • A walk is not a snapshot. The refund was published after the second step and the walk returned it at sequence 10, because every step reads what the stream holds at that moment. If you need a fixed end, read the stream's last sequence first and stop there.
  • time is a string, as the server sent it, with nanoseconds. DateTimeImmutable parses it and keeps the microseconds, as the last line shows.
  • rawHeaders is the stored header block, NATS/1.0 line and all, not a parsed array. Our X-Source header and the Nats-Msg-Id that msgId: set both came back.

Where a walk ends, and what it refuses

errors.php sends the cases the release notes list, plus one the README does not show: the stream name with a typo.

php
<?php
// errors.php: what the call refuses, and the two 404s a walk can end on.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

$client = connect('nats://127.0.0.1:14614');
$js = $client->jetStream();
orders($js);

$cases = [
    'empty subject' => ['ORDERS', '', 0],
    'negative start' => ['ORDERS', 'orders.1002.>', -1],
    'past the last event' => ['ORDERS', 'orders.1002.>', 10],
    'a subject with nothing on it' => ['ORDERS', 'orders.9999.>', 0],
    'a stream that does not exist' => ['ORDRES', 'orders.1002.>', 0],
];
foreach ($cases as $label => [$stream, $subject, $start]) {
    echo "$label:\n";
    try {
        $m = $js->getNextMessageForSubject($stream, $subject, $start)->await();
        printf("   got %d %s\n", $m->sequence, $m->subject);
    } catch (JetStreamException $e) {
        line('   ' . describe($e));
    }
}

echo "What the server answers to an empty next_by_subj, sent raw:\n";
$reply = $client->request('$JS.API.STREAM.MSG.GET.ORDERS',
    json_encode(['next_by_subj' => '', 'seq' => 3]))->await();
$stored = json_decode($reply->payload, true)['message'];
printf("   %d %s, a message of order 1001\n", $stored['seq'], $stored['subject']);

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
empty subject:
   0, err_code -: getNextMessageForSubject requires a non-empty subject
negative start:
   0, err_code -: getNextMessageForSubject requires a start sequence of 0 or more, got
     -1
past the last event:
   404, err_code 10037: no message found
a subject with nothing on it:
   404, err_code 10037: no message found
a stream that does not exist:
   404, err_code 10059: stream not found
What the server answers to an empty next_by_subj, sent raw:
   3 orders.1001.paid, a message of order 1001
  • Two calls never leave the client. An empty subject and a negative start sequence fail with code 0 and no err_code, before anything is sent.
  • The empty subject check matters. The last line shows why it is there: sent raw, an empty next_by_subj is not refused by the server, which answers with the message at the start sequence on whatever subject it has. A walk built on that would wander through every order.
  • Three different mistakes answer 404. Past the last event and a subject with nothing on it both give err_code 10037. A stream that does not exist gives 10059. A walk that ends on getCode() === 404 treats a typo in the stream name as an order with no history, and returns an empty list without an error.

That last case is what the snippet in the README and the bundled example still do, and the team filed it as issue #302 while reviewing the pull request that added the call:

GitHub issue 302 of php-nats-jetstream-client: the walk-a-subject snippet ends on any 404, so an unknown stream (err_code 10059) looks like the end of the subject

The release notes' own snippet and our walk() helper test getErrCode() !== 10037 instead. The client's ApiErrCode class has a constant for 10059 but none for 10037 yet, so the number is written out.

One request per message

A walk costs one round trip per message on the subject, plus the 404 at the end. cost.php puts that next to the two other ways that work without allow_direct: reading every sequence, and a pull consumer filtered on the order, created, fetched with no_wait and deleted again.

php
<?php
// cost.php: three ways to read one order's events out of 2000 messages.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

$client = connect('nats://127.0.0.1:14614');
$js = $client->jetStream();
try {
    $js->deleteStream('ORDERS')->await();
} catch (JetStreamException) {
    // first run: nothing to delete
}
$js->createStream('ORDERS', ['orders.>'])->await();
// 500 orders with four events each, each step of every order before the next step.
foreach (['created', 'paid', 'shipped', 'delivered'] as $event) {
    for ($order = 1; $order <= 500; $order++) {
        $js->publish("orders.$order.$event", '{}')->await();
    }
}
$subject = 'orders.250.>';
printf("ORDERS holds %d messages; reading %s\n",
    $js->getStream('ORDERS')->await()->raw['state']['messages'], $subject);

$report = function (string $how, int $calls, array $sequences, float $start): void {
    printf("%-28s %4d calls %6.1f ms  seq %s\n", $how, $calls,
        (microtime(true) - $start) * 1000, implode(',', $sequences));
};

// 1. Every sequence, keeping the matches (what 2.35 could do on any stream).
$start = microtime(true);
$found = [];
for ($seq = 1; $seq <= 2000; $seq++) {
    $message = $js->getStreamMessage('ORDERS', $seq)->await();
    if (str_starts_with($message->subject, 'orders.250.')) {
        $found[] = $seq;
    }
}
$report('getStreamMessage() x 2000', 2000, $found, $start);

// 2. getNextMessageForSubject(): one request per event, plus the 404 that ends the walk.
$start = microtime(true);
$walked = walk($js, $subject);
$found = array_map(fn($m) => $m->sequence, $walked);
$report('getNextMessageForSubject()', count($walked) + 1, $found, $start);

// 3. A filtered pull consumer: create it, fetch without waiting, delete it.
$start = microtime(true);
$js->createConsumer('ORDERS', 'REPLAY_250', $subject, ['ack_policy' => 'none'])->await();
$batch = $js->fetchBatch('ORDERS', 'REPLAY_250', 10, 1000, ['no_wait' => true])->await();
$js->deleteConsumer('ORDERS', 'REPLAY_250')->await();
$found = array_map(fn($m) => $js->messageMetadata($m)->streamSequence, $batch);
$report('pull consumer', 3, $found, $start);

$client->disconnect()->await();
text
Connected to nats-2-14, nats-server 2.14.10
ORDERS holds 2000 messages; reading orders.250.>
getStreamMessage() x 2000    2000 calls  472.6 ms  seq 250,750,1250,1750
getNextMessageForSubject()      5 calls    1.5 ms  seq 250,750,1250,1750
pull consumer                   3 calls    2.4 ms  seq 250,750,1250,1750

All three found sequences 250, 750, 1250 and 1750. The scan made 2000 calls to find four messages, and its cost grows with the stream, not with the order. The walk and the consumer took a few milliseconds each. These are single runs against a server on the same machine, so read the milliseconds as an order of magnitude, not as a benchmark; the call counts do not change between runs.

The walk does not replace a consumer. Each message costs a round trip, so a replay of thousands of messages on one subject makes thousands of calls, where a consumer delivers them in batches. The consumer, though, is state on the server: it has to be created, given a name, and deleted when you are done, or left to expire. The walk leaves nothing behind and can stop at any message. For the history of one order, one device or one user, that is the better trade.

Five server versions

The release says it measured the call against nats-server 2.10.29 to 2.15.3 and found no difference, so there is no version check. servers.php repeats the main checks on each of our servers: a walk with a stored header, a start sequence that counts, a wildcard, and an unknown stream.

php
<?php
// servers.php: the same checks against one server; the client does not check the version.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14614');
$js = $client->jetStream();
orders($js);
$js->publish('orders.1002.refunded', '{}', ['X-Source' => 'support'])->await();

$sequences = fn(array $messages): string => implode(',',
    array_map(fn($m) => $m->sequence, $messages));
$order = walk($js, 'orders.1002.>');
$from5 = $js->getNextMessageForSubject('ORDERS', 'orders.1002.>', 5)->await();
try {
    $js->getNextMessageForSubject('ORDRES', 'orders.>')->await();
    $unknown = 'answered';
} catch (JetStreamException $e) {
    $unknown = $e->getCode() . '/' . $e->getErrCode();
}
printf("   order 1002: %s | from 5: %d | *.shipped: %s\n", $sequences($order),
    $from5->sequence, $sequences(walk($js, 'orders.*.shipped')));
printf("   headers %s | unknown stream %s | time %s\n",
    str_contains((string) end($order)->rawHeaders, 'X-Source:support') ? 'kept' : 'lost',
    $unknown, $order[0]->time);

$client->disconnect()->await();
text
Connected to nats-2-10, nats-server 2.10.29
   order 1002: 2,5,8,9,10 | from 5: 5 | *.shipped: 6,8
   headers kept | unknown stream 404/10059 | time 2026-11-28T21:43:38.020756125Z
Connected to nats-2-11, nats-server 2.11.17
   order 1002: 2,5,8,9,10 | from 5: 5 | *.shipped: 6,8
   headers kept | unknown stream 404/10059 | time 2026-11-28T21:43:38.074606415Z
Connected to nats-2-12, nats-server 2.12.15
   order 1002: 2,5,8,9,10 | from 5: 5 | *.shipped: 6,8
   headers kept | unknown stream 404/10059 | time 2026-11-28T21:43:38.128060389Z
Connected to nats-2-14, nats-server 2.14.10
   order 1002: 2,5,8,9,10 | from 5: 5 | *.shipped: 6,8
   headers kept | unknown stream 404/10059 | time 2026-11-28T21:43:38.178789889Z
Connected to nats-2-15, nats-server 2.15.1
   order 1002: 2,5,8,9,10 | from 5: 5 | *.shipped: 6,8
   headers kept | unknown stream 404/10059 | time 2026-11-28T21:43:38.228982766Z

Every server gave the same answers, and every one sent the store time with nanoseconds. Our 2.15 image was 2.15.1, not the 2.15.3 the release used.

A replicated stream, and a leader that steps down

$JS.API.STREAM.MSG.GET is served by the stream leader, and the release notes say clustered or replicated streams were not run live. cluster.php creates ORDERS with three replicas on the three-node cluster, starts walking order 1002, and after two events asks the leader to step down with the raw $JS.API.STREAM.LEADER.STEPDOWN request. When a step fails with anything other than the end of the subject, it waits 250 ms and asks again from the same sequence:

php
<?php
// cluster.php: walk a stream with three replicas while its leader steps down.
declare(strict_types=1);

require __DIR__ . '/lib.php';

use IDCT\NATS\Exception\JetStreamException;

use function Amp\delay;

$client = connect($argv[1] ?? 'nats://127.0.0.1:14621'); // c1, c2, c3: 14621 to 14623
$js = $client->jetStream();
orders($js, ['num_replicas' => 3]);
$leader = fn(): string =>
    $js->getStream('ORDERS')->await()->raw['cluster']['leader'] ?? '?';
$before = $leader();
printf("ORDERS: 3 replicas, leader %s\n", $before);

$all = [];
$from = 0;
$failed = [];
while (true) {
    try {
        $stored = $js->getNextMessageForSubject('ORDERS', 'orders.1002.>', $from)
            ->await();
    } catch (JetStreamException $e) {
        if ($e->getErrCode() === 10037) {
            break; // the end of the walk
        }
        $failed[] = describe($e); // no leader yet: ask again from the same sequence
        if (count($failed) > 40) {
            throw $e;
        }
        delay(0.25);
        continue;
    }
    printf("   %2d %-22s %s\n", $stored->sequence, $stored->subject, $stored->payload);
    $all[] = $stored;
    $from = $stored->sequence + 1;
    if (count($all) === 2) {
        $client->request('$JS.API.STREAM.LEADER.STEPDOWN.ORDERS', '')->await();
        echo "   (leader asked to step down)\n";
    }
}
printf("Walked %d events; failed attempts during the election: %d\n", count($all),
    count($failed));
foreach (array_unique($failed) as $error) {
    line('   ' . $error);
}
$after = $leader();
printf("Leader before %s, after %s\n", $before, $after);

$client->disconnect()->await();
text
Connected to c1, nats-server 2.14.10
ORDERS: 3 replicas, leader c2
    2 orders.1002.created    {"total":40}
    5 orders.1002.paid       {"amount":40}
   (leader asked to step down)
    8 orders.1002.shipped    {"carrier":"ups"}
    9 orders.1002.delivered  {}
Walked 4 events; failed attempts during the election: 1
   503, err_code 10008: JetStream system temporarily unavailable
Leader before c2, after c1
  • The call works on a replicated stream, through any node. The client was connected to c1. The first two events came from the leader, c2, through it; after the step-down c1 itself led the stream, and the walk went on without any change in the code.
  • During the election the call fails with 503, err_code 10008, "JetStream system temporarily unavailable". It happened exactly once in this run, and once in each of three more runs we made, one through each node.
  • A walk that rethrows everything but 10037 stops here. That is the right default for a typo in the stream name, but not for a leader change. Because the walk's state is just the next sequence, retrying from it is safe: no message was skipped or returned twice.

Also in this release

The rest of 2.36.0 is documentation. The README's "JetStream Domains and API Prefixes" section has a new "Account imports" part: what an account that imports another account's JetStream needs beyond $JS.API.> for acknowledgements, flow control, calls with several replies and push delivery, and what fails without each (#281). Our 2.34 post ran an account import, and this section now covers what such a setup needs in more detail. The 2.30.0 changelog section gets four corrections, recorded as entries of this release, and the changelog now says that a released section is not rewritten. TESTS.md no longer gives test totals, which had drifted. The docs of DurableSourcingIntegrationTest now name the second integration stage, against nats-server 2.14 (#287).

Quality gates

From the release notes: PHPStan level 8; 4229 unit tests (with data sets) on PHP 8.2 to 8.5; 176 live integration tests against the nats-server 2.12 fixture stack, where 7 skip because they need 2.14, and 174 in the second run against nats-server 2.14, where nothing may skip; all 51 Behat scenarios and all 47 runnable examples pass. Every changed line that can be covered is covered. Infection reports a covered MSI of 92.75% against a 90% floor, with the caveat the release states itself: it skipped 5357 of the 9495 mutants it generated as too slow, so the score does not include them.

The 16 new unit cases all fail on 2.35.0. The new live test testGetNextMessageForSubjectWalksASubjectLive runs in both integration stages, on a stream without allow_direct, with interleaved subjects, a walk to the 404 and wildcard walks.

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.