Broadcasting
Broadcasting is how php-via pushes updates to multiple clients at once. When a user's action should change what everyone sees (not just themselves), you broadcast to a scope.
The basics
Call $app->broadcast(scope) after modifying shared state. Every context registered
in that scope will re-render its view and push the update via SSE:
$increment = $c->action(function (Context $c) use ($app, $counter): void {
$newVal = $app->incrementGlobalState('shared_counter');
$counter->setValue($newVal);
// Push to everyone on this route
$app->broadcast(Scope::routeScope('/'));
}, 'increment');Scope targets
You can broadcast to any scope string:
// All connected clients everywhere
$app->broadcast(Scope::GLOBAL);
// All clients on a specific route (a bare Scope::ROUTE throws here)
$app->broadcast(Scope::routeScope('/dashboard'));
// A custom scope (e.g. a chat room)
$app->broadcast('room:lobby');
// Equivalent shorthand when inside a context:
$c->broadcast(); // broadcasts to $c's primary scopeAuto-broadcast on scoped signals
Scoped signals auto-broadcast when setValue() is called. You don't always need
an explicit broadcast(). The auto-broadcast fires to the signal's scope:
// This signal is ROUTE-scoped. setValue() and increment() auto-broadcast to route:/
$shared = $c->signal(0, 'count', Scope::routeScope('/'));
$c->action(function (Context $c) use ($shared): void {
$shared->increment();
// No explicit broadcast needed: auto-broadcast fires for Scope::routeScope('/')
}, 'inc');
An action that writes several scoped signals, or writes them and also calls broadcast(),
still re-renders each client once. See the next section.
When the update is sent
Actions, timers, SSE hooks and broker messages all run in a coroutine. There, broadcast()
only marks the scope. The worker's next flush re-renders every marked scope once and publishes it to
other workers and nodes once. A client in several marked scopes renders once. Outside a coroutine, for
example in a CLI script, and while the worker shuts down, broadcast() renders before it
returns.
A flush runs at the end of the current event-loop turn when the worker's last flush started at least one broadcast tick ago and ended at least half a tick ago, so on a quiet server the update goes out at once. Otherwise it runs as soon as both have passed, and every broadcast in between shares it. The tick is 25 ms by default. The re-rendering a worker does per second then depends on its clients and the tick, not on how many actions arrive: flushes whose views render for F milliseconds without waiting on I/O use at most F / 25 of the worker up to F = 12.5, and F / (F + 12.5) above that. After every flush the worker has at least half a tick for requests, timers and I/O, so slow flushes slow requests down but cannot starve them. Under load, clients skip intermediate frames and still end on the latest state. Broadcasts received from other workers and nodes go through the same flush.
Flushes of different scopes run side by side, so a view that waits on a slow database query delays only its own scope. A scope broadcast while its fan-out is still running is rendered by the first flush after that fan-out ends. When a later broadcast finds a fan-out that has been running for over a second, the worker logs a warning naming the scope. When two flushes render the same tab and the one that started first finishes last, it renders the tab again, so the tab ends on the newer state after a brief step back.
$config = (new Config())
->withBroadcastTickMs(50); // fewer, larger flushes under load; 0 flushes every event-loop turn with no gap
Each worker counts its flushes in $app->getStats()->getBroadcastStats(), also shown
under broadcast_stats in the dev-mode /_stats endpoint: broadcasts scheduled
and coalesced, flushes, the last, longest and total flush time, and flush_overruns, the
flushes that took longer than the tick. Flush times are wall time, including time the views spend
waiting on I/O while the worker does other work. When the views do not wait on I/O, flushes longer
than the tick mean the worker spends more than two thirds of its time in them under sustained load,
so climbing overruns are the signal to raise the tick or make the views cheaper.
What this means for your code:
- Views render the state as it is when the fan-out runs. Ten broadcasts in one action send one frame with all ten changes, as long as the action does not wait on I/O between them: a database call in between lets the flush run and send a half-updated frame. Write first and broadcast last.
- If an action sets a value, broadcasts and then changes the value back, clients never see it.
Call
$app->flushBroadcasts()before changing it back. - Patches the action queues itself, such as
execScript()or$c->sync(), reach the tab before the broadcast's frame. CallflushBroadcasts()first when the script needs the new DOM. - The action's HTTP response does not wait for the fan-out to every client, so a
data-indicatorcan clear before the new frame arrives. - With
worker_num > 1, a flush reads each scoped signal from shared memory once and reuses the value for every tab it renders. A view that computes a new value from one, such assetValue($s->int() + 1), computes it from that value, so useincrement()ormutate()there.
$send = $c->action(function (Context $c) use ($app): void {
$app->mutateGlobalState('messages', fn (?array $m) => [...$m ?? [], $c->input('text')]);
$app->broadcast('room:lobby');
// Render the new message everywhere now, then scroll this tab to it.
$app->flushBroadcasts();
$c->execScript('document.querySelector("#messages").lastElementChild.scrollIntoView()');
}, 'send');
When another flush is already rendering room:lobby, flushBroadcasts() waits for
it and then renders the new message. It waits at most one second: past that it logs a warning and
returns, and the message's frame follows on a later flush, after the script.
To render and publish on every call instead, as earlier releases did, turn coalescing off:
(new Config())->withBroadcastCoalescing(false). There is no tick then, except under
sustained load: a broadcast that finds its scope's fan-out running makes that fan-out render once more
when it ends, and when other actions keep that going for 8 passes in a row, the rest goes to a flush
paced by the tick, so the action that started the fan-out can return. These flushes count under
flushes in broadcast_stats, while scheduled stays 0.
In both modes, a view that broadcasts its own scope while it renders, directly or from a coroutine it starts, makes its fan-out render again. When it does that in 8 passes in a row, the fan-out stops and the worker logs "Broadcast re-entrancy limit reached" with the scope's name.
Two more warnings point at views. "Broadcast chain limit reached" means views broadcast each other's scopes in a loop; the chain stops after 8 flushes. "The fan-out of scope ... has been running for" means a broadcast found that scope's fan-out still rendering after more than a second, which usually means a view is blocked on I/O.
Broadcasting on connect and disconnect
Use onClientConnect / onClientDisconnect app-level hooks to broadcast
whenever a client joins or leaves. This replaces polling timers for presence features:
// Broadcast to the route when occupancy changes: presence counter stays live
$app->onClientConnect(fn(Context $c) => $app->broadcast(Scope::routeScope($c->getRoute())));
$app->onClientDisconnect(fn(Context $c) => $app->broadcast(Scope::routeScope($c->getRoute())));See Lifecycle for full details on connect/disconnect hooks.
Combining global state and broadcast
Use setGlobalState to store shared data in process memory, then broadcast to re-render
all clients with the new value. The standard multiplayer pattern:
// Initialize once
$app->setGlobalState('messages', []);
// In an action:
$send = $c->action(function (Context $c) use ($app): void {
$msg = ['user' => substr($c->getId(), -4), 'text' => (string) $c->input('text', '')];
$app->mutateGlobalState('messages', fn (?array $msgs) => array_slice([...$msgs ?? [], $msg], -50)); // keep last 50
$app->broadcast(Scope::routeScope('/chat'));
}, 'send');
Multi-worker note. With withWorkerNum(>1), GlobalState is backed
by an OpenSwoole\Table shared across all workers. Values are PHP-serialized
before storage; the default column size is 32 KB per value and keys are at most 63 characters.
Read-then-write loses updates when two workers do it at once, so append with
mutateGlobalState() rather than globalState() plus setGlobalState().
For large values (deep arrays, long strings), increase the limit with
Config::withGlobalStateTableSize(int $maxRows, int $maxValueBytes) before calling
start(). An \OverflowException is thrown at write time if a value
exceeds the configured size. For high-frequency or large shared data, prefer scoped signals
with explicit broadcast() over GlobalState.
Next steps
- Scopes: understanding scope types and targets
- Lifecycle: connect/disconnect hooks and timers
- Actions: server-side handlers that trigger broadcasts
- Multi-node broker: fan out broadcasts across servers with Redis or NATS
- API: broadcast(): method signature
- API: flushBroadcasts(): run scheduled broadcasts now