php-nats-jetstream-client 2.32: no more silently dropped fields
(php, nats, release-notes) 16 min read by Bartosz Pachołek
2.32.0 makes a stream or consumer that asks for a feature the NATS server is too old for fail with UnsupportedFeatureException, where 2.10 and 2.11 used to create it without the feature. Plus 2.31.1: maxReconnectAttempts 0 now makes no reconnect attempt.
idct/php-nats-jetstream-client 2.32.0 is out, and it closes a quiet gap. Ask an older NATS server for a stream feature it does not have, such as per-message TTLs on 2.10, and until now the call succeeded: the stream was created, the reply looked normal, and the feature was simply not there. From 2.32.0 such a call fails with an UnsupportedFeatureException, before anything is sent whenever the server's version tells the client enough.
Our last post on the client covered 2.31.0, released earlier today. Two releases have come out since: 2.31.1, a patch that makes maxReconnectAttempts: 0 mean what its documentation says, and 2.32.0. This post covers both, starting with what to check before you upgrade. We ran every example on PHP 8.5.9 against nats-server 2.10.29, 2.11.17 (in its default mode and in strict mode) and 2.12.15 in Docker, and the output is pasted as it came out.
Upgrading
composer require idct/php-nats-jetstream-client:^2.32
On nats-server 2.12 or later every version-gated field exists, and 2.32.0 changes nothing for you. On older servers, or with reconnect attempts set to zero, check these:
- A stream or consumer that sets a field the server is too old for now throws (2.32.0). On 2.10 or 2.11 such a create or update used to succeed without the feature. If your code sets such a field "just in case", set it only when the server supports it (an example below shows how), or catch
UnsupportedFeatureException. - When the message says
exists without itorthe state of ... is unknown, do not delete the stream or consumer as a rollback. The request reached the server, and a create returns an existing stream or consumer whose config matches. It may be older than your call and hold messages. Inspect it withgetStream()orgetConsumer()first. - A negative
subject_delete_marker_ttlnow counts as asking for the feature. It is an invalid value, not "off". Use0, or leave the field out. - On a 2.11 server in strict mode the client now answers before the server does. The exception has code 0 and the client's message, where it had code 400 and the server's text.
catch (UnsupportedFeatureException)catches both. - A call made while the client fails over to a newer server can be refused on the version of the server it is leaving. Make the call again once connected.
maxReconnectAttempts: 0with reconnect on now makes no reconnect attempt (2.31.1). If you relied on the single retry it used to make, setmaxReconnectAttempts: 1.
The exception is a JetStreamException, so existing handlers still catch it. The full upgrade notes are in the changelog at v2.32.0.
The error the README promised
Several stream and consumer config fields need a newer server: filter_subjects needs nats-server 2.10; message TTLs (allow_msg_ttl), subject delete markers and the priority group fields need 2.11; and allow_msg_schedules, allow_atomic and allow_msg_counter need 2.12. Our README said that a server older than such a field "rejects the unknown field", and that the client turns the rejection into an UnsupportedFeatureException.
nats-server rejects an unknown field only in strict mode. 2.10 has no strict mode, 2.11 has it only with jetstream { strict: true }, and 2.12 is the first line where it is on by default. A default 2.10 or 2.11 server dropped the field and answered as if all was well. As the issue that tracked the fix points out, every gated field needs 2.12 at most, so in practice the documented exception could fire only on a 2.11 server with strict mode turned on.

What followed went wrong without an error. The release notes list three cases:
allow_msg_ttlon 2.10: a message published with a TTL was stored and never expired.allow_msg_counteron 2.11:incrementCounter()stored a plain message, then failed withCounter response did not include a value.allow_msg_scheduleson 2.11:publishScheduled()stored a message that no scheduler would fire.
The first two are easy to reproduce, so we did.
A proof of concept you can run
Four NATS servers in Docker, one script, and the client from Packagist. The strict server reads a three-line config file.
services:
nats-2-10:
image: nats:2.10-alpine
command: ["-js"]
ports: ["14310:4222"]
nats-2-11:
image: nats:2.11-alpine
command: ["-js"]
ports: ["14311:4222"]
nats-2-11-strict:
image: nats:2.11-alpine
command: ["-c", "/etc/nats/strict.conf"]
volumes: ["./strict.conf:/etc/nats/strict.conf:ro"]
ports: ["14313:4222"]
nats-2-12:
image: nats:2.12-alpine
command: ["-js"]
ports: ["14312:4222"]
jetstream {
strict: true
}
{
"require": {
"php": "^8.2",
"idct/php-nats-jetstream-client": "^2.32"
}
}
The script creates two streams. TTL_DEMO asks for message TTLs: the script publishes a message with a one-second TTL, waits three seconds and counts what is left. COUNTER_DEMO asks for a counter and increments it once. For each stream the script prints the fields the server echoed back in its config, or the exception if the create failed.
<?php
// gated.php: ask a server for message TTLs and a counter, and see what you get.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use function Amp\delay;
$url = $argv[1] ?? 'nats://127.0.0.1:4222';
$client = new NatsClient(new NatsOptions(servers: [$url]));
$client->connect()->await();
$js = $client->jetStream();
echo 'server ', $client->serverInfo()?->version, PHP_EOL;
// Create a stream that asks for a version-gated feature, or say why not.
$create = function (string $name, string $subjects, array $options) use ($js): bool {
try {
$js->deleteStream($name)->await();
} catch (\Throwable) {
// first run: nothing to delete
}
try {
$info = $js->createStream($name, [$subjects], $options)->await();
} catch (\Throwable $e) {
$class = (new \ReflectionClass($e))->getShortName();
printf("%s: %s (code %d)\n", $name, $class, $e->getCode());
echo ' ', wordwrap($e->getMessage(), 76, "\n "), PHP_EOL;
return false;
}
$echoed = json_encode((object) array_intersect_key($info->raw['config'], $options));
printf("%s: created, the server echoes %s\n", $name, $echoed);
return true;
};
// 1. A message that should be gone one second after it was published.
if ($create('TTL_DEMO', 'ttl.>', ['allow_msg_ttl' => true])) {
$js->publish('ttl.a', 'gone in 1s', ttl: '1s')->await();
delay(3);
$left = $js->getStream('TTL_DEMO')->await()->raw['state']['messages'] ?? '?';
printf(" 3 s after a publish with ttl 1s, the stream holds %s message(s)\n", $left);
}
// 2. A counter that should add up.
$counter = ['allow_msg_counter' => true, 'allow_direct' => true];
if ($create('COUNTER_DEMO', 'hits.>', $counter)) {
try {
$total = $js->incrementCounter('hits.home', '+1')->await();
printf(" incrementCounter: total %s\n", $total);
} catch (\Throwable $e) {
$error = (new \ReflectionClass($e))->getShortName() . ': ' . $e->getMessage();
echo ' incrementCounter: ', wordwrap($error, 74, "\n "), PHP_EOL;
}
}
$client->disconnect()->await();
docker compose up -d
composer install
php gated.php nats://127.0.0.1:14310 # nats-server 2.10
php gated.php nats://127.0.0.1:14311 # 2.11
php gated.php nats://127.0.0.1:14313 # 2.11, strict mode
php gated.php nats://127.0.0.1:14312 # 2.12
First the old behavior. We installed 2.31.1 in a separate directory (composer require idct/php-nats-jetstream-client:2.31.1), copied the script there and ran it against nats-server 2.10.29:
server 2.10.29
TTL_DEMO: created, the server echoes {}
3 s after a publish with ttl 1s, the stream holds 1 message(s)
COUNTER_DEMO: created, the server echoes {"allow_direct":true}
incrementCounter: JetStreamException: Counter response did not include a value
Both creates succeed. The server echoes {} for TTL_DEMO: it never stored allow_msg_ttl, and three seconds after a publish with a one-second TTL the message is still there. It will stay there. COUNTER_DEMO comes back without allow_msg_counter, and the first increment fails with an error that says nothing about the server's version. On 2.11.17 the TTL works, because 2.11 has the field, but the counter fails the same way:
server 2.11.17
TTL_DEMO: created, the server echoes {"allow_msg_ttl":true}
3 s after a publish with ttl 1s, the stream holds 0 message(s)
COUNTER_DEMO: created, the server echoes {"allow_direct":true}
incrementCounter: JetStreamException: Counter response did not include a value
With 2.32.0, on the same 2.10.29 server:
server 2.10.29
TTL_DEMO: UnsupportedFeatureException (code 0)
The "allow_msg_ttl" feature requires NATS server 2.11+, but the connected
server reports 2.10.29 (nothing was sent: an older server ignores the field
and would set up the stream without it)
COUNTER_DEMO: UnsupportedFeatureException (code 0)
The "allow_msg_counter" feature requires NATS server 2.12+, but the
connected server reports 2.10.29 (nothing was sent: an older server ignores
the field and would set up the stream without it)
Two refusals, each naming the field, the version it needs and the version the server reported. Nothing was sent, so there is no half-made stream to clean up. On 2.11.17:
server 2.11.17
TTL_DEMO: created, the server echoes {"allow_msg_ttl":true}
3 s after a publish with ttl 1s, the stream holds 0 message(s)
COUNTER_DEMO: UnsupportedFeatureException (code 0)
The "allow_msg_counter" feature requires NATS server 2.12+, but the
connected server reports 2.11.17 (nothing was sent: an older server ignores
the field and would set up the stream without it)
The TTL stream is created as before, since 2.11 has the field, and only the counter is refused. On nats-server 2.12.15 both releases printed the same lines, and both features work:
server 2.12.15
TTL_DEMO: created, the server echoes {"allow_msg_ttl":true}
3 s after a publish with ttl 1s, the stream holds 0 message(s)
COUNTER_DEMO: created, the server echoes {"allow_direct":true,"allow_msg_counter":true}
incrementCounter: total 1

Two checks, before and after the request
createStream(), addStream(), updateStream(), createOrUpdateStream() and the five consumer create calls now check every gated field the config sets to anything but its default. false, 0, 'none', [] and a missing field ask for nothing and are not checked. KeyValue and Object Store buckets are created through the same calls, so they are covered too.
- Before the request. When the version the server advertised in its INFO is older than the field needs, the call throws and nothing is sent. That is what the runs above show: the message ends with
nothing was sent. - After the reply. When the server's answer does not confirm the field, the call throws and names it. This covers a server whose version the client cannot read, such as a proxy or a custom build, and a cluster where an older server answers the JetStream API. The request was sent by then, so the message says only what the reply shows:
stream "X" exists without it, orthe state of stream "X" is unknownwhen the reply carries no config.
We did not run the second check against a real server: all four of ours advertise a version the client can read, so the first check always answered. According to the release notes, the pull request's author checked the change against real servers, and that check was not run again for the release: 2.10.29 and 2.11.17 got no request for a field they lack, and 2.11.17, 2.12.15 and 2.15.1 created and echoed every field they have, so the reply check raised no false alarm there. A server with an unreadable version and a failover between versions were covered over scripted transports only.
Strict mode on 2.11: same exception, new code
A 2.11 server with jetstream { strict: true } did reject the unknown field, and 2.31.1 mapped that rejection to the documented exception, with the server's code and text:
server 2.11.17
TTL_DEMO: created, the server echoes {"allow_msg_ttl":true}
3 s after a publish with ttl 1s, the stream holds 0 message(s)
COUNTER_DEMO: UnsupportedFeatureException (code 400)
The "allow_msg_counter" feature requires NATS server 2.12+, but the
connected server reports 2.11.17. (invalid JSON: json: unknown field
"allow_msg_counter")
2.32.0 does not let the request go out:
server 2.11.17
TTL_DEMO: created, the server echoes {"allow_msg_ttl":true}
3 s after a publish with ttl 1s, the stream holds 0 message(s)
COUNTER_DEMO: UnsupportedFeatureException (code 0)
The "allow_msg_counter" feature requires NATS server 2.12+, but the
connected server reports 2.11.17 (nothing was sent: an older server ignores
the field and would set up the stream without it)
Code that compared the code with 400, or matched unknown field in the message, should catch UnsupportedFeatureException and read its feature, requiredVersion and serverVersion properties instead.
Checking a config before you send it
2.32.0 adds one public method, FeatureSupport::requestedFields($config). It lists the gated fields a stream or consumer config asks for, by the same rules as the checks. Together with FeatureSupport::requiredVersion() it tells you which server a config needs before you send it, and with serverIsOlderThan(), which compares a required version with the one the server advertised, an application can leave out what the server lacks instead of failing:
<?php
// plan.php: which fields of this config can the connected server keep?
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\JetStream\FeatureSupport;
$url = $argv[1] ?? 'nats://127.0.0.1:4222';
$client = new NatsClient(new NatsOptions(servers: [$url]));
$client->connect()->await();
$js = $client->jetStream();
$server = $client->serverInfo()?->version;
echo "server $server\n";
$config = [
'max_msgs' => 10_000, // not version-gated
'allow_msg_ttl' => true, // NATS 2.11
'allow_msg_schedules' => true, // NATS 2.12
'allow_direct' => true, // not version-gated
'allow_msg_counter' => false, // the default: asks for nothing
];
foreach (FeatureSupport::requestedFields($config) as $field) {
$needs = FeatureSupport::requiredVersion($field);
if (FeatureSupport::serverIsOlderThan($server, $needs)) {
printf(" %-19s needs %s: left out\n", $field, $needs);
unset($config[$field]);
} else {
printf(" %-19s needs %s: kept\n", $field, $needs);
}
}
try {
$js->deleteStream('PLAN_DEMO')->await();
} catch (\Throwable) {
// first run: nothing to delete
}
$info = $js->createStream('PLAN_DEMO', ['plan.>'], $config)->await();
$gated = FeatureSupport::requestedFields($info->raw['config']);
$what = $gated === [] ? 'no gated field' : implode(', ', $gated);
echo "PLAN_DEMO created with $what\n";
$client->disconnect()->await();
server 2.10.29
allow_msg_ttl needs 2.11: left out
allow_msg_schedules needs 2.12: left out
PLAN_DEMO created with no gated field
server 2.11.17
allow_msg_ttl needs 2.11: kept
allow_msg_schedules needs 2.12: left out
PLAN_DEMO created with allow_msg_ttl
server 2.12.15
allow_msg_ttl needs 2.11: kept
allow_msg_schedules needs 2.12: kept
PLAN_DEMO created with allow_msg_ttl, allow_msg_schedules
allow_msg_counter => false is the default, so it is not listed. The last line reads the server's own config back through the same method, which confirms that each server kept what it was asked for. Whether leaving a feature out is acceptable is your call: a stream without message TTLs keeps its messages longer, and a stream without schedules cannot run them. When it is not acceptable, let the create fail.
We first wrote this script with allow_msg_counter next to allow_msg_ttl, and nats-server 2.12.15 refused that stream with counter stream cannot use message TTLs. A counter stream and message TTLs do not mix, whatever the client version.
The two checks themselves, FeatureSupport::assertSupportedBy() and assertHonored(), are public because JetStreamContext calls them, but they are marked @internal and are not part of the supported API.
A smaller fix: scheduler keys are not config fields
2.31.0 added schedule_every, schedule_cron, schedule_source, schedule_time_zone and schedule_rollup to the client's version table, as features of publishScheduled() that need nats-server 2.14. A side effect: a strict server's unknown field "schedule_every" rejection of a stream or consumer config was reported as "requires NATS 2.14". No server version accepts those keys in a config, so that advice was wrong. 2.32.0 reports the rejection as the ordinary JetStreamException with the server's own text. requiredVersion() still answers 2.14 for those keys, since that is what publishScheduled() needs. We did not run this case.
2.31.1: zero reconnect attempts means zero
NatsOptions::$maxReconnectAttempts is documented as "Set 0 to disable reconnect retries". The first connect read it that way, but the recovery after a lost connection made at least one attempt. With reconnectEnabled: true, maxReconnectAttempts: 0, a dropped connection waited out one backoff, dialled once more and, when that dial succeeded, carried on with its subscriptions replayed, possibly on another server of the pool. A worker that a supervisor should restart on connection loss, or a CLI tool that sets 0 to fail fast, got one more dial after every drop.
To see it, we put a small TCP proxy in front of a real nats-server 2.12.15, inside the same script. The proxy counts the dials and cuts the first connection after one second. The script then publishes and reports what happened.
<?php
// zero.php: reconnect on, maxReconnectAttempts 0. Does a lost connection dial again?
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use IDCT\NATS\Connection\Enum\ConnectionEvent;
use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use function Amp\async;
use function Amp\ByteStream\pipe;
use function Amp\delay;
use function Amp\Socket\connect;
use function Amp\Socket\listen;
// A small TCP proxy in front of the NATS server: it counts dials and cuts the first one.
$nats = $argv[1] ?? '127.0.0.1:4222';
$proxy = listen('127.0.0.1:0');
$dials = 0;
async(function () use ($proxy, $nats, &$dials): void {
while ($down = $proxy->accept()) {
$up = connect($nats);
$dials++;
async(function () use ($down, $up): void {
try { pipe($down, $up); } finally { $up->close(); }
})->ignore();
async(function () use ($down, $up): void {
try { pipe($up, $down); } finally { $down->close(); }
})->ignore();
if ($dials === 1) {
async(function () use ($down): void {
delay(1);
$down->close();
})->ignore();
}
}
})->ignore();
$client = new NatsClient(new NatsOptions(
servers: ['nats://' . $proxy->getAddress()],
reconnectEnabled: true,
maxReconnectAttempts: 0,
connectionListener: function (ConnectionEvent $event, ?\Throwable $cause): void {
$why = $cause ? ': ' . $cause->getMessage() : '';
echo ' event ', $event->name, $why, PHP_EOL;
},
));
$client->connect()->await();
echo "connected\n";
delay(2); // the proxy cuts the connection after 1 s
try {
$client->publish('demo', 'hello')->await();
$client->flush()->await();
echo "publish after the cut: ok\n";
} catch (\Throwable $e) {
echo 'publish after the cut: ', $e->getMessage(), PHP_EOL;
}
printf("dials: %d, state: %s\n", $dials, $client->state()->name);
$proxy->close();
try {
$client->disconnect()->await();
} catch (\Throwable) {
// already closed
}
php zero.php 127.0.0.1:14312
With 2.31.0:
event Connected
connected
event Disconnected
event Reconnected
publish after the cut: ok
dials: 2, state: Open
event Closed
The client dialled a second time, reconnected and went on as if nothing had happened, the opposite of what 0 promised. The last Closed comes from the script's own disconnect(). With 2.31.1, and the same with 2.32.0:
event Connected
connected
event Closed: Socket closed by peer (EOF), found before a write
publish after the cut: Reconnect is disabled
dials: 1, state: Closed
One dial, a Closed event that carries the cause, and the operation that noticed the loss fails with Reconnect is disabled. At 0 the connection now ends as it does with reconnect off, on every path that notices the loss: a failed read or write, missed pings, or a connection-ending frame. The count is for the whole server pool, so no other server is dialled either, and a lame duck notice starts no failover: the connection stays until the server closes it. maxReconnectAttempts: 1 still makes exactly one attempt. The release notes add that symfony-nats-messenger takes only a positive max_reconnect_attempts, so it never passes 0.
The second fix in 2.31.1 came out of the review of the first. With reconnect off, a heartbeat that gave up on a server which stopped answering its PINGs closed the socket while its previous PONG read was still waiting on it. That read then failed with the end of the client's own close, and the connection listener heard Closed twice. It showed with a pingIntervalSeconds below 2 seconds, and it is fixed. The release names one case that is still open: when your own processIncoming() read is waiting at the moment the heartbeat gives up, the listener still hears Closed twice. We did not run either heartbeat case.
Quality gates
For 2.32.0, from the release notes: PHPStan level 8, 3998 unit tests (with data sets) on PHP 8.2 to 8.5, 162 live integration tests and 51 Behat scenarios, and all 47 runnable examples pass. Every changed line is covered (102 of 102), and total coverage is 99.11%. Infection reports a covered MSI of 92.70% against a 90% floor, with a caveat the release states itself: it skipped 4898 of the 9361 mutants it generated as too slow, so the score does not include them. 63 of the new test cases fail on 2.31.1. CI's fixture server is 2.12, the side where nothing changes, which is why we ran the older servers for this post ourselves.
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.