A page that shows data is a snapshot. An editor saves a node, a queue worker finishes a report, a colleague opens the same form, and the page in front of you does not know. The usual answers are a reload button or a timer that polls an endpoint. Both work, and both make every component solve the same problem again.
sdx_realtime is our answer for SDX sites. It starts from something Drupal already does well: it knows exactly which cache tags a change invalidates. In this article we turn those invalidations into live updates, push our own events from PHP, and add WebSocket channels with presence so editors can see who else has a node open. The examples use sdx_realtime 1.0.0-alpha9, its latest tag, with SDX 1.0.0-alpha18.
Three modules, three jobs
The project is three submodules you can enable separately. sdx_broadcast pushes events one way, from server to browser, over Server-Sent Events. sdx_websocket runs a WebSocket server for two-way channels and presence. sdx_reactive runs PHP-driven components; we covered it in reactive components in Drupal without writing JavaScript, so this article is about the other two.
composer require drupal/sdx_realtime
drush en sdx_broadcast sdx_websocket
drush sdx:resolve
drush cset sdx_broadcast.settings broadcast_cache_tags 1
drush sdx:resolve picks up the modules' new SDX manifests, and React components that use the hooks below are built with the rest of your SDX components (drush sdx:build). The last line switches on the feature this article leads with; it is off by default.
Cache tags as the event source
sdx_broadcast decorates Drupal's cache_tags.invalidator service. Every invalidation, whether from an entity save, a config change, or your own code, still reaches Drupal's own invalidator. With broadcast_cache_tags on, each tag is also published as an invalidate event on one SSE channel called cache-tags. The browser keeps a single shared connection to that channel per page, and each component filters for the tags it cares about.
Two settings in sdx_broadcast.settings control what leaves the server. broadcast_cache_tags is the switch. cache_tags_blocklist drops tags before they are published, matching either exactly or by prefix when the pattern ends in *. The default list is user:*, user_list, session, permissions:*, and config:user.role.*.
Subscribing needs one more step. On the built-in SSE stream, channel access is deny-by-default: only user.{uid} (for its owner), __global, and entity.{type} are open without help, and cache-tags is not among them. One hook opens it, on that stream and in the Mercure hub's subscriber token alike:
<?php
/**
* @file
* Hook implementations for my_module.
*/
use Drupal\Core\Session\AccountInterface;
/**
* Implements hook_sdx_broadcast_subscriber_topics_alter().
*/
function my_module_sdx_broadcast_subscriber_topics_alter(array &$topics, AccountInterface $account): void {
$topics[] = \Drupal::service('sdx_broadcast.subscriber_scope')->topicFor('cache-tags');
}
topicFor() turns the channel name into the topic string the transports compare against, so the configured topic prefix is respected. This grants the channel to every visitor, which suits public content. If the tags on your site say more than you want to share, narrow the grant here by checking $account.
A component that refreshes itself
Take an event page with a badge that says how many seats are left, read from an integer field field_seats_left. The badge is a React component, my_module:seats-badge, declared like any SDX component (sdx: framework: react and an entry file in its component.yml, with nid and seatsLeft as props). Its props come from a DataProvider: a class next to the component, discovered by its #[SdxComponentDataProvider] attribute.
<?php
declare(strict_types=1);
namespace Drupal\my_module\Component;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\sdx\Attribute\SdxComponentDataProvider;
use Drupal\sdx\DataProvider\ComponentDataProviderBase;
use Drupal\sdx\DataProvider\ResolveContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
#[SdxComponentDataProvider(component: 'my_module:seats-badge')]
final class SeatsBadge extends ComponentDataProviderBase {
public function __construct(array $configuration, $plugin_id, $plugin_definition, private readonly EntityTypeManagerInterface $entityTypeManager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container->get('entity_type.manager'));
}
public function resolve(ResolveContext $ctx): array {
$node = $this->entityTypeManager->getStorage('node')->load((int) ($ctx->incomingProps['nid'] ?? 0));
if ($node === NULL) {
return ['seatsLeft' => NULL];
}
$access = $node->access('view', NULL, TRUE);
$ctx->cacheMetadata->addCacheableDependency($access)->addCacheableDependency($node);
return ['seatsLeft' => $access->isAllowed() ? (int) $node->get('field_seats_left')->value : NULL];
}
}
The file lives at my_module/components/seats-badge/SeatsBadge.php. The parent passes nid; the provider adds seatsLeft and declares the node as a cache dependency, so Drupal's render cache is already correct. Live updates add one thing: an endpoint that returns the same props as JSON, in the {"props": {...}} shape the live hook reads.
<?php
declare(strict_types=1);
namespace Drupal\my_module\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
final class SeatsController extends ControllerBase {
public function props(NodeInterface $node): CacheableJsonResponse {
$response = new CacheableJsonResponse([
'props' => [
'nid' => (int) $node->id(),
'seatsLeft' => (int) $node->get('field_seats_left')->value,
],
]);
$response->addCacheableDependency($node);
return $response;
}
}
Register it in my_module.routing.yml at /my-module/seats/{node}, with _entity_access: 'node.view' as its requirement so the endpoint applies the same access as the page. Because the response carries the node as a cache dependency, it can be cached and is invalidated by the same node:{nid} tag that triggers the refresh. The component itself:
import { useLiveDataProvider } from '@sdx/live-data-provider/react';
import { formatPlural, t } from '@sdx/runtime';
interface SeatsBadgeProps {
nid: number;
seatsLeft: number | null;
}
const SeatsBadge = (props: SeatsBadgeProps) => {
const live = useLiveDataProvider<SeatsBadgeProps>(props, {
tags: [`node:${props.nid}`],
refetchUrl: `/my-module/seats/${props.nid}`,
});
if (live.seatsLeft === null) {
return null;
}
return (
<p className="seats-badge">
{live.seatsLeft > 0
? formatPlural(live.seatsLeft, '1 seat left', '@count seats left')
: t('Fully booked')}
</p>
);
};
export default SeatsBadge;
The hook renders the server's props first. When node:42 is invalidated anywhere, it fetches refetchUrl and swaps in the returned props. A failed fetch keeps the previous value. Underneath, the hook uses useCacheTags(tags, onInvalidate) from @sdx/cache-tags/react, which you can call directly when you want something other than a refetch. For any other channel there is useBroadcast(channel, onEvent) from @sdx/broadcast/react. Vue and Svelte versions of all three use the same aliases, ending in /vue and /svelte.
Sending your own events from PHP
Not every change is a cache tag. For events of your own, inject the sdx_broadcast.broadcaster service. Here a queue worker tells a user that their report is ready:
<?php
declare(strict_types=1);
namespace Drupal\my_module\Plugin\QueueWorker;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\Attribute\QueueWorker;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\sdx_broadcast\Service\BroadcastService;
use Symfony\Component\DependencyInjection\ContainerInterface;
#[QueueWorker(
id: 'my_module_report',
title: new TranslatableMarkup('Report builder'),
cron: ['time' => 60],
)]
final class ReportWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {
public function __construct(array $configuration, $plugin_id, $plugin_definition, private readonly BroadcastService $broadcaster) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
return new static($configuration, $plugin_id, $plugin_definition, $container->get('sdx_broadcast.broadcaster'));
}
public function processItem($data): void {
// The report is built and stored above this line.
$this->broadcaster->broadcastToUser((int) $data['uid'], 'report.ready', [
'reportId' => (int) $data['report_id'],
]);
}
}
broadcastToUser() publishes on user.{uid}, the user's own channel. In the browser, useBroadcast(`user.${uid}`, (event, data) => …) receives it. The service also has broadcast($channel, $event, $data) for channels of your own (grant them with hook_sdx_broadcast_channel_access()) and broadcastToAll(), which uses the public __global channel. Publishing works from any context: web requests, cron, queue workers, and Drush.
Entity changes come for free. With auto_broadcast_entities on, which is the default, inserts, updates, and deletes are published on entity.{type} as created, updated, or deleted, carrying only the id and bundle. Unpublished entities and entities anonymous users cannot view are skipped.
Channels and presence over WebSockets
SSE is one-way. When browsers need to talk to each other, sdx_websocket adds a WebSocket server written in plain PHP. It runs as its own process, started with drush sdx:ws, and listens on port 8090 by default (--port changes it). In production you keep it running under your process manager and put it behind the site's web server; ws_path and external_url in sdx_websocket.settings tell the browser where to connect.
Authentication rides on Drupal's session without sharing it. On every page, the module gives the browser a short-lived token for the current user, signed on the server. The browser sends it with the handshake, and the server rejects missing, altered, or expired tokens. From then on, identity comes from the token, never from message content: the server adds a sender with uid and name to every message it relays. Origins are checked too; an empty allowed_origins means the site's own host only.
The React hooks ship with SDX's sdx_react module. Here is a notice for the node edit form that lists who else has it open:
import { usePresence } from '@sdx/presence';
import { t } from '@sdx/runtime';
interface EditingNowProps {
nid: number;
uid: number;
}
const EditingNow = ({ nid, uid }: EditingNowProps) => {
const { users, connected } = usePresence(`node.${nid}.editing`);
const others = users.filter((user) => user.uid !== uid);
if (!connected || others.length === 0) {
return null;
}
return (
<p className="editing-now" role="status">
{t('Also editing: @names', { '@names': others.map((user) => user.name).join(', ') })}
</p>
);
};
export default EditingNow;
Mounting the component joins the channel; the server then pushes the full list of present users on every join and leave. Read that list as "joined recently": at this tag the server forgets a user about a minute after they joined, even while they stay connected, so the next list it pushes leaves them out. The block that places it passes the node id and the current user's id, and adds the user cache context. To exchange messages on the same channel, useChannel(channel, { onMessage }) returns send and connected; the server relays each message to every other subscriber.
Deciding who may join
On the WebSocket server, give every channel you use an explicit access rule instead of relying on the defaults. Two hooks do the work. Both run inside the long-running drush sdx:ws process, whose in-memory caches do not see changes made by other requests, so restart it after deploying code and after changing roles or permissions:
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
/**
* Implements hook_sdx_websocket_channel_access().
*/
function my_module_sdx_websocket_channel_access(string $channel, int $uid): ?bool {
if (!preg_match('/^node\.(\d+)\.editing$/', $channel, $match)) {
return NULL;
}
$account = User::load($uid);
$node = Node::load((int) $match[1]);
return $account !== NULL && $node !== NULL && $node->access('update', $account);
}
/**
* Implements hook_sdx_websocket_message_alter().
*/
function my_module_sdx_websocket_message_alter(?array &$message, array $context): void {
// Editing channels relay focus notices and nothing else.
if (str_ends_with($context['channel'], '.editing') && ($message['action'] ?? NULL) !== 'focus') {
$message = NULL;
}
}
Returning FALSE from the access hook denies; NULL abstains. In the alter hook, setting the message to NULL stops the relay, and changing it changes what subscribers receive.
Limits worth planning for
Realtime features lean on parts of the stack that ordinary pages barely use. We plan for these.
- The built-in transport is for small loads. The default
in_processtransport serves SSE from PHP-FPM, so every open stream holds a worker untilstream_timeout(30 seconds by default) ends it and the browser reconnects. The module's own guidance puts its ceiling around 50 simultaneous subscribers. It also reads and then deletes a channel's queued events, so when several browsers listen on one channel, each event reaches the stream that reads it first. Use it in development. - Mercure for production, with care. Set
transporttomercureand run a Mercure hub, which delivers events without holding PHP workers. The JWT secrets must be at least 32 bytes, and the default cookie authentication expects the hub on the site's own origin. We use it for data every visitor may see, such as live counters. The hub also receives entity events during the save, before Drupal commits it and clears the cache, so an immediate refetch can still read the old value. - Proxies and edges must not buffer. The stream sends
X-Accel-Buffering: noandCache-Control: no-cache, and a heartbeat comment every 15 seconds. Any CDN, WAF, or load balancer in front of the site still needs to pass/api/sdx-broadcast/stream/(or the hub path) through unbuffered, uncached, and with an idle timeout longer than the heartbeat. Otherwise events arrive late and in clumps. - Connections add up. A page opens one EventSource per channel, shared by every component on it, plus one WebSocket. Browsers cap open connections per origin over HTTP/1.1, and every tab counts, so serve the site over HTTP/2. The WebSocket server is a single process that stops accepting new connections at
max_connections(100 by default). - Every listener refetches at once. When a popular node changes, every open page that watches its tag fetches the endpoint together. Keep that endpoint cacheable, as the controller above is.
- Presence is per user. A user with two tabs open appears once, and closing one tab removes them.
- Tokens are short-lived. The handshake token is valid for five minutes, and at this tag the browser reconnects with the token the page was rendered with. A tab older than that which loses its connection stays offline until it is reloaded. Pages served from Drupal's page cache do not get a fresh token, so keep WebSocket features on pages for signed-in users.
One rule matters more than the rest: decide what never goes on the wire. __global and entity.* are public by design. The cache-tags channel sends every tag that is not blocklisted to everyone you granted it to, and tag names carry ids and config names, including ids of content that is not published yet. Extend cache_tags_blocklist for anything whose existence is sensitive. In your own events, send ids and let the browser fetch details through a route that checks access. Personal data, tokens, and anything a user could not see on the page do not belong in a payload.
Planned this way, a Drupal site keeps its pages current without a reload, and each component gets live data from one small hook. The modules are on the sdx_realtime project page. If you want realtime features on a site you run, or a second pair of eyes on the infrastructure in front of it, get in touch.
