symfony-nats-messenger 5.15: per-message subjects
(php, symfony, nats, release-notes) 25 min read by Bartosz Pachołek
5.15.0 adds per-message subjects, from Adrian Brajković: a NatsSubjectStamp sends one message to a subject of its own, and additional_subjects lets the transport's one consumer read them in stream order. Run on NATS 2.9, 2.10 and 2.15, with the two-step rollout reproduced.
symfony-nats-messenger 5.15.0 is out, and its main feature comes from an outside contributor. Per-message subjects, proposed by Adrian Brajković in #100, let one message go to a subject of its own, such as shop.orders.updated.42, while the transport's one durable consumer still reads everything in stream order. A NatsSubjectStamp picks the subject for one message, and the new option additional_subjects lists the patterns those subjects fall under. With the option, setup() needs NATS 2.10 or later, and the upgrade has to go out in two steps: we reproduced what happens to a stamped message when it does not.
We ran every example on PHP 8.5.9 against the official NATS images 2.9.25, 2.10.29 and 2.15.3 in Docker, with Symfony Messenger 8.2.0 and php-nats-jetstream-client 2.42.1. We installed 5.14.0 and 5.15.0 from Packagist side by side with the same composer.lock, so only the transport differs. The outputs are pasted as they came out.

Why a message would want a subject of its own
A transport's DSN names a stream and a topic, and up to 5.14.0 every message a transport sent was delivered to the topic. Every OrderUpdated went to shop.orders, whichever order it was about. That is fine for the worker, which reads the topic anyway, but it hides the order from NATS itself.
A subject per entity puts that information where NATS can use it. Another consumer can filter on one order, any tool can read one order's messages by subject, and per-subject limits (the transport's own stream_max_messages_per_subject maps to NATS max_msgs_per_subject) count per order. What you did not want to give up is the single consumer: one durable consumer per transport is what keeps a transport's messages in stream order. Two transports, one per subject, would mean two consumers and two orders.
5.15.0 keeps the one consumer and gives it several filters. The topic stays the default publish subject. A message stamped with NatsSubjectStamp('shop.orders.updated.42') goes to that subject instead, and additional_subjects=shop.orders.updated.> puts the pattern on the stream and, next to the topic, on the consumer's filter_subjects. That field arrived in NATS 2.10, which is where the version requirement comes from.

Adrian opened the pull request on 3 November. Our review on 13 November opened three issues against it: a stamp applied by every transport a message is routed to (#110), a setup() with another configuration narrowing the consumer so that stamped messages are lost (#111), and a NATS 2.9 consumer left unfiltered before the setup failed (#112). He answered them on the branch, our team added the maintainer rounds on top, and the pull request was merged this morning with 32 commits, 12 of them his. v5.15.0 was published within a minute.
Proof of concept: one consumer, several subjects
Every example below runs on one Compose project, one server per release:
# One server with JetStream per release the examples compare. Host ports:
# s29 14861 nats-server 2.9.25, before filter_subjects
# s210 14862 nats-server 2.10.29, the first release with filter_subjects
# s215 14863 nats-server 2.15.3, which also has message schedules
services:
s29:
image: nats:2.9.25-alpine
command: ["-js", "--server_name", "s29"]
ports: ["14861:4222"]
s210:
image: nats:2.10.29-alpine
command: ["-js", "--server_name", "s210"]
ports: ["14862:4222"]
s215:
image: nats:2.15.3-alpine
command: ["-js", "--server_name", "s215"]
ports: ["14863:4222"]
The project needs only the transport:
{
"require": {
"idct/symfony-nats-messenger": "^5.15"
}
}
The scripts share a few helpers. api() sends one raw JetStream API request, which is what any other tool sends. consumer() reads the consumer's filters from whichever field holds them, and stored() lists what the stream holds with each message's Nats-Msg-Id:
<?php
// What the examples share: a transport on one of the three servers, raw JetStream API
// requests to look at the stream and the consumer the way any other tool would, and a
// pull loop that receives and acknowledges like a worker.
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\NatsTransport;
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
const SERVERS = ['2.9.25' => 14861, '2.10.29' => 14862, '2.15.3' => 14863];
/** The message of every example: a line of text. */
final class OrderEvent
{
public function __construct(public readonly string $text)
{
}
}
/** A transport on 127.0.0.1:$port, $path being "<stream>/<topic>". */
function transport(int $port, string $path, string $query = ''): NatsTransport
{
$dsn = "nats-jetstream://127.0.0.1:$port/$path" . ($query === '' ? '' : "?$query");
return new NatsTransport($dsn, ['max_batch_timeout' => 0.2], new PhpSerializer());
}
/** One JetStream API request, its reply decoded to arrays. */
function api(int $port, string $subject, ?array $body = null): array
{
$client = (new NatsTransportConfigurationBuilder())
->build("nats-jetstream://127.0.0.1:$port/x/x")->client;
$client->connect()->await();
try {
$payload = $body === null ? '' : json_encode($body, JSON_THROW_ON_ERROR);
$reply = $client->request('$JS.API.' . $subject, $payload)->await();
return json_decode($reply->payload, true, 512, JSON_THROW_ON_ERROR);
} finally {
$client->disconnect()->await();
}
}
/** Deletes the stream, so that every run starts from nothing. */
function fresh(int $port, string $stream): void
{
api($port, "STREAM.DELETE.$stream");
}
/** The stream's subjects, or why there are none. */
function streamSubjects(int $port, string $stream): string
{
$info = api($port, "STREAM.INFO.$stream");
if (isset($info['error'])) {
return "no stream $stream";
}
return implode(', ', $info['config']['subjects']);
}
/** The consumer's filters, in whichever field it holds them, and its num_pending. */
function consumer(int $port, string $stream, string $name): string
{
$info = api($port, "CONSUMER.INFO.$stream.$name");
if (isset($info['error'])) {
return "no consumer $name";
}
$config = $info['config'];
$filters = isset($config['filter_subjects'])
? 'filter_subjects [' . implode(', ', $config['filter_subjects']) . ']'
: 'filter_subject ' . ($config['filter_subject'] ?? '(none)');
return sprintf('%s, num_pending %d', $filters, $info['num_pending']);
}
/**
* Every message the stream stores: its sequence, subject and Nats-Msg-Id.
*
* @return list<array{int, string, ?string}>
*/
function stored(int $port, string $stream): array
{
$info = api($port, "STREAM.INFO.$stream");
$messages = [];
$last = $info['state']['last_seq'];
for ($seq = $info['state']['first_seq']; $seq <= $last; $seq++) {
$reply = api($port, "STREAM.MSG.GET.$stream", ['seq' => $seq]);
if (!isset($reply['message'])) {
continue;
}
$headers = base64_decode($reply['message']['hdrs'] ?? '');
$id = preg_match('/^Nats-Msg-Id: *(\S+)/mi', $headers, $m) === 1 ? $m[1] : null;
$messages[] = [$seq, $reply['message']['subject'], $id];
}
return $messages;
}
/**
* Pulls for $seconds as a worker does, acknowledging what arrives.
*
* @return list<Envelope>
*/
function receive(NatsTransport $transport, float $seconds): array
{
$received = [];
$until = microtime(true) + $seconds;
while (microtime(true) < $until) {
foreach ($transport->get() as $envelope) {
$transport->ack($envelope);
$received[] = $envelope;
}
}
return $received;
}
function versions(): void
{
printf(
"symfony-nats-messenger %s, php-nats-jetstream-client %s\n",
InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger'),
InstalledVersions::getPrettyVersion('idct/php-nats-jetstream-client'),
);
}
/** Prints a line, wrapped under 90 characters, the indent of the next lines included. */
function out(string $line, string $indent = ' '): void
{
echo wordwrap(rtrim($line), 88 - strlen($indent), "\n" . $indent, true), "\n";
}
subjects.php sets up a transport on the topic shop.orders with the pattern shop.orders.updated.> and duplicate protection on, sends five messages, three of them stamped, and reads them back through the consumer:
<?php
// One transport, one durable consumer. The topic is shop.orders, and additional_subjects
// adds the pattern shop.orders.updated.> for the messages stamped with a subject of
// their own. Run: php subjects.php <port>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NatsMessenger\Stamp\NatsReceivedSubjectStamp;
use IDCT\NatsMessenger\Stamp\NatsSubjectStamp;
use Symfony\Component\Messenger\Envelope;
$port = (int) ($argv[1] ?? 14863);
versions();
fresh($port, 'shop');
$transport = transport(
$port,
'shop/shop.orders',
'consumer=worker&deduplicate=true&additional_subjects=shop.orders.updated.>',
);
try {
$transport->setup();
} catch (RuntimeException $refused) {
out('setup() refused: ' . $refused->getMessage());
out('stream: ' . streamSubjects($port, 'shop'));
exit(1);
}
out('stream subjects: ' . streamSubjects($port, 'shop'));
out('consumer: ' . consumer($port, 'shop', 'worker'));
// The text of each message, and the subject it is stamped for (null: no stamp).
$sends = [
['order 41 placed', null],
['order 42 updated', 'shop.orders.updated.42'],
['order 7 updated', 'shop.orders.updated.7'],
['invoice 42 issued', 'shop.invoices.42'],
['order 43 placed', null],
];
foreach ($sends as [$text, $subject]) {
$stamps = $subject === null ? [] : [new NatsSubjectStamp($subject)];
$transport->send(new Envelope(new OrderEvent($text), $stamps));
}
echo "stored:\n";
foreach (stored($port, 'shop') as [$seq, $subject, $id]) {
out(" #$seq $subject");
out(" Nats-Msg-Id $id");
}
echo "received by the consumer worker:\n";
foreach (receive($transport, 1.0) as $envelope) {
$arrived = $envelope->last(NatsReceivedSubjectStamp::class)?->subject;
out(sprintf(' %-18s on %s', $envelope->getMessage()->text, $arrived));
}
out('consumer: ' . consumer($port, 'shop', 'worker'));
$transport->close();
Run it:
docker compose up --detach
composer install
php subjects.php 14863
On nats-server 2.15.3:
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
stream subjects: shop.orders, shop.orders.updated.>
consumer: filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
stored:
#1 shop.orders
Nats-Msg-Id 5c280eca-2975-4744-90b9-3984e611341f:shop.orders:0
#2 shop.orders.updated.42
Nats-Msg-Id 4b4373f0-de34-41d8-9f2b-65029e86e87f:shop.orders.updated.42:0
#3 shop.orders.updated.7
Nats-Msg-Id 7816294b-54bd-42cb-879f-7c660f1daa59:shop.orders.updated.7:0
#4 shop.orders
Nats-Msg-Id 296d39a4-f1ff-4168-ba39-5b8b35fc8048:shop.orders:0
#5 shop.orders
Nats-Msg-Id ccd14157-4246-437a-9b91-262935d61339:shop.orders:0
received by the consumer worker:
order 41 placed on shop.orders
order 42 updated on shop.orders.updated.42
order 7 updated on shop.orders.updated.7
invoice 42 issued on shop.orders
order 43 placed on shop.orders
consumer: filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
What to look at:
setup()put the pattern on the stream's subjects and gave the consumerfilter_subjectswith the topic and the pattern. Without the option a new consumer still gets its singlefilter_subject.- The two order updates are stored on their own subjects, and the consumer received all five messages in the order they were sent, the topic's and the stamped ones mixed.
- Each received envelope carries a
NatsReceivedSubjectStampwith the subject it arrived on, so a handler can tellshop.orders.updated.42from the topic without parsing the payload. invoice 42 issuedwas stamped forshop.invoices.42, which this consumer does not read, and it went to the topic. A transport uses a stamp only for a subject its own consumer reads. Symfony hands every transport a message is routed to the same envelope, stamp included, so this rule is what lets a stamped message routed to two transports reach each of them once (#110).Nats-Msg-Idnow names the subject the message is delivered to:<id>:<subject>:<retry count>. 5.14.0 wrote the topic there, and with stamps an id naming only the topic would have made JetStream drop the copy one deduplication id sent to a second subject. Messages without a stamp keep the ids they had,<id>:shop.orders:0.
On 2.10.29 (php subjects.php 14862) the run printed the same lines with other ids. On 2.9.25 the transport refuses the option before it creates anything:
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
setup() refused: The 'additional_subjects' option requires NATS Server >= 2.10, but
the connected server reports 2.9.25. Remove additional_subjects or upgrade NATS.
stream: no stream shop
A 2.9 server would accept filter_subjects without a word and ignore it, leaving the consumer reading the whole stream, so setup() checks the release of the server it is connected to first. On a leaf node with jetstream_domain that is the leaf node's release, not the hub's, the same rule our symfony-nats-messenger 5.14 post showed for stream_metadata.
Retries go back to the subject
The stamp itself is not sent with the message. So what does Symfony's retry do with a stamped message that failed? retry.php runs Symfony's own Worker with its retry listener, as messenger:consume wires them, over one stamped message whose handler fails on the first run:
<?php
// Symfony's Worker with its retry listener, as messenger:consume wires it, over one
// stamped message whose handler fails once. Run: php retry.php <port>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NatsMessenger\Stamp\NatsReceivedSubjectStamp;
use IDCT\NatsMessenger\Stamp\NatsSubjectStamp;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent;
use Symfony\Component\Messenger\Event\WorkerRunningEvent;
use Symfony\Component\Messenger\EventListener\SendFailedMessageForRetryListener;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Retry\MultiplierRetryStrategy;
use Symfony\Component\Messenger\Stamp\RedeliveryStamp;
use Symfony\Component\Messenger\Worker;
$port = (int) ($argv[1] ?? 14863);
versions();
fresh($port, 'shop');
$transport = transport(
$port,
'shop/shop.orders',
'consumer=worker&deduplicate=true&additional_subjects=shop.orders.updated.>',
);
$transport->setup();
$transport->send(new Envelope(
new OrderEvent('order 7 updated'),
[new NatsSubjectStamp('shop.orders.updated.7')],
));
// The handler fails on its first run and succeeds on the second.
$runs = 0;
$handledAt = null;
$handler = static function (OrderEvent $event) use (&$runs, &$handledAt): void {
if (++$runs === 1) {
out(" handler run $runs: fails");
throw new RuntimeException('the stock service did not answer');
}
out(" handler run $runs: handled $event->text");
$handledAt = microtime(true);
};
$bus = new MessageBus([
new HandleMessageMiddleware(new HandlersLocator([OrderEvent::class => [$handler]])),
]);
// The retry listener takes its sender and its strategy from service locators.
$locator = static fn (object $service): ContainerInterface => new class ($service)
implements ContainerInterface {
public function __construct(private readonly object $service)
{
}
public function get(string $id): object
{
return $this->service;
}
public function has(string $id): bool
{
return true;
}
};
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new SendFailedMessageForRetryListener(
$locator($transport),
$locator(new MultiplierRetryStrategy(3, 0)),
));
$dispatcher->addListener(
WorkerMessageReceivedEvent::class,
static function (WorkerMessageReceivedEvent $event): void {
$envelope = $event->getEnvelope();
out(sprintf(
'worker received "%s", retry count %d, on %s',
$envelope->getMessage()->text,
RedeliveryStamp::getRetryCountFromEnvelope($envelope),
$envelope->last(NatsReceivedSubjectStamp::class)?->subject,
));
},
);
// Stops one second after the message is handled, to see that nothing else arrives.
$until = microtime(true) + 10.0;
$dispatcher->addListener(
WorkerRunningEvent::class,
static function (WorkerRunningEvent $event) use (&$handledAt, $until): void {
$now = microtime(true);
if (($handledAt !== null && $now - $handledAt > 1.0) || $now > $until) {
$event->getWorker()->stop();
}
},
);
(new Worker(['async' => $transport], $bus, $dispatcher))->run(['sleep' => 0]);
echo "stored:\n";
foreach (stored($port, 'shop') as [$seq, $subject, $id]) {
out(" #$seq $subject");
out(" Nats-Msg-Id $id");
}
out('consumer: ' . consumer($port, 'shop', 'worker'));
$transport->close();
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
worker received "order 7 updated", retry count 0, on shop.orders.updated.7
handler run 1: fails
worker received "order 7 updated", retry count 1, on shop.orders.updated.7
handler run 2: handled order 7 updated
stored:
#1 shop.orders.updated.7
Nats-Msg-Id c7f88e61-2fb9-445c-8255-eaa084811444:shop.orders.updated.7:0
#2 shop.orders.updated.7
Nats-Msg-Id c7f88e61-2fb9-445c-8255-eaa084811444:shop.orders.updated.7:1
consumer: filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
The retry copy Symfony sent went to shop.orders.updated.7, the subject the message arrived on, not to the topic, and the second run handled it. The transport takes that subject from the NatsReceivedSubjectStamp that get() added: a Symfony retry, an envelope a worker received and re-sent with a retry count, goes back there. The copy's Nats-Msg-Id ends in :1, so JetStream keeps it apart from the original. With retry_handler=nats there is no copy at all, and NATS redelivers the original on its own subject. A copy for a failure transport goes to that transport's topic.
Delayed stamped messages
With scheduled_messages (NATS 2.12 and later), a delayed message waits on the stream as a schedule. A stamped one waits under the topic and is delivered to its stamped subject. delayed.php sends one with a DelayStamp of two seconds on 2.15.3:
<?php
// A delayed stamped message: Symfony's DelayStamp next to NatsSubjectStamp, with
// scheduled_messages on a server that has message schedules. Run: php delayed.php <port>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NatsMessenger\Stamp\NatsReceivedSubjectStamp;
use IDCT\NatsMessenger\Stamp\NatsSubjectStamp;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Stamp\DelayStamp;
$port = (int) ($argv[1] ?? 14863);
versions();
fresh($port, 'shop');
$transport = transport(
$port,
'shop/shop.orders',
'consumer=worker&scheduled_messages=true&additional_subjects=shop.orders.updated.>',
);
$transport->setup();
out('stream subjects: ' . streamSubjects($port, 'shop'));
$start = microtime(true);
$at = static fn (): string => sprintf('%4.1f s', microtime(true) - $start);
$transport->send(new Envelope(new OrderEvent('order 9 updated'), [
new NatsSubjectStamp('shop.orders.updated.9'),
new DelayStamp(2000),
]));
foreach (stored($port, 'shop') as [$seq, $subject]) {
$message = api($port, 'STREAM.MSG.GET.shop', ['seq' => $seq])['message'];
$headers = base64_decode($message['hdrs']);
preg_match_all('/^(Nats-Schedule[^:]*): *(.+?)\r?$/m', $headers, $m, PREG_SET_ORDER);
out(sprintf('%s stored #%d %s', $at(), $seq, $subject));
foreach ($m as [, $name, $value]) {
out(" $name: $value");
}
}
$until = $start + 6.0;
while (microtime(true) < $until) {
foreach ($transport->get() as $envelope) {
$transport->ack($envelope);
out(sprintf(
'%s received "%s" on %s',
$at(),
$envelope->getMessage()->text,
$envelope->last(NatsReceivedSubjectStamp::class)?->subject,
));
break 2;
}
}
foreach (stored($port, 'shop') as [$seq, $subject]) {
out(sprintf('%s stored #%d %s', $at(), $seq, $subject));
}
out('consumer: ' . consumer($port, 'shop', 'worker'));
$transport->close();
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
stream subjects: shop.orders, shop.orders.updated.>, shop.orders.delayed.>
0.0 s stored #1 shop.orders.delayed.3641f4ec-c55e-418c-9545-55942fdab80b
Nats-Schedule: @at 2026-12-03T08:19:43Z
Nats-Schedule-Target: shop.orders.updated.9
2.2 s received "order 9 updated" on shop.orders.updated.9
2.2 s stored #2 shop.orders.updated.9
consumer: filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
The schedule waits on shop.orders.delayed.<uuid>, so the stream needs one delayed pattern whatever the targets are, and Nats-Schedule-Target names the stamped subject. When it fired, the server stored the message on shop.orders.updated.9, where the consumer received it, and removed the schedule. The delay came out at a little over two seconds because a schedule's @at time has whole-second resolution and the transport rounds it up.
What the transport refuses
additional_subjects takes a comma-separated string or a list, and the transport checks the entries when it is built, before it connects. JetStream refuses a stream whose subjects overlap, so the transport refuses such an entry first, by name. entries.php builds a few configurations and makes a few stamps:
<?php
// What the transport refuses in additional_subjects when it is built, before it connects
// to anything, and what NatsSubjectStamp refuses when it is made. Run: php entries.php
declare(strict_types=1);
require __DIR__ . '/lib.php';
use IDCT\NatsMessenger\Options\NatsTransportConfigurationBuilder;
use IDCT\NatsMessenger\Stamp\NatsSubjectStamp;
$queries = [
'additional_subjects=shop.orders.updated.>',
'additional_subjects=shop.orders.updated.>,shop.refunds.*',
'additional_subjects[]=shop.orders.updated.>&additional_subjects[]=shop.orders.*.42',
'additional_subjects=shop.>',
'additional_subjects=shop.orders.>&scheduled_messages=true',
'additional_subjects=shop.orders.up*',
];
versions();
echo "topic shop.orders, DSN query:\n";
$last = null;
foreach ($queries as $query) {
try {
$config = (new NatsTransportConfigurationBuilder())
->build("nats-jetstream://127.0.0.1:14863/shop/shop.orders?$query");
$result = 'consumer filters [shop.orders, '
. implode(', ', $config->additionalSubjects()) . ']';
} catch (InvalidArgumentException $e) {
$result = $e->getMessage() === $last ? 'refused, the same message'
: 'refused: ' . $e->getMessage();
$last = $e->getMessage();
}
out(" $query");
out(" $result", ' ');
}
if (!class_exists(NatsSubjectStamp::class)) {
exit("no NatsSubjectStamp in this release\n");
}
echo "new NatsSubjectStamp(...):\n";
foreach (['shop.orders.updated.42', 'shop.orders.updated.*', 'shop..42', 'a b'] as $s) {
try {
new NatsSubjectStamp($s);
$result = 'made';
} catch (InvalidArgumentException $e) {
$result = 'refused: ' . $e->getMessage();
}
out(" '$s'");
out(" $result", ' ');
}
On 5.15.0:
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
topic shop.orders, DSN query:
additional_subjects=shop.orders.updated.>
consumer filters [shop.orders, shop.orders.updated.>]
additional_subjects=shop.orders.updated.>,shop.refunds.*
consumer filters [shop.orders, shop.orders.updated.>, shop.refunds.*]
additional_subjects[]=shop.orders.updated.>&additional_subjects[]=shop.orders.*.42
refused: The additional_subjects entry "shop.orders.*.42" overlaps the entry
"shop.orders.updated.>".
additional_subjects=shop.>
refused: The additional_subjects entry "shop.>" overlaps the topic.
additional_subjects=shop.orders.>&scheduled_messages=true
refused: The additional_subjects entry "shop.orders.>" overlaps
"shop.orders.delayed.>", the subjects scheduled messages wait on.
additional_subjects=shop.orders.up*
refused: The additional_subjects entry "shop.orders.up*" is not a subject
pattern: dot-separated tokens, none empty or with whitespace, with "*" only as a
whole token and ">" only as the last one.
new NatsSubjectStamp(...):
'shop.orders.updated.42'
made
'shop.orders.updated.*'
refused: A message cannot be published to "shop.orders.updated.*": a subject
is dot-separated tokens, none empty and none with the wildcards "*" or ">" in it.
'shop..42'
refused: A message cannot be published to "shop..42": a subject is
dot-separated tokens, none empty and none with the wildcards "*" or ">" in it.
'a b'
refused: A NATS subject must be a non-empty string without whitespace, "a b"
is not.
An entry may not overlap the topic, another entry or, with scheduled_messages, the shop.orders.delayed.> subjects schedules wait on, which a pattern such as shop.orders.> would match. The README's advice is to give the stamped subjects a token of their own, like updated. The stamp checks its subject when it is made, at dispatch: a wildcard, an empty token or whitespace would otherwise break the publish later. The same script on 5.14.0:
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
topic shop.orders, DSN query:
additional_subjects=shop.orders.updated.>
refused: Unknown option 'additional_subjects' in the DSN query of the NATS
transport. See "Configuration Options" in the README for the options it takes.
additional_subjects=shop.orders.updated.>,shop.refunds.*
refused, the same message
additional_subjects[]=shop.orders.updated.>&additional_subjects[]=shop.orders.*.42
refused, the same message
additional_subjects=shop.>
refused, the same message
additional_subjects=shop.orders.>&scheduled_messages=true
refused, the same message
additional_subjects=shop.orders.up*
refused, the same message
no NatsSubjectStamp in this release
5.14.0 does not know the option and refuses the whole transport. A rollback to 5.14.0 with additional_subjects still in the configuration leaves every transport that has it unable to start.
The two-step rollout, reproduced
The README's upgrade note is the part of this release we would read twice. A process of 5.14.0 or older that runs setup() writes the topic as the consumer's only filter. If stamped messages are published while the consumer is narrowed, and a worker reads past them, they are never delivered, and nothing reports an error. rollout.sh plays one bad deploy, one process per line, each in the install of its release:
#!/bin/sh
# 5.15.0 is deployed with additional_subjects while one 5.14.0 worker still runs, and the
# code that stamps messages goes out with the first deploy. One process per line, each in
# the install of its release: v5.14.0 and v5.15.0 side by side.
R=$(cd "$(dirname "$0")/.." && pwd)
(cd $R/v5.15.0 && php rollout.php fresh)
(cd $R/v5.15.0 && php rollout.php setup) # messenger:setup-transports of the new deploy
(cd $R/v5.14.0 && php rollout.php setup) # an old worker restarts and sets up
(cd $R/v5.15.0 && php rollout.php send) # new code stamps a message
(cd $R/v5.14.0 && php rollout.php work) # the old worker pulls
(cd $R/v5.15.0 && php rollout.php setup) # the new workers start
(cd $R/v5.15.0 && php rollout.php work)
(cd $R/v5.15.0 && php rollout.php state)
rollout.php holds the steps. Its 5.15.0 configuration lists the pattern; the 5.14.0 one cannot:
<?php
// The upgrade note of 5.15.0, one process per step. Each step runs in the install of the
// release rollout.sh names, with that release's configuration: 5.15.0 lists the pattern,
// 5.14.0 does not know the option. Run: php rollout.php <step>
declare(strict_types=1);
require __DIR__ . '/lib.php';
use Composer\InstalledVersions;
use IDCT\NatsMessenger\Stamp\NatsSubjectStamp;
use Symfony\Component\Messenger\Envelope;
const PORT = 14863;
$release = InstalledVersions::getPrettyVersion('idct/symfony-nats-messenger');
$query = str_starts_with($release, 'v5.14.')
? 'consumer=worker'
: 'consumer=worker&additional_subjects=shop.orders.updated.>';
$transport = transport(PORT, 'shop/shop.orders', $query);
$step = $argv[1] ?? '';
switch ($step) {
case 'fresh':
fresh(PORT, 'shop');
$what = streamSubjects(PORT, 'shop');
break;
case 'setup':
$transport->setup();
$what = consumer(PORT, 'shop', 'worker');
break;
case 'send':
$transport->send(new Envelope(
new OrderEvent('order 42 updated'),
[new NatsSubjectStamp('shop.orders.updated.42')],
));
$transport->send(new Envelope(new OrderEvent('order 43 placed')));
$what = 'sent "order 42 updated" stamped for shop.orders.updated.42, '
. 'then "order 43 placed"';
break;
case 'work':
$texts = array_map(
static fn (Envelope $envelope): string => $envelope->getMessage()->text,
receive($transport, 1.0),
);
$what = $texts === [] ? 'received nothing'
: 'received "' . implode('", "', $texts) . '"';
break;
case 'state':
$held = array_map(
static fn (array $message): string => "#$message[0] $message[1]",
stored(PORT, 'shop'),
);
$info = api(PORT, 'CONSUMER.INFO.shop.worker');
$what = 'the stream holds ' . implode(', ', $held)
. '; the consumer has delivered up to #' . $info['delivered']['stream_seq']
. ', ' . consumer(PORT, 'shop', 'worker');
break;
default:
exit("no step $step\n");
}
$transport->close();
out(sprintf('%s %-5s %s', $release, $step, $what));
v5.15.0 fresh no stream shop
v5.15.0 setup filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
v5.14.0 setup filter_subject shop.orders, num_pending 0
v5.15.0 send sent "order 42 updated" stamped for shop.orders.updated.42, then
"order 43 placed"
v5.14.0 work received "order 43 placed"
v5.15.0 setup filter_subjects [shop.orders, shop.orders.updated.>], num_pending 0
v5.15.0 work received nothing
v5.15.0 state the stream holds #1 shop.orders.updated.42, #2 shop.orders; the
consumer has delivered up to #2, filter_subjects [shop.orders,
shop.orders.updated.>], num_pending 0
The old worker's setup() put the consumer back on filter_subject shop.orders. The new code stamped order 42 updated, the old worker pulled and got only order 43 placed, and the consumer's position moved to #2. When the new workers set up, the filters were widened again, but a consumer does not go back: the stamped message is still in the stream as #1, num_pending is 0, and no worker will see it. That is what the README means by "never delivered, without any error". With auto_setup on, the narrowing does not even need a deploy script, since every old process runs setup() on its first send or pull.
The order the README gives:
- Deploy 5.15.0 with
additional_subjectseverywhere and make sure nothing older runssetup(). - Then deploy the code that stamps messages.
Back out in reverse: stop stamping, let the workers drain the patterns, take the option out, and only then roll back.
Without the option: a renamed topic is kept
One change shows on deployments that never use the new option. setup() now writes the union of the configured filters and those the live consumer already has, so a process whose configuration lacks a pattern cannot narrow the consumer (#111). That holds for the topic too. rename.php sets up a transport on billing.a, then one on billing.b with the same stream and consumer name, and then publishes one message to the old topic:
<?php
// The topic renamed in the DSN, the stream and the consumer name kept: setup() on
// billing.a, then on billing.b. Then one message to the old topic, billing.a.
// Run: php rename.php
declare(strict_types=1);
require __DIR__ . '/lib.php';
use Symfony\Component\Messenger\Envelope;
versions();
foreach (SERVERS as $release => $port) {
fresh($port, 'billing');
echo "nats-server $release\n";
foreach (['billing.a', 'billing.b'] as $topic) {
$transport = transport($port, "billing/$topic", 'consumer=worker');
$transport->setup();
$transport->close();
out(" setup() on $topic: " . consumer($port, 'billing', 'worker'));
}
$old = transport($port, 'billing/billing.a', 'consumer=other');
$old->send(new Envelope(new OrderEvent('invoice 9 paid')));
$old->close();
out(' one message to billing.a: ' . consumer($port, 'billing', 'worker'));
}
On 5.14.0:
symfony-nats-messenger v5.14.0, php-nats-jetstream-client v2.42.1
nats-server 2.9.25
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subject billing.b, num_pending 0
one message to billing.a: filter_subject billing.b, num_pending 0
nats-server 2.10.29
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subject billing.b, num_pending 0
one message to billing.a: filter_subject billing.b, num_pending 0
nats-server 2.15.3
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subject billing.b, num_pending 0
one message to billing.a: filter_subject billing.b, num_pending 0
On 5.15.0:
symfony-nats-messenger v5.15.0, php-nats-jetstream-client v2.42.1
nats-server 2.9.25
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subject billing.b, num_pending 0
one message to billing.a: filter_subject billing.b, num_pending 0
nats-server 2.10.29
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subjects [billing.b, billing.a], num_pending 0
one message to billing.a: filter_subjects [billing.b, billing.a], num_pending 1
nats-server 2.15.3
setup() on billing.a: filter_subject billing.a, num_pending 0
setup() on billing.b: filter_subjects [billing.b, billing.a], num_pending 0
one message to billing.a: filter_subjects [billing.b, billing.a], num_pending 1
On NATS 2.10 and later, 5.14.0 replaced the old topic and 5.15.0 adds the new one beside it, so the consumer keeps reading billing.a: the message published there is pending for the renamed transport. That is what you want while the old topic drains, and a surprise if you expected the rename to cut it off. The old filter stays until you remove it with nats consumer edit. A 2.9 server still gets the topic alone, as before, because its consumer can hold one filter only.
Patterns work the same way. Removing one from the configuration removes nothing from the consumer or the stream: the README says to drain it first, then take it off the consumer with nats consumer edit and off the stream with nats stream edit. The transport cannot do it for you, since on a stream several transports share it cannot tell its own old pattern from a subject someone else needs. A new pattern that overlaps one the stream still has is refused by the server at the stream update, and setup() changes nothing.
Upgrading
composer update idct/symfony-nats-messenger
The client floor stays at php-nats-jetstream-client 2.39.1. Then, from the README's upgrade section and our runs:
- Without
additional_subjects, messages keep theirNats-Msg-Idand go where they went. The one change is thatsetup()keeps the filters an existing consumer has, so a renamed topic is added on NATS 2.10 and later instead of replacing the old one. - With it, the server needs 2.10 or later, and on a leaf node with
jetstream_domainthe leaf node's release decides. - Roll it out in two steps: the option first, with nothing older running
setup(), then the code that stamps. - Give the stamped subjects a token of their own, such as
shop.orders.updated.>, so they overlap neither the topic nor the delayed subjects. - Before a rollback to 5.14.0, stop stamping, drain, and take
additional_subjectsout of the configuration: 5.14.0 refuses a transport with an option it does not know.
How it is tested
The README now counts 1956 unit tests at about 99.8% coverage and a mutation score of 98.6%. The feature has its own Behat file, nats_subjects.feature, with seven scenarios against a live server: one consumer reading the topic and a stamped subject, a delayed stamped message delivered once to its subject, Symfony's retry keeping the subject, a stamped message routed to two transports handled once by each, and three on the filters of an existing consumer (widened, kept, and not replayed). The repository's own examples/per-message-subjects.php covers the order of delivery and the retry, and shows the refusal on a server before 2.10. The record of the pull request lists what the review measured by hand on nats-server 2.9.25, 2.10.29 and 2.15.3.
Two smaller changes come with the release. The two connectIfNeeded() calls in front of the scheduled_messages check have tests that fail again when either call is deleted (#203). And CI's time caps are raised (#178): the test job may run 50 minutes instead of 40, after the PHP 8.5 leg hit its 40-minute cap in 10 of 26 runs since 30 November.
Get it
- Source and issues: symfony-nats-messenger on GitHub, with the v5.15.0 release notes and pull request #100.
- Install:
composer require idct/symfony-nats-messenger, from Packagist. - Our symfony-nats-messenger software page lists what it does and what it needs.