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

php-nats-jetstream-client 2.31: schedules your server can run

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

2.31.0 refuses a recurring schedule, a source or a rollup that NATS 2.12 would reject with an opaque 400 or silently ignore. Plus everything since 2.27: instant permission errors, a diagnosis for a pull's 503, and writes that survive a dead socket.

idct/php-nats-jetstream-client 2.31.0 is out, and its one fix is about scheduled publishing: publishScheduled() now refuses, before anything is written, a schedule that the connected NATS server cannot run. On nats-server 2.12 and 2.13 such a call used to end in an error that named no version, or worse, in a schedule stored without the parts you asked for.

Our last post on the client covered 2.27.0. Seven releases have come out since, 2.27.1 to 2.31.0, and this post goes through all of them, starting with what to check before you upgrade. We ran the examples on PHP 8.5.9 against nats-server 2.12.15 and 2.14.10 in Docker, and the output is pasted as it came out.

Upgrading

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

Most of this cycle is fixes, but a few calls now fail differently, or sooner. Check these:

  • Scheduled publishing on nats-server 2.12 or 2.13 (2.31.0). A recurring schedule still fails, but with an UnsupportedFeatureException (code 0) thrown by the client, where it was a JetStreamException with code 400 from the server. An @at schedule with source or rollup now fails, where it used to be stored without them. catch (JetStreamException) catches both. Code that compared the code 400 or the message message schedules pattern is invalid should catch UnsupportedFeatureException instead. On 2.14 and later nothing changes.
  • A request to a subject the user may not publish to (2.30.0) fails at once with the new PermissionViolationException, instead of a TimeoutException at the end of its timeout. It is a NatsException, not a ConnectionException. requestMany() to such a subject throws it too when no reply came, where it returned an empty list.
  • A JetStream API call that nobody answers (2.29.0), on a server or account without JetStream for example, fails with a JetStreamException with code 503 instead of a bare NatsException. Its message is now No JetStream responder for subject ..., so match the code, not the text.
  • A plain publish whose write is the first to notice a lost connection (2.27.1) resolves once its frame is in the reconnect buffer, instead of waiting for the whole reconnect. If the reconnect gives up, the loss goes to the errorListener and the Closed event, not to the publish. Call flush() where you need to wait for the frame to go out. This covers publish(), publishWithHeaders(), ack(), nak(), term(), inProgress() and respond().

2.28.0 adds one option, resendJetStreamPublishOnReconnect, which is off by default. The full upgrade notes are in the changelog at v2.31.0.

Scheduled publishing needs 2.14 for more than we said

A JetStream stream can hold a message and publish it later, or on a schedule. The design is ADR-51, and the client wraps it in publishScheduled() and the Schedule builders. The first scheduler shipped in nats-server 2.12, but it runs only one-off @at schedules. The recurring ones (@every, 6-field cron, aliases such as @daily) and the source, timeZone and rollup options came in nats-server 2.14.0, as revisions 3 to 7 of ADR-51 record.

Our README and docblocks said 2.12 for all of it. That was wrong, and the issue that tracked the fix explains how it went unnoticed: the CI fixture runs nats:2.12-alpine, and the integration tests exercised only @at.

GitHub issue 267 of php-nats-jetstream-client, closed by pull request 270: @every, cron, the aliases, timeZone, source and rollup need nats-server 2.14, not 2.12

On a 2.12 or 2.13 server, two things went wrong:

  • A recurring schedule failed with an error that named no version: JetStreamException (code 400): message schedules pattern is invalid.
  • source and rollup on an @at schedule were dropped without an error. The server stored the schedule, ignored both headers, and later published a message that was not the one the caller asked for.

The second one is the nasty one. source exists for sampling: when the schedule fires, the server publishes the latest message of the source subject instead of the schedule's own payload. Dropped silently, the schedule publishes its placeholder payload, and nothing in your logs says so.

A proof of concept you can run

To see both failures and the fix, we wrote a small project: two NATS servers in Docker, one script, and the client from Packagist.

yaml
services:
  nats-2-12:
    image: nats:2.12-alpine
    command: ["-js"]
    ports: ["14212:4222"]
  nats-2-14:
    image: nats:2.14-alpine
    command: ["-js"]
    ports: ["14214:4222"]
json
{
    "require": {
        "php": "^8.2",
        "idct/php-nats-jetstream-client": "^2.31"
    }
}

The script creates a stream that allows schedules and puts "the latest price" on prices.latest. Then it asks for four schedules: a one-off @at two seconds ahead, @every 1m, a cron that fires at 09:00 every day, and an @at whose source is prices.latest. It waits four seconds and prints what the two @at schedules published.

php
<?php
// schedules.php: what does this server schedule, and what fires?
declare(strict_types=1);

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

use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\JetStream\Schedule;

use function Amp\delay;

$client = new NatsClient(new NatsOptions(servers: [$argv[1] ?? 'nats://127.0.0.1:4222']));
$client->connect()->await();
$js = $client->jetStream();
echo 'server ', $client->serverInfo()?->version, PHP_EOL;

try {
    $js->deleteStream('DEMO')->await();
} catch (\Throwable) {
    // first run: nothing to delete
}
$js->createStream('DEMO', ['schedules.>', 'events.>', 'prices.>'], [
    'allow_msg_schedules' => true,
])->await();
$js->publish('prices.latest', 'the latest price')->await();

// One schedule per subject: schedules.<n> fires into events.<n>.
$schedule = fn (string $n, string $expr, ?string $source = null) => $js->publishScheduled(
    "schedules.$n", "events.$n", 'my payload', $expr, source: $source,
);
$soon = Schedule::at(new DateTimeImmutable('+2 seconds'));
$calls = [
    '@at' => fn () => $schedule('a', $soon),
    '@every 1m' => fn () => $schedule('b', Schedule::every('1m')),
    'cron' => fn () => $schedule('c', Schedule::cron('0 0 9 * * *')),
    '@at+source' => fn () => $schedule('d', $soon, 'prices.latest'),
];
foreach ($calls as $label => $call) {
    try {
        printf("%-11s stored, seq %d\n", $label, $call()->await()->seq);
    } catch (\Throwable $e) {
        $class = (new \ReflectionClass($e))->getShortName();
        printf("%-11s %s (code %d)\n", $label, $class, $e->getCode());
        echo '  ', wordwrap($e->getMessage(), 76, "\n  "), PHP_EOL;
    }
}

delay(4); // let the two @at schedules fire
foreach (['events.a', 'events.d'] as $subject) {
    try {
        $payload = $js->getLastMessageForSubject('DEMO', $subject)->await()->payload;
    } catch (\Throwable) {
        $payload = '(nothing)';
    }
    printf("%s received: %s\n", $subject, $payload);
}
$client->disconnect()->await();

Start the servers, install, and run it against each server:

bash
docker compose up -d
composer install
php schedules.php nats://127.0.0.1:14212
php schedules.php nats://127.0.0.1:14214

First the old behavior. We installed 2.30.1 in a separate directory (composer require idct/php-nats-jetstream-client:2.30.1), copied the script there, and ran it against nats-server 2.12.15:

text
server 2.12.15
@at         stored, seq 2
@every 1m   JetStreamException (code 400)
  message schedules pattern is invalid
cron        JetStreamException (code 400)
  message schedules pattern is invalid
@at+source  stored, seq 3
events.a received: my payload
events.d received: my payload

The @at with source reports "stored", and four seconds later events.d received my payload, not the latest price. The caller has no way to tell. The two recurring schedules fail, but the error does not say why.

With 2.31.0, on the same server:

text
server 2.12.15
@at         stored, seq 2
@every 1m   UnsupportedFeatureException (code 0)
  The schedule "@every 1m" requires NATS server 2.14+; older servers accept
  only "@at" schedules (connected server 2.12.15; nothing was published)
cron        UnsupportedFeatureException (code 0)
  The schedule "0 0 9 * * *" requires NATS server 2.14+; older servers accept
  only "@at" schedules (connected server 2.12.15; nothing was published)
@at+source  UnsupportedFeatureException (code 0)
  Nats-Schedule-Source (the source argument) requires NATS server 2.14+; older
  servers ignore it (connected server 2.12.15; nothing was published)
events.a received: my payload
events.d received: (nothing)

Three refusals, each naming what was asked for, the version it needs and the server's version, and nothing stored: events.d stays empty. The plain @at schedule works as before.

On nats-server 2.14.10, both releases printed the same lines:

text
server 2.14.10
@at         stored, seq 2
@every 1m   stored, seq 3
cron        stored, seq 4
@at+source  stored, seq 5
events.a received: my payload
events.d received: the latest price

Here the @at with source published the latest price, which is what the 2.12 server silently did not do. A time zone is accepted only with a cron schedule, so the cron check covers it, and rollup is refused on an older server the same way as source.

GitHub release page of php-nats-jetstream-client v2.31.0, whose Fixed section describes the opaque 400 and the dropped source and rollup on NATS 2.12

Choosing a schedule by server version

The refusal is an UnsupportedFeatureException with three public properties: feature (schedule_every, schedule_cron, schedule_source or schedule_rollup), requiredVersion and serverVersion. It extends JetStreamException, so existing handlers still catch it.

If you would rather not meet it at all, 2.31.0 lets you ask first. FeatureSupport::requiredVersion() now knows schedule_every, schedule_cron, schedule_source, schedule_time_zone and schedule_rollup, and answers "2.14" for each. FeatureSupport::serverIsOlderThan() compares that with the version the server advertised. This script, run after schedules.php so that the stream exists, falls back to a one-off schedule on the older server:

php
<?php
// fallback.php: ask the server before you schedule, and fall back on an older one.
// Run it after schedules.php, which creates the DEMO stream on both servers.
declare(strict_types=1);

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

use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\JetStream\FeatureSupport;
use IDCT\NATS\JetStream\Schedule;

foreach (['nats://127.0.0.1:14212', 'nats://127.0.0.1:14214'] as $url) {
    $client = new NatsClient(new NatsOptions(servers: [$url]));
    $client->connect()->await();

    $version = $client->serverInfo()?->version;
    $needs = FeatureSupport::requiredVersion('schedule_every');
    // On an older server: a single run in an hour, and the next one is up to you.
    $schedule = FeatureSupport::serverIsOlderThan($version, $needs)
        ? Schedule::at(new DateTimeImmutable('+1 hour'))
        : Schedule::every('1h');

    $ack = $client->jetStream()->publishScheduled(
        'schedules.report', 'events.report', '{"report":"hourly"}', $schedule,
    )->await();
    printf("%s (@every needs %s): %s, seq %d\n", $version, $needs, $schedule, $ack->seq);
    $client->disconnect()->await();
}
text
2.12.15 (@every needs 2.14): @at 2026-11-25T13:47:44Z, seq 4
2.14.10 (@every needs 2.14): @every 1h, seq 8

A version that cannot be read is never "older". Behind a proxy, or with a custom build that reports no usable version, serverIsOlderThan() returns false, and publishScheduled() publishes as before and leaves the decision to the server.

Reconnects and failover

The version checked is that of the server that takes the message. On an open connection the call is checked at once. It is checked again in the step that writes the frame: once a reconnect the call waited for is over, and before the retry that follows a failed write. A client that fails over from a 2.14 server to a 2.12 one gets the refusal there, instead of a schedule stored without its source. One that fails over from 2.12 to 2.14 publishes, instead of being refused because of the connection it left.

We did not run a failover for this post. The release adds ScheduledPublishServerVersionTest with 39 cases, 17 of them for a reconnect between a 2.14 and a 2.12 server in both directions and for the retry after a failed write; 18 of the 39 fail on 2.30.1. According to the release notes, the pull request's author also checked the change against real 2.12.15 and 2.14.10 servers, including a client failing over between them, and that check was not run again for the release. CI's fixture server is 2.12, so CI covers the refusal.

2.30: a refused request fails at once

When a user publishes to a subject it may not publish to, nats-server answers -ERR 'Permissions Violation for Publish to "<subject>"', keeps the connection open, and no reply ever comes. Up to 2.29, request() waited out its whole timeout and then threw a TimeoutException. That also made a refused JetStream publish look like one whose acknowledgement was late, which might still have been stored. The changelog gives one measurement: a getConsumer() by a user denied $JS.API.CONSUMER.INFO.> took 5006 ms with a 5-second timeout.

Since 2.30.0, every request in flight to the refused subject fails as soon as the -ERR is read, with a PermissionViolationException whose getSubject() names the subject. Requests to other subjects are left alone, the connection stays open, and the error listener still gets the -ERR.

We gave one user the right to publish to orders.> and nothing else:

text
authorization {
  users = [
    {
      user: shop, password: demo
      permissions: { publish: ["orders.>"], subscribe: ["_INBOX.>"] }
    }
  ]
}
bash
docker run -d -p 14216:4222 -v "$PWD/perm.conf:/etc/nats/perm.conf:ro" \
  nats:2.14-alpine -c /etc/nats/perm.conf

Then we made two requests with a 3-second timeout: one to orders.lookup, which the user may publish to but nobody answers, and one to billing.refund, which it may not publish to.

php
<?php
// permissions.php: a request to a subject this user may not publish to.
declare(strict_types=1);

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

use IDCT\NATS\Connection\NatsOptions;
use IDCT\NATS\Core\NatsClient;
use IDCT\NATS\Exception\PermissionViolationException;

$client = new NatsClient(new NatsOptions(
    servers: ['nats://127.0.0.1:14216'],
    username: 'shop',
    password: 'demo',
    requestTimeoutMs: 3000,
));
$client->connect()->await();

foreach (['orders.lookup', 'billing.refund'] as $subject) {
    $start = hrtime(true);
    try {
        $client->request($subject, '{"order":42}')->await();
        $result = 'a reply';
    } catch (\Throwable $e) {
        $result = (new \ReflectionClass($e))->getShortName();
        if ($e instanceof PermissionViolationException) {
            $result .= ' for ' . $e->getSubject();
        }
    }
    printf("%-15s %s after %.1f ms\n", $subject, $result, (hrtime(true) - $start) / 1e6);
}
$client->disconnect()->await();

With 2.29.0:

text
orders.lookup   NatsException after 0.6 ms
billing.refund  TimeoutException after 3001.9 ms

With 2.31.0:

text
orders.lookup   NatsException after 0.6 ms
billing.refund  PermissionViolationException for billing.refund after 0.3 ms

The allowed subject without a responder fails at once in both, through NATS's no-responders status. The refused one used to cost the full three seconds and looked like a slow server.

The changelog names two limits. fetchBatch() and the pull consumer publish with an inbox of their own and are not covered: a refused pull still ends at its expiry with the 408 of an empty one. And the refusal is matched by subject, so an -ERR for an earlier publish to that subject, left unread, refuses a later request to it as well.

2.29 and 2.30.1: what a pull's 503 means

A pull that gets status 503 (no responders) usually means that the consumer or its stream does not exist. It also happens in the last moments of a server that is going away, in a graceful stop or in lame duck mode, because such a server stops its consumers before it closes the connections. fetchBatch() reports both as the same JetStreamException(503), and a consumer loop that read it as a missing consumer ended, or created the consumer again on the server that was leaving.

2.29.0 adds JetStreamContext::diagnoseNoResponders($stream, $consumer, $timeoutMs = null) to tell them apart. It asks the server for the consumer while it watches the connection the pull came on, and returns a NoRespondersCause: ConsumerNotFound, StreamNotFound, ConsumerFound, JetStreamError, ServerGoingAway or NoAnswer. A server that stays answers at once. One that is going away answers nothing, and the cause is ServerGoingAway as soon as the connection is closed or replaced, or its server announces lame duck mode. Call it right after the pull's 503, and pause before the next pull. symfony-nats-messenger 5.8.1 does exactly that, and our symfony-nats-messenger 5.8 post shows a worker that keeps pulling through the lame duck grace period instead of ending on the first 503.

2.29.0 also reports a JetStream API call that nobody answers as a JetStreamException with code 503 (see the upgrade list above), and fails a JSON API reply that is not an object with a JetStreamException, where it used to end in a TypeError.

2.30.0 kept the diagnosis working for a user who may pull but not ask for consumer info. The server refuses that user's question at once, so with the new permission error every such 503 would have looked like a missing consumer. Instead, the client watches the connection for the rest of the question's time. 2.30.1 fixes two cases of that watch:

  • With reconnect on, it returned ServerGoingAway only once the reconnect was over: 3.0 s for a 1 s timeout in the changelog's case, where 2.29.0 returned after 0.17 s. A symfony-nats-messenger worker with reconnect: true stayed deaf to messenger:stop-workers and SIGTERM meanwhile. The watch now returns while the client is still reconnecting.
  • Over a transport whose idle read returns at once, the watch spun at full CPU and never returned. It now pauses 1 ms after such a read. The built-in socket and WebSocket transports wait in their read and were not affected.

2.27.1 to 2.28: writes that meet a dead socket

Three releases in this cycle deal with what happens to a write when the server has just gone away.

  • 2.27.1: no inline reconnect in a publish. A fire-and-forget publish whose write failed on a connection still marked open ran the whole reconnect loop in the caller's fiber. With the defaults, that is about 100 s for a server that does not come back. Measured through symfony-nats-messenger, an ack() that met the outage returned after 103 s. The frame now goes to the reconnect buffer, and the recovery runs in a fiber of its own. This is the behavior change in the upgrade list.
  • 2.27.2: a status next to a fatal error. A pull status read in the same chunk as a frame that ends the connection, such as a 409 Consumer Deleted next to a Stale Connection error, now reaches onError and ends an infinite run. Before, the run pulled on against a deleted consumer and never ended.
  • 2.28.0: no writes into a closed socket. The connection reads the socket only while something waits for a reply, so a close from the server could stay unread, and a publish or ack() written after it reached no server. The publish resolved and its message was lost, or the ack was lost and the message came back after ack_wait. Before such a write, the client now asks the transport whether the server has closed the socket, a peek that reads nothing and takes about half a microsecond, and treats a yes as a failed write: the frame goes out on the new connection.

2.28.0 also adds NatsOptions::$resendJetStreamPublishOnReconnect. With it on, a JetStream publish() that carries a $msgId writes its frame once more on the new connection when the one it went out on is replaced before the PubAck came. The Nats-Msg-Id makes a second copy harmless. It is off by default because of two limits: the stream's duplicate_window must be longer than the request timeout (the 2-minute default is), and on a NATS 2.10 cluster a new stream leader can take a publish before it has applied what the old leader replicated, so a copy may be stored twice there.

Quality gates

For 2.31.0, from the release notes: PHPStan level 8, 3907 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 (57 of 57), and total coverage is 99.10%. Infection reports a covered MSI of 92.68% against a 90% floor, with a caveat the release states itself: it skipped 4766 of the 9277 mutants it generated as too slow, so the score does not include them.

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.