Symfony 8.2 Messenger 的 --concurrency:每個類別首則訊息的成本
Messenger --concurrency in Symfony 8.2: What the First Message of Every Class Costs You
Symfony 8.2 的並行 Worker 會把每個 bus、transport 和訊息類別組合的首則訊息當作探測,以判斷處理程序是否使用批次處理。8.2.0-BETA2 的探測會暫停整個 Worker,而且每次重啟都要重新探測;修正於 2026 年 11 月 23 日合併,並隨 8.2.0-RC1 推出,將暫停範圍限制在正在探測的類別。
You upgraded to Symfony 8.2, replaced four messenger:consume processes with one --concurrency=4, and the dashboard looks better: one connection to the broker instead of four, one process to supervise. Then a deploy restarts the worker, and for a minute the short messages that used to take half a second sit in the queue while three of the four children do nothing.
The cause is a design decision in the new parallel worker. It cannot know whether a handler batches until it has run one message of that class, so the first message of every bus, transport and class combination runs alone, as a probe. On 8.2.0-BETA2 the probe paused consumption for the whole worker, and what the probe learned lived in the memory of the parent process, so every restart paid it again. A fix merged on 23 November 2026 and shipped in 8.2.0-RC1 scopes the pause to the probed class. The probe itself stays, and so does a cost worth understanding before you size a pool.
This article walks through how --concurrency schedules work, why the probe exists, what it cost on BETA2 and what it costs after the fix, with a reproduction you can run in ten minutes. Then it covers the decisions that follow: which messages get their own transport, how long a worker should live, and when --concurrency is the wrong tool.
Prerequisites
- PHP 8.4 (tested on 8.4.22)
-
symfony/messenger8.2.0-BETA2 for the worker-wide pause, 8.2.0-RC1 for the fixed behaviour -
amphp/parallel, which--concurrencyrequires, andsymfony/runtime, which the children use to boot -
symfony/doctrine-messengerwith a SQLite database as the async transport; any transport works, the parent is the only process that talks to it - no
ext-parallel; with it the children are threads instead of processes and the scheduling is the same
1. One fetcher, N children, one strategy
A worker without --concurrency fetches a message and handles it in the same process. With --concurrency=N the Worker keeps the fetching and hands each envelope to a ParallelExecutionStrategy, which owns a pool of up to N amphp workers. Each child is a separate PHP process that boots your application through bin/console (DispatchTask::bootstrap() requires the file and asks symfony/runtime for the container), then loops: receive an envelope over a channel, dispatch it on the bus, send the handled envelope back. The parent acks or rejects on the transport when the answer arrives.
Two things follow from this shape. The parent is the only connection to the transport, which is the point of the feature. And fetching plus unserializing is not parallel, which is why Nicolas Grekas, who wrote the feature in symfony/symfony PR #63650, notes that it is "unfavorable for very short tasks". His own measurement in that PR, 192 plain messages of 20 ms each on 24 cores with warm workers, gives 3.73x at --concurrency=4 and 7.52x at 8.
The strategy decides which child gets a message with an affinity key:
// Symfony\Component\Messenger\Execution\ParallelExecutionStrategy, 8.2
private function getAffinityKey(Envelope $envelope): string
{
return ($envelope->last(BusNameStamp::class)?->getBusName() ?? 'message.bus')
.'|'.($envelope->last(ReceivedStamp::class)?->getTransportName() ?? '')
.'|'.$envelope->getMessage()::class;
}
Bus, transport and message class. For a key the strategy knows as non-batching, any idle child will do. For a key it knows as batching, the message goes to the child that already holds the batch, busy or not, because a batch handler accumulates state in the memory of one child and flushing it from another child is impossible. That is the pin, and it is the reason batch handlers do not parallelize within one message class: the PR's table shows a single batching class at 0.98x whatever the concurrency, two classes at 2.00x.
2. The probe, and what it cost on BETA2
The pin needs a fact the strategy does not have when it sees a class for the first time: does its handler batch? A batch handler leaves a NoAutoAckStamp on the envelope and acks later, when its batch flushes, and the child reports that as a DeferredEnvelopeMessage instead of a handled envelope. The strategy learns that a class batches at that moment and not before. Until then, spreading five messages of that class across four children could strand a batch on a child that never gets the sixth.
So the first message of an unknown key runs as a probe. On BETA2 the whole worker waited for it:
// 8.2.0-BETA2
private ?int $pendingProbeRequestId = null;
public function shouldPauseConsumption(): bool
{
return null !== $this->pendingProbeRequestId
|| \count($this->busyChannels) >= $this->concurrencyLimit;
}
Worker::run() checks shouldPauseConsumption() after every message it hands over. When it returns true, the envelopes already fetched stay in a buffer and the loop waits for a child to answer. With --fetch-size defaulting to --concurrency, a cold worker fetched four messages, gave the first one to a child as the probe, and buffered the other three until that one child came back. If the first message was a report that takes a minute, the other three children idled for a minute, and so did every message behind them on the transport, whatever its class.
The second half of the cost is where the answer is stored. $keyModes is an array on the strategy, which lives in the parent process. A worker that stops on --time-limit, --memory-limit, a deploy or a crash starts with an empty array. Every class probes again, and the worker is paused again for the duration of each class's first message, one class after another. Nothing in the documentation mentions the probe; it says that batch-handled messages go to the same child, which is the consequence, not the mechanism.
3. Reproducing it
The reproduction is a skeleton application with three messages and no batch handler at all, so every probe ends the same way, with the key learned as non-batching, and the cost is pure waiting:
#[AsMessageHandler]
final class SlowMessageHandler
{
public function __invoke(SlowMessage $message): void
{
sleep($message->seconds);
}
}
#[AsMessageHandler]
final class FastMessageHandler
{
public function __invoke(FastMessage $message): void
{
usleep(500_000);
}
}
#[AsMessageHandler]
final class PingHandler
{
public function __invoke(Ping $ping): void
{
$wait = microtime(true) - $ping->dispatchedAt;
file_put_contents(__DIR__.'/../../var/ping-waits.log', sprintf("%.3f\n", $wait), FILE_APPEND);
}
}
Ping carries its dispatch time, so its handler records how long the message waited in the queue. That number is what a user of a latency-sensitive message feels. All three are routed to one Doctrine transport on SQLite, and every scenario starts a fresh worker on an empty queue, so the probe runs.
Scenario 1: four slow messages of one class
Four SlowMessage(10) and messenger:consume async --concurrency=4 --limit=4.
| Version | Wall time | Timeline |
|---|---|---|
| 8.2.0-BETA2 | 21.9 s | probe from 1.0 s to 11.0 s, then three in parallel until 21.9 s |
| 8.2.0-RC1 | 21.8 s | probe from 0.8 s to 10.8 s, held siblings dispatched at 11.2 s to 11.8 s, done at 21.8 s |
The fix changes nothing here, and that is by design: the three other messages share the probed key, so they are held until the probe completes. Four messages of one class on a cold worker take two rounds, before and after the fix. The first second is the child booting the kernel.
One measurement trap on the way: with --limit=4 the fixed strategy finished in 11.8 s, because the limit stops the worker as soon as it has taken its four messages, and a stopping worker releases what it holds (flush(true)), so all four ran in parallel. That is the shutdown path, not the scheduling. Use --time-limit to measure.
Scenario 2: one slow class ahead of two fast ones
One SlowMessage(10), then three FastMessage, then three Ping, --concurrency=4 --limit=7.
| Version | Messages done | Ping waits |
|---|---|---|
| 8.2.0-BETA2 | 12.8 s | 13,174 ms, 13,175 ms, 13,175 ms |
| 8.2.0-RC1 | 11.1 s | 3,949 ms, 3,950 ms, 3,952 ms |
This is the case the fix was written for. On BETA2 the three pings sat behind the ten-second probe of a class they have nothing to do with, then behind the probe of FastMessage, then their own. On RC1 they waited for the FastMessage probe and their own, about four seconds, while the slow message ran on another child. Four seconds is still not zero: every class pays its probe, one class after another, and a ping dispatched before the worker starts is behind all of them.
Scenario 3: the mixed load from the bug report
The issue that led to the fix, symfony/symfony#68311, describes a transport that mixes an LLM-backed job of several minutes with short messages and a latency-sensitive one every few seconds. Scaled down to a run of a few minutes: one SlowMessage(60), five SlowMessage(3), twenty FastMessage, and a Ping dispatched every five seconds for ninety seconds from a second process, all consumed by a worker started cold with --concurrency=4. Then the same load again against the same worker, now warm.
| Version | Cold worker, average wait | Cold, max | Warm worker, average wait | Warm, max |
|---|---|---|---|---|
| 8.2.0-BETA2 | 25,238 ms | 67,253 ms | 12,151 ms | 44,056 ms |
| 8.2.0-RC1 | 25,390 ms | 67,812 ms | 11,493 ms | 43,862 ms |
Eighteen pings per phase. Cold, thirteen of them waited behind the sixty-second message, from 67 seconds for the first down to 2 seconds for the last, on both versions. The fix did not change the cold phase, and the worker log says why: the five SlowMessage(3) share the affinity key of the SlowMessage(60) probe, so they are held, and held messages count against the concurrency limit. One probe plus three held messages is four slots, shouldPauseConsumption() is true, and the parent fetches nothing until the probe completes at 62 seconds. The RC1 log shows a SlowMessage received at 2.0 s and the next line at 62.1 s.
That is the sharpest cost left after the fix. A class whose first message is slow and whose next messages are already queued fills the pool with its own held messages, and the whole worker waits as before. The fix helps when the slow class arrives alone, as in scenario 2. It does not help when the slow class arrives in a burst of --concurrency or more.
The warm numbers are dominated by a second problem that has nothing to do with the probe, covered in section 7, and they are reported here because that is what we measured.
4. What the fix changed
symfony/symfony PR #68313, merged on 23 November 2026 and released in 8.2.0-RC1 two days later, keeps the probe and removes the worker-wide pause. The probe is now tracked per key, and the messages of a key whose probe is in flight are held by the strategy instead of blocking the fetch loop:
// symfony/messenger 8.2.0-RC1
/** @var array<string, int> The request id of the probe in flight, by affinity key */
private array $pendingProbeRequests = [];
/** @var array<string, list<array{Envelope, string, callable}>> Messages held until the probe of their key completes */
private array $heldRequests = [];
public function execute(Envelope $envelope, string $transportName, callable $onHandled): void
{
// ...
$affinityKey = $this->getAffinityKey($envelope);
$keyMode = $this->keyModes[$affinityKey] ?? null;
if (!$this->releasingHeldRequests && null === $keyMode && isset($this->pendingProbeRequests[$affinityKey])) {
// a probe is learning whether this key batches: the message joins its siblings
// and is dispatched when the probe completes
$this->heldRequests[$affinityKey][] = [$envelope, $transportName, $onHandled];
return;
}
// ...
}
public function shouldPauseConsumption(): bool
{
// held messages occupy the slot of the worker they wait for, like busy ones do
return \count($this->busyChannels) + $this->countHeldRequests() >= $this->concurrencyLimit;
}
When the probe answers, releaseHeldRequests() re-executes the held messages in arrival order. If the probe deferred, the key is now batching and they go to the pinned child one after another. If it completed, they are spread over idle children like any other message. Held messages count against the concurrency limit, so the parent cannot buffer an unbounded queue behind a slow probe, and a worker that stops releases what it holds instead of leaving it unacked. The three new tests in ParallelExecutionStrategyTest fail on BETA2 and describe the contract in their names: a probe does not pause consumption of other keys, messages of a probed key are held until its probe defers, held messages count towards the concurrency limit.
5. What the first message still costs
The fix changes who waits, not whether anyone does. Four costs remain, and they are worth knowing when you size a pool.
The probed class waits for itself. Messages of the probed key are held until the probe completes, whatever the children are doing. If ReportMessage takes a minute and ten of them arrive on a cold worker, the second to the tenth start after the first finishes, then spread over the children. The probe can only end sooner if the handler defers earlier, which a plain handler never does.
The answer still dies with the process. $keyModes is still an array in the parent. Every restart, planned or not, probes every class again. The first message of each class after a restart is the slow one, and now only its own class pays. A worker with --time-limit=3600 probes each class once an hour; one with --time-limit=60 does it once a minute. With a class whose handler runs for longer than the time limit, the probe is the only message of that class the worker will ever run alone, and the next worker probes again. Set the time limit from the longest handler you route to that worker, not from habit.
A burst of the probed class fills the pool. Held messages occupy a slot each, so with --concurrency=4 a probe plus three queued messages of the same class pauses the fetch loop for the duration of the probe, as scenario 3 shows. The PR takes that trade-off deliberately, so the parent cannot buffer an unbounded queue behind a slow probe. The practical consequence is that the class most likely to have a slow first message, a report or an import that arrives in batches, is the class the fix helps least.
The children boot too. Each child requires bin/console and builds the container before its first message. That is the same cost as starting one more messenger:consume, paid N times per restart, and it adds to the probe on a cold worker because the probe's child boots first. A warm pool does not pay it; a child replaced after reaching --memory-limit pays it once, without a new probe.
6. Decisions
Give latency-sensitive messages their own worker, not only their own transport. The affinity key includes the transport, so on RC1 a Ping on async_fast is never held by a probe on async. It is still fetched by the same parent, and scenario 3 shows that parent pausing when a slow class arrives in a burst. On BETA2 the pause was per worker in every case. So the separation that holds on both versions is a second messenger:consume for the fast transport. A message that must be handled within a second has no business sharing a worker with one that takes a minute, and that was true before --concurrency existed.
Pick --concurrency from the number of distinct keys in flight when handlers batch. The PR's table is the whole argument: one batching class gains nothing from any concurrency, two classes cap at 2x. For a transport that carries one batching class, several workers remain the way to parallelize.
Keep the parent alive as long as you safely can. A restart of the parent costs a probe per class and a boot per child. --time-limit stops the parent. --memory-limit is enforced in the parent and in every child: a child that crosses it after a message stops, and the strategy replaces it with a fresh one, which costs a boot but no probe, because the answers live in the parent. For leaky handlers that is the limit to rely on; the time limit should come from the slowest handler, as above.
Do not use --concurrency for very short messages. Fetching and unserializing stays in the parent, and the handled envelope travels back over a channel. For a handler that takes two milliseconds, the round trip is the work. Several plain workers scale that case; --concurrency scales the case where the handler, not the transport, is the bottleneck.
Upgrade past BETA2 before you turn it on. The worker-wide pause is the kind of cost that only shows on a restart with a slow message at the head of the queue, which is to say in production on deploy day. The fix is in 8.2.0-RC1 and every later 8.2 release.
7. A second cost that is not the probe: the parent blocks on a busy child
In the warm phase of scenario 3, on both versions, the parent fetched nothing for about fifty seconds while one child was inside the sixty-second handler and the other three were idle. Every key was known by then, so the probe was not involved. The minimal form of it is one slow message alone on a warm worker, with a ping every five seconds:
ping waits (ms): 717, 390, 34, 44359, 38982, 33574, 28210, 22815, 17439, 12088, 6707, 1318, 984, 636
The cause is in flush(). The idle loop of Worker::run() calls flush(false) and flush(30.0) on every pass, and flush() sends a FlushBatchHandlersMessage to every channel with a pending request, including the channel of a child that is inside a handler. That child does not read its channel until the handler returns. Each flush waits in the socket buffer, and once the buffer is full the next $channel->send() suspends the parent until the child reads. An amphp worker inside sleep() accepts 29 sends of 100 bytes on macOS; the 30th blocks until the sleep ends. At two flushes per idle second that is about fifteen seconds into any handler. Instrumented, 42 sends to the busy channel took 0.000 s and the 43rd took 47.678 s.
The fix is a condition in flush(): a timed flush skips the busy channels, since a child inside a handler cannot act on a flush before the handler returns anyway, and a child holding a batch is never busy. A forced flush, which stops the worker, still reaches every child. With it, the same run gives:
ping waits (ms): 722, 385, 45, 708, 379, 1024, 690, 318, 995, 680, 345, 985, 988, 655
This one is still in 8.2.0-RC1. The fix is open as symfony/symfony#68459 against 8.2, so until it is merged, a child inside a handler longer than about fifteen seconds stops the parent's fetch loop for the rest of that handler, whatever the other children are doing.
Conclusion
--concurrency moves the parallelism from N processes polling a broker to one process and N children, and it needs one piece of information it can only learn at runtime: whether a class batches. The probe is how it learns, and the probe is why the first message of every class after every restart runs alone. On 8.2.0-BETA2 it ran alone with the whole worker waiting; from the fix of 23 November it runs alone with its own class waiting. In the reproduction, a ping behind a slow probe of another class waited 13.2 s on BETA2 and 3.9 s on RC1; a ping behind a slow probe whose class had three more messages queued waited 67 s on both.
If you adopt it: separate the slow classes from the fast ones by transport, set the time limit from the slowest handler, and measure a cold restart and a long handler next to short ones, because those are the two moments where the parent stops fetching.
Source Code: You can find the full implementation and follow the project's progress on GitHub: https://github.com/mattleads/messenger-concurrency-probe
Let's Connect!
If you found this helpful or have questions about the implementation, I'd love to hear from you. Let's stay in touch and keep the conversation going across these platforms:
- LinkedIn: https://www.linkedin.com/in/matthew-mochalkin/
- X (Twitter): https://x.com/MattLeads
- Telegram: https://t.me/MattLeads
- GitHub: https://github.com/mattleads
來源:DEV Community · dev.to