Events, webhooks and subscriptions
What this is. How Exponential tells other systems what happened to content: the event journal, every event kind and its payload, signed webhooks (with retries, the job queue, ordering, idempotency and replay), and GraphQL subscriptions over Server-Sent Events and WebSockets.
When to use it. When a front end must drop cached pages after a publish, a static site must rebuild, a search index or a shop must follow content, or a dashboard must show changes live.
Quick example: a webhook to a revalidation route, and its receiver.
./console exp:graphql:webhooks --add=front --url=https://front.example.com/api/revalidate \
--events=publish,update,trash,delete,move,hide,reveal --siteaccess=site --apply
# prints the signing secret once: put it into the receiver's environment as EXPONENTIAL_WEBHOOK_SECRET
./console exp:graphql:webhooks --test=front --apply # sends a ping now// a route of any framework that hands you a Web Request (Next.js, Remix, Hono, Workers ...)
import { createWebhookReceiver, webhookResponse } from '@exponentialcms/client';
const receive = createWebhookReceiver({
secret: process.env.EXPONENTIAL_WEBHOOK_SECRET!,
invalidate: async (tags) => { for (const tag of tags) await purgeTag(tag); },
});
export async function POST(request: Request) {
return webhookResponse(await receive(request)); // 204 when done; 401 bad signature; 413 too large
}Contents
- The event journal
- Event kinds
- The event record
- Events of packages
- Events during migrations
- Webhooks: how they work
- Setting up a webhook
- The request a receiver gets
- Verifying the signature
- Retries and giving up
- Ordering
- Idempotency
- Replay
- Delivery by the job queue (expqueue)
- Operating webhooks
- Subscriptions
- Privacy
- Troubleshooting
- Settings
The event journal
Every change to content is written to the event journal: one JSON line per event in
var/<site>/graphql/events/events-<generation>.jsonl. Webhooks and subscriptions both read it; neither ever runs
inside the request that changed content.
- Where events come from. The kernel calls
expGraphQLEventListenerwherever content changes, in every process: a web request of the administration, a GraphQL mutation, a REST call, a console command, a cronjob, a queue worker, a migration. - When they are written. At the end of the request, after the database transaction: the notes of the request become records and are appended in one write, under an exclusive file lock. A change rolled back writes nothing; a failure to write is logged and never reaches the editor.
- When the journal is written at all. Only while somebody listens: the API is switched on in some siteaccess, and
Subscriptions=enabledor a webhook is configured. An installation without listeners writes no journal. - Files, not a table. A reader follows the journal without a database connection (a subscription that waits for minutes must not hold one), and every PHP-FPM and Velocity worker sees the same events.
- Rotation. A file grows to
JournalMaxBytes(5 MB), then the next generation starts; the newestJournalKeep(3) files stay. A reader further behind than the oldest file kept goes on from the oldest one (and the webhooks report the loss aslost). - Positions.
<generation>.<byte offset>(1.734211) is where the next read starts. It is theid:of each event in a subscription stream (what a client sends back asLast-Event-ID) and the webhooks' cursor.
How long events are kept depends on traffic: 3 files of 5 MB hold roughly 15 MB of events, about 30 000 to 50 000
events. On a busy site raise JournalMaxBytes or JournalKeep so a webhook receiver that is down for a day does
not miss events.
Event kinds
| Kind | When | Content | content of a subscription |
|---|---|---|---|
publish | the first version of an object is published | the object, its locations and parents | the content now |
update | a later version is published (an edit, a new translation) | as publish, version is the new one | the content now |
trash | the object goes to the trash (every location removed) | the object; locations may be empty, see below | null |
delete | the object is removed for good | as trash | null |
move | a location moves to another parent | oldParentNodeId, newParentNodeId, nodeIds the moved location | the content now |
hide | a location is hidden | nodeIds the hidden location | the content now (if readable) |
reveal | a hidden location is revealed | nodeIds the revealed location | the content now |
mutation | a GraphQL mutation succeeded (also a package's mutation), or a migration's summary | mutation names it (createContent, newsletterUnsubscribed, migration) | the content now |
clear | the content caches were cleared as a whole | no object; data.scope is content or graphql | null |
ping | a webhook test (--test, the Test button); never in the journal | no object | |
<package>.<name> | an event a package registers (newsletter.subscription.confirmed) | the fields the kind declares in data |
A mutation writes two events: the content event it caused (publish, move ...) and a mutation event naming
the mutation. Receivers that purge caches can ignore mutation.
Which kinds a receiver gets. A webhook without Events[], or contentEvents without events, gets the kernel's
kinds publish, update, trash, delete, move, hide, reveal, mutation. clear and the kinds of packages
are sent only to receivers that name them (Events[]=clear, Events[]=newsletter.*): older receivers never asked
for them.
Known limitation (6.0.15): trash events without locations. A trash event, and most delete events, carry
empty nodeIds and parentNodeIds (and mainNodeId 0): the locations are already gone when the object is
described. Purge by c<objectId>, which drops every cached answer that showed the object (lists that showed it carry
its c tag too). Lists that did not show it (a later page, a totalCount) need a TTL or the parent's pl tag from
your own records. See Cache tags and invalidation.
The event record
What receivers get (a webhook's data.contentEvent, a subscription's ContentEvent), always with every key:
| Field | Type | Meaning |
|---|---|---|
id | string | the event's id: <microseconds since 1970>-<8 hex> (1796376216010281-d9f6e3ce); the same in every webhook and subscription |
event | string | the kind |
time | string | ISO 8601 UTC with milliseconds (2026-12-04T09:15:02.120Z) |
objectId | int or null | the content object |
remoteId | string or null | its remote id |
version | int or null | the version published |
classIdentifier | string or null | its class |
name | string or null | its name at that moment |
language | string or null | the language of the version (its initial language) |
languages | string[] | its translations |
nodeIds | int[] | its locations (a move, hide or reveal: the one it happened to) |
mainNodeId | int or null | its main location (0 when gone) |
parentNodeIds | int[] | the parents of its locations |
oldParentNodeId, newParentNodeId | int or null | a move: before and after |
mutation | string or null | the GraphQL mutation, or migration for a migration's summary |
migration | string or null | the id of the migration that made the change |
objectIds | int[] | a migration's summary: the objects it changed (at most 1000) |
data | object | a package event's declared fields; clear: {"scope": "content"}; absent for the kernel's other kinds |
What the journal stores (version 1 of the line format, "v": 1): the fields above with time as a Unix time
with milliseconds (1796376216.01), and also classId, sectionId, ownerId, userId (who made the change),
siteaccess (where), stateIds and pathStrings. These extra fields are used for filtering (subscriptions, webhook
filters) and are not sent to receivers. A record is at most a few hundred bytes; a package event's data at most 8 KB.
{"v":1,"id":"1795074820716196-f3145aa2","event":"move","time":1795074820.716,"objectId":57,"version":1,"classId":46,
"sectionId":3,"ownerId":14,"mainNodeId":59,"userId":10,"oldParentNodeId":12,"newParentNodeId":14,"nodeIds":[59],
"parentNodeIds":[43],"stateIds":[1,80,83],"remoteId":"media-o-components","classIdentifier":"ng_container",
"language":"eng-US","languages":["eng-US"],"pathStrings":["/1/43/59/"]}The line format only grows: new optional fields may be added; existing ones keep their name, type and meaning (see Compatibility and upgrades).
Events of packages
An extension adds event kinds of its own through a schema extension that implements expGraphQLEventExtension:
public function eventKinds()
{
return array(
'newsletter.subscription.confirmed' => array(
'description' => 'A subscription to a newsletter list was confirmed.',
'object' => true, // bound to a content object: who may read it hears it
'policy' => array( 'newsletter', 'index' ), // or null; with a policy only unlimited access hears it
'fields' => array( 'listId' => 'int', 'status' => 'string' ), // int, string, bool, int[], string[]
),
);
}and notes each event with expGraphQLEventListener::packageEvent( $kind, array( 'listId' => 18830, 'status' => 'confirmed' ), $objectId ). Rules the kernel enforces: at least two dot-separated segments of lower-case letters and
digits, at most 64 characters, object and/or policy, at most 20 fields; only declared fields of the declared type
are kept; at most 8 KB of data. In the GraphQL enum ContentEventKind a package kind is spelled with underscores
(newsletter_subscription_confirmed). ./console exp:graphql:status lists the registered kinds and refused
declarations. The fields are the review point that keeps personal data out of the journal: ids and states only, never
addresses, names or free text.
Events during migrations
A migration's header events: decides what its changes write:
| Mode | Events |
|---|---|
each (default) | every change its own event, with migration set to the migration's id |
summary | no event per change; one mutation event at the end with mutation: "migration", objectIds and nodeIds (at most 1000 each) |
none | nothing |
A migration that failed and was rolled back drops its notes when they were not written yet. Use summary for bulk
imports, so a webhook receiver gets one event instead of ten thousand, and purge broadly (ez-all) on it.
Webhooks: how they work
journal ──► cron part graphqlwebhooks (frequent group) ┌─► your end point (2xx = delivered)
1. read events from cursor.json │
2. for every end point that wants an event: a delivery ────┤ outbox/<delivery>-<name>.json (default)
3. send due deliveries, oldest first, BatchSize per run │ or a job graphql.webhook (Delivery=queue)
4. failure: next try after the backoff; after MaxAttempts: failed/
every attempt: one line in deliveries.jsonl- The cron part
graphqlwebhooksis in thefrequentgroup; the delay between a publish and its webhook is the interval of that group (run it on its own every minute for faster delivery:php runcronjobs.php -q graphqlwebhooks)../console exp:graphql:webhooks --deliver --applydoes the same by hand. - One run at a time (a lock file); a second run at the same moment does nothing.
- A new end point gets what happens after it was set up: the first run starts at the end of the journal.
- Files under
var/<site>/graphql/webhooks/:cursor.json({"position":"1.734211","time":...}),outbox/,failed/,deliveries.jsonl(the log),deliver.lock.
Setting up a webhook
# a dry run: shows the change to settings/override/graphql.ini.append.php
./console exp:graphql:webhooks --add=front --url=https://front.example.com/api/revalidate --events=publish,update,trash
# write it, make the signing secret and show it once
./console exp:graphql:webhooks --add=front --url=https://front.example.com/api/revalidate \
--events=publish,update,trash,delete,move,hide,reveal --classes=ng_article,ng_recipe --siteaccess=site --apply
./console exp:graphql:webhooks # the list: state, waiting, given up
./console exp:graphql:webhooks --test=front --apply # a ping, now
./console exp:graphql:webhooks --remove=front --apply # and its signing secretOr in Setup > GraphQL, section Webhooks (policy graphql/administrate), which also shows the last deliveries.
Either way the end point becomes settings:
[GraphQLWebhooks]
EndpointList[]=front
[GraphQLWebhook_front]
URL=https://front.example.com/api/revalidate
Events[]=publish
Events[]=update
Events[]=trash
SiteAccessList[]=site
ClassList[]=ng_article
SubtreeList[]=2
Secret=graphql.webhook.front
Payload=event
Delivery=outbox
Enabled=enabled| Key | Default | Meaning |
|---|---|---|
URL | https:// (or http://, for a receiver on the same network), with a host, without a user or password; redirects are not followed | |
Events[] | every kernel kind but clear | kinds, package kinds, or namespaces (shop.*); an unknown package kind is a warning, still sent |
SiteAccessList[] | every siteaccess | only content below the root node of these siteaccesses (content.ini [NodeSettings] RootNode), in their languages (SiteLanguageList[]) |
ClassList[] | every class | only these class identifiers |
SubtreeList[] | the whole tree | only content at or below these nodes |
Secret | graphql.webhook.<name> | the name of the signing secret in the secret store (Setup > Secrets), or env:VARIABLE |
Payload | event | event: the event; query: the answer of a persisted query |
Query | with Payload=query: the persisted query's name or SHA-256 | |
QueryUser | anonymous | with Payload=query: the login the query runs as |
Delivery | outbox | queue: one expqueue job per delivery |
Enabled | enabled | disabled keeps the end point but sends nothing |
An event without a content object (clear, some package events) never reaches an end point that filters by
siteaccess, class or subtree, except clear when named.
Payload=query sends the answer of a persisted query instead of the bare event, so the receiver gets everything
it needs in one request (a search indexer, a shop). The query runs as QueryUser with the variables objectId,
nodeId (the main location), version, language and event; declare those you use:
# queries/article_for_index.graphql, stored with: ./console exp:graphql:persist queries/ --apply
query ArticleForIndex($objectId: Int!, $language: String) {
content(id: $objectId, language: $language) {
id remoteId name url published modified classIdentifier languages
... on ng_article { title full_intro { text } body { text } }
}
}./console exp:graphql:webhooks --add=search --url=https://search.example.com/hook --payload=query \
--query=article_for_index --as=indexer --classes=ng_article --applyThe body is then {"data": {"content": {...}}, "extensions": {"schema": "exp-graphql-webhook/1", "webhook": "search", "delivery": "...", "attempt": 1, "event": {...the event...}}}. For a trash or delete event content is null:
remove the document by extensions.event.objectId.
The signing secret is never in a settings file, a log or a page after it was made: --add makes 32 random bytes
(64 hexadecimal characters), keeps them encrypted in the kernel's secret store under
the name of Secret, and shows them once. Secret=env:FRONT_HOOK_SECRET reads an environment variable of the PHP
process instead. To change a secret, set a new value in Setup > Secrets and on the receiver (see
Rotating a signing secret).
The request a receiver gets
POST with Content-Type: application/json; charset=UTF-8 and User-Agent: Exponential-GraphQL-Webhooks/1:
{"data":{"contentEvent":{"id":"1796376216010281-d9f6e3ce","event":"publish","time":"2026-12-04T09:23:36.010Z",
"objectId":312,"remoteId":"8f2c4b1e...","version":1,"classIdentifier":"ng_article","name":"Ten minutes a day",
"language":"eng-US","languages":["eng-US"],"nodeIds":[868],"mainNodeId":868,"parentNodeIds":[556],
"oldParentNodeId":null,"newParentNodeId":null,"mutation":null,"migration":null,"objectIds":[]}},
"extensions":{"schema":"exp-graphql-webhook/1","webhook":"front","delivery":"1796376240004112-c41d9e02","attempt":1}}| Header | Meaning |
|---|---|
X-Exponential-Webhook | the end point's name |
X-Exponential-Event | the kind (publish, ping ...) |
X-Exponential-Event-Id | the event's id (the same for every end point) |
X-Exponential-Delivery | the delivery's id (one per end point and event, the same over its retries) |
X-Exponential-Timestamp | Unix seconds when this attempt was signed |
X-Exponential-Signature | sha256=<hex of HMAC-SHA-256(secret, timestamp + "." + body)> |
extensions.attempt counts the tries (1 for the first). A ping has event: "ping" and every content field null
or empty.
Answer with any 2xx within Timeout seconds (10). The body of your answer is ignored. Anything else, a
redirect, a timeout or a connection error is a failed attempt. Do the work after answering (a queue of your own) when
it takes longer than a few seconds.
Verifying the signature
Verify over the raw bytes of the body, exactly as received (never a parsed and re-serialized JSON), compare in constant time, and refuse a timestamp more than 300 seconds away from now (a recorded request cannot be replayed later).
SDK (Web Crypto; Node.js 20+, Deno, Bun, Workers):
import { verifyWebhook, tagsForEvent, type WebhookPayload } from '@exponentialcms/client';
export async function POST(request: Request): Promise<Response> {
const body = await request.text();
const check = await verifyWebhook({
secret: process.env.EXPONENTIAL_WEBHOOK_SECRET!,
timestamp: request.headers.get('X-Exponential-Timestamp'),
signature: request.headers.get('X-Exponential-Signature'),
body,
});
if (!check.ok) return new Response(check.reason, { status: 401 }); // missing, stale_timestamp, bad_signature
const payload = JSON.parse(body) as WebhookPayload;
for (const tag of tagsForEvent(payload.data.contentEvent)) await purgeTag(tag);
return new Response(null, { status: 204 });
}createWebhookReceiver({ secret, invalidate, tagPrefix?, onEvent?, toleranceSeconds?, rememberDeliveries?, maxBodyBytes? }) does all of it: POST only, the body read up to maxBodyBytes (1 MB; larger: 413), the signature
over the bytes as sent, repeated deliveries dropped (the last 1000 remembered), the tags of tagsForEvent() passed to
invalidate.
Node.js with Express (no SDK):
import express from 'express';
import crypto from 'node:crypto';
const app = express();
app.post('/api/revalidate', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => {
const secret = process.env.EXPONENTIAL_WEBHOOK_SECRET;
const ts = req.get('X-Exponential-Timestamp') ?? '';
const given = req.get('X-Exponential-Signature') ?? '';
const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(`${ts}.`).update(req.body).digest('hex');
const fresh = /^\d+$/.test(ts) && Math.abs(Date.now() / 1000 - Number(ts)) <= 300;
const same = given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
if (!fresh || !same) return res.sendStatus(401);
const { data } = JSON.parse(req.body.toString('utf8'));
res.sendStatus(204); // answer first ...
queueMicrotask(() => handle(data.contentEvent, req.get('X-Exponential-Delivery'))); // ... then work
});
app.listen(3000);PHP (any framework; plain PHP shown):
$secret = getenv( 'EXPONENTIAL_WEBHOOK_SECRET' );
$body = file_get_contents( 'php://input' );
$ts = $_SERVER['HTTP_X_EXPONENTIAL_TIMESTAMP'] ?? '';
$given = $_SERVER['HTTP_X_EXPONENTIAL_SIGNATURE'] ?? '';
$expected = 'sha256=' . hash_hmac( 'sha256', $ts . '.' . $body, $secret );
if ( !ctype_digit( $ts ) || abs( time() - (int)$ts ) > 300 || !hash_equals( $expected, $given ) )
{
http_response_code( 401 );
exit;
}
$payload = json_decode( $body, true );
$event = $payload['data']['contentEvent'] ?? $payload['extensions']['event']; // Payload=event or Payload=query
http_response_code( 204 );
// ... purge, index, enqueue: $event['event'], $event['objectId'], $event['nodeIds'] ...Inside an Exponential installation: expGraphQLWebhooks::verify( $secret, $timestamp, $body, $signature ) returns ''
when valid, else stale_timestamp or bad_signature.
Python (Flask):
import hashlib, hmac, os, time
from flask import Flask, request, abort
app = Flask(__name__)
('/api/revalidate')
def revalidate():
body = request.get_data() # raw bytes
ts = request.headers.get('X-Exponential-Timestamp', '')
given = request.headers.get('X-Exponential-Signature', '')
expected = 'sha256=' + hmac.new(os.environ['EXPONENTIAL_WEBHOOK_SECRET'].encode(), ts.encode() + b'.' + body, hashlib.sha256).hexdigest()
if not ts.isdigit() or abs(time.time() - int(ts)) > 300 or not hmac.compare_digest(expected, given):
abort(401)
event = request.get_json()['data']['contentEvent']
return '', 204Clocks. The timestamp check needs both servers' clocks within a few seconds (NTP). A retry is signed anew with a new timestamp, so a delivery that waited an hour in the outbox still verifies.
Rotating a signing secret
The installation signs with one secret per end point; there is no overlap period on the sending side. To rotate without losing deliveries:
- Make the receiver accept two secrets (the current and the next): valid if either matches.
- Set the new value in Setup > Secrets (name
graphql.webhook.<name>), or change the environment variable ofSecret=env:.... - After the outbox is empty and an hour has passed, remove the old secret from the receiver.
Retries and giving up
A failed attempt is tried again after RetryBackoff seconds (30), doubled after each failure, at most MaxBackoff
(3600), at most MaxAttempts (8) attempts in all:
| Attempt | Waits before it | About this long after the first |
|---|---|---|
| 1 | 0 | |
| 2 | 30 s | 30 s |
| 3 | 60 s | 1.5 min |
| 4 | 120 s | 3.5 min |
| 5 | 240 s | 7.5 min |
| 6 | 480 s | 15.5 min |
| 7 | 960 s | 31.5 min |
| 8 | 1920 s | 63.5 min |
The times are lower bounds: an attempt is made by the next run of the cron part after it is due. After the last
failure the delivery moves to var/<site>/graphql/webhooks/failed/ and the log says gave-up. A delivery whose end
point was removed from the settings gives up at once.
Raise MaxAttempts (and MaxBackoff) when a receiver may be down longer: with MaxAttempts=12 and MaxBackoff=3600
deliveries are tried for about five hours.
Ordering
- Events are written to the journal in the order the requests ended (two editors publishing at once: the request that finished first is first).
- Deliveries are queued in journal order and sent oldest first in each run.
- A retry breaks order. While delivery A waits for its retry, a later delivery B to the same end point can be sent and succeed. Your receiver must not assume order.
- Between end points there is no order.
- Subscriptions get events in journal order while connected.
Make receivers order-independent: on every event, read the current state (the content now, content { ... } of a
subscription, a Payload=query answer, or a query of your own) instead of applying the event as a diff. For a purge,
order does not matter at all.
Idempotency
Delivery is at least once: a receiver can get the same delivery twice (it answered 2xx but the answer was lost,
or it timed out after doing the work).
| Id | Same for | Use it to |
|---|---|---|
X-Exponential-Delivery (extensions.delivery) | one event to one end point, over all its retries | drop a repeated delivery |
X-Exponential-Event-Id (data.contentEvent.id) | one event, in every end point and subscription | drop an event that reached you by two end points |
Keep the ids you have handled for at least a day (the retries span about an hour; a replay may come later): a
Set in memory for a purge receiver (the SDK remembers the last 1000), a table with a unique key for a receiver that
writes:
CREATE TABLE exponential_deliveries ( delivery_id VARCHAR(64) PRIMARY KEY, received_at TIMESTAMP NOT NULL );
-- INSERT ... ; on a duplicate-key error: answer 204 and do nothingReplay
| What to replay | How |
|---|---|
| Deliveries that gave up | after fixing the receiver: move their files from failed/ back to outbox/ with attempts 0 and next 0 (below), then exp:graphql:webhooks --deliver --apply |
| Everything since a point in time, for every end point | set the webhooks' cursor back to a position (below); every event since then is queued again to every end point that wants it |
| A subscription after a disconnect | the client sends Last-Event-ID (the SDK and EventSource do it by themselves) |
Dead jobs of Delivery=queue | Setup > Job queue, or ./console ext:expqueue:retry --dead |
| A full resynchronization | do not replay: walk the content with cursor pagination and rebuild the receiver's state |
Back up var/<site>/graphql/webhooks/ before you touch it, and stop the cron part while you do (or run it by hand
afterwards).
Deliveries that gave up, as the site user (one file per delivery, <delivery id>-<end point>.json):
cd /path/to/installation/var/site/graphql/webhooks
for f in failed/*.json; do
jq '.attempts = 0 | .next = 0 | .lastStatus = null | .lastError = null' "$f" > "outbox/$(basename "$f")" && mv "$f" "$f.replayed"
done
cd /path/to/installation && ./console exp:graphql:webhooks --deliver --applyFrom a position of the journal. Positions are <generation>.<byte offset> of events/events-<generation>.jsonl;
0 is the start of a file. To queue again every event since the start of generation 3:
cd /path/to/installation/var/site/graphql/webhooks
cp cursor.json cursor.json.before-replay
printf '{"position":"3.0","time":%s}\n' "$(date +%s)" > cursor.json
cd /path/to/installation && ./console exp:graphql:webhooks --deliver --applyOnly events still in the journal (the newest JournalKeep files) can be replayed. Every end point gets them again,
so this is only safe with idempotent receivers.
Delivery by the job queue (expqueue)
With Delivery=queue (--delivery=queue), each delivery is a job of the job queue extension
expqueue instead of a file of the outbox, while expqueue is active and its
tables are installed:
- one job of the type
graphql.webhook(kernelsettings/expqueue.ini: classeditorial,Timeout=60) per delivery, keyed by the delivery id (queued twice, it is one job); - the resource
graphql-webhook:<name>, so[QueueResource_graphql-webhook:<name>] MaxConcurrent=<n>inexpqueue.inilimits how many requests go to one receiver at once; - the same body, signature, headers and log line as the outbox; a failed try is retried no sooner than the end
point's backoff, at most
MaxAttempts; the last failure goes to the queue's dead letter (Setup > Job queue), where it can be retried by hand; - sent by the queue's workers on whichever node runs one, never by the cron part, never inside a web request; the job carries the event, never the secret;
- when expqueue is not active, or refuses a job (a quota), the delivery goes to the outbox as before.
Run workers by cron (php runcronjobs.php -q expqueue every minute), by hand (./console ext:expqueue:work), or as a
systemd service (./console ext:expqueue:service install). Watch them with ./console ext:expqueue:status and
./console ext:expqueue:list --state=dead.
Choose the queue when you have several receivers that must not slow each other down, when you want a dead letter with a retry button, or when several nodes should share the sending.
Operating webhooks
./console exp:graphql:webhooks # end points, state, waiting, given up, the last delivery
./console exp:graphql:webhooks --format=json
./console exp:graphql:webhooks --log --limit=50 # the delivery log
./console exp:graphql:webhooks --test=front --apply # exit code 1 when not answered with 2xxA line of deliveries.jsonl (kept as deliveries.1.jsonl past LogMaxBytes, 1 MB):
{"time":1796376240,"delivery":"1796376240004112-c41d9e02","endpoint":"front","event":"publish","eventId":"1796376216010281-d9f6e3ce","objectId":312,"attempt":1,"status":204,"ms":87,"result":"sent","error":null}result is sent, retry or gave-up; error the reason (HTTP 500, a cURL error, the signing secret ... is not set (Setup > Secrets)). Never a body or a secret.
Monitor: the number of files in outbox/ (a growing outbox means the cron part does not run or a receiver is
down), new files in failed/, and gave-up lines in the log. See Operations, "Monitoring".
Subscriptions
A subscription keeps a connection open and receives each matching event, as the subscriber may read it, as it happens.
subscription Articles {
contentPublished(classes: ["ng_article"], subtreeId: 89) {
id event time objectId version language
content { name url ... on ng_article { title } }
}
}| Root field | Events | Arguments |
|---|---|---|
contentEvents | those of events: [ContentEventKind!] (none: every kernel kind but clear; package kinds only when named) | events, classes, parentId (directly below), subtreeId (at or anywhere below) |
contentPublished | publish, update | classes, parentId, subtreeId |
contentUpdated | update | the same |
contentDeleted | trash, delete (content is null) | the same |
contentMoved | move | the same |
contentHidden | hide, reveal | the same |
One subscription asks for exactly one root field ("A subscription asks for exactly one field.", VALIDATION).
Transports.
| Transport | Where | Protocol |
|---|---|---|
| Server-Sent Events | POST (or GET) /api/graphql/subscribe with Accept: text/event-stream, under PHP-FPM and Velocity | graphql-sse, "distinct connections" mode |
| WebSocket | through Velocity only | graphql-transport-ws; Velocity's WebSocket bridge opens the SSE stream for each subscription, so every rule here applies |
The stream, with curl (a key with graphql:read):
curl -N -s "$EXP/api/graphql/subscribe" -H "Authorization: Bearer $KEY" -H 'Accept: text/event-stream' \
-H 'Content-Type: application/json' \
-d '{"query":"subscription { contentPublished(classes: [\"ng_article\"]) { id event objectId content { name url } } }"}': heartbeat
event: next
id: 1.734211
data: {"data":{"contentPublished":{"id":"1796376216010281-d9f6e3ce","event":"publish","objectId":312,"content":{"name":"Ten minutes a day","url":"https://www.example.com/fitness/ten-minutes-a-day"}}}}
: heartbeat
id: 1.735002
event: complete
data:- Each event is
event: nextwithid:(the journal position after it) and the GraphQL answer asdata:. - A comment (
: heartbeat) everySubscriptionHeartbeatseconds (15) keeps proxies from closing the stream and finds clients that left; it may carry anid:when the stream skipped events the subscriber may not read, so a resume never sees them again. - The stream ends after
SubscriptionMaxDurationseconds (280) orSubscriptionIdleTimeoutseconds without an event (0: off). The client reconnects withLast-Event-ID: <last id>(orlastEventIdin the body or query string) and gets every event since, as far as the journal still has it.EventSource, graphql-sse clients, the SDK and Velocity's WebSocket bridge do so by themselves. - A
querysent to/subscribeis answered as onenextandcomplete; a mutation is refused (405, "Send mutations to /api/graphql.").
With the SDK:
const controller = new AbortController();
for await (const event of client.subscribe<{ contentPublished: { objectId: number; content: { name: string } | null } }>(
'subscription { contentPublished(classes: ["ng_article"]) { objectId content { name } } }',
undefined,
{ signal: controller.signal },
)) {
console.log(event.data.contentPublished.objectId, event.data.contentPublished.content?.name);
}In a browser with EventSource (anonymous subscriptions must be enabled; EventSource can neither send headers
nor POST, so it uses GET with the query in the URL):
const url = new URL('https://www.example.com/api/graphql/subscribe');
url.searchParams.set('query', 'subscription { contentPublished(classes: ["ng_article"]) { objectId content { name url } } }');
const source = new EventSource(url);
source.addEventListener('next', (e) => {
const { data } = JSON.parse(e.data);
console.log(data.contentPublished);
});
source.addEventListener('complete', () => source.close());Rights. Every event is checked against the subscriber's rights at that moment: the user is read again, and the content must be readable (for a trashed or deleted object, its policies against what the event recorded). Events the subscriber may not read are skipped silently.
Who may subscribe. A signed-in request (a key or token with graphql:read); anonymous requests only with
AnonymousSubscriptions=enabled (otherwise 403 FORBIDDEN "Sign in to subscribe (a token or a personal API
key)."). Switched off (Subscriptions=disabled): 404 DISABLED.
Limits and cost. Each open stream holds one PHP process (or Velocity worker) for its whole duration, but never a
database connection while it waits: it polls the journal every SubscriptionPollInterval ms (500) and opens a
connection only for an event it sends.
| Limit | Default | Over it |
|---|---|---|
MaxSubscriptions | 200 open at once on the installation | 429 SUBSCRIPTION_LIMIT "Too many subscriptions are open; try again later." |
MaxSubscriptionsPerUser | 5 per signed-in user | 429 "You have 5 subscriptions open, the most allowed." |
MaxSubscriptionsPerAddress | 10 per IP address | 429 "Your address has 10 subscriptions open, the most allowed." |
Keep MaxSubscriptions below what PHP-FPM's pm.max_children (or Velocity's StreamShare) leaves for pages, keep
SubscriptionMaxDuration below Velocity's StreamTimeout (300) and below the idle timeouts of proxies in front
(nginx proxy_read_timeout, load balancers), and make sure no proxy buffers the stream (the API sends
X-Accel-Buffering: no for nginx).
Webhooks or subscriptions? Subscriptions are for clients that are connected now (a dashboard, a live page); webhooks for servers that must not miss anything (retries for an hour, a dead letter). A server that needs both reliability and low latency uses a webhook, and pushes to its own clients from there.
Privacy
- An event carries the object's
name. Content of every class produces events, user accounts included (their name is the person's name), although the classesuseranduser_groupare not in the schema. A webhook withoutClassList[]receives them. SetClassList[](orSubtreeList[]/SiteAccessList[]below the content tree) for every end point outside your own infrastructure. - Subscriptions check the subscriber's read rights per event; anonymous subscribers never see user accounts unless the role Anonymous may read them.
- Package event kinds carry only declared fields (ids and states by convention).
- The delivery log never contains bodies or secrets. The journal files do contain names: protect
var/as you protect the database, and keepJournalKeepno larger than you need.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
nothing is delivered, outbox/ grows | the cron part does not run | check the frequent group in cron (runcronjobs.php -q frequent), or run graphqlwebhooks on its own |
| nothing in the outbox after a publish | the journal is not written (API off everywhere, no webhook, no subscriptions), or the end point's filters exclude the event | exp:graphql:status; check Events[], ClassList[], SubtreeList[], SiteAccessList[] |
| a new end point gets no old events | by design: it starts at the end of the journal | Replay from a position |
every delivery retry with HTTP 401 | the receiver's secret differs | compare with Setup > Secrets; rotate both |
stale_timestamp at the receiver | clocks differ by more than 300 s | NTP on both servers |
the signing secret ... is not set | the secret was removed or never stored | set it in Setup > Secrets, or --add again |
HTTP 301/302 | the receiver redirects (http → https, a trailing slash) | use the final URL; redirects are never followed |
| deliveries repeat | at-least-once delivery, a slow receiver | answer 2xx at once, de-duplicate by X-Exponential-Delivery |
| subscription ends every 280 s | by design | reconnect with Last-Event-ID (automatic in the SDK) |
| subscription ends after 60 s | a proxy's idle timeout | raise it, or lower SubscriptionHeartbeat |
| subscription gets nothing | anonymous and not enabled; filters; no read right | sign in; check the arguments; check the role |
429 SUBSCRIPTION_LIMIT | too many open streams | close unused ones; raise the limits within the process budget |
Settings
graphql.ini | Default | Meaning |
|---|---|---|
[GraphQLEvents] JournalMaxBytes | 5M | size of one journal file |
JournalKeep | 3 | journal files kept |
[GraphQLWebhooks] EndpointList[] | the end points, each with [GraphQLWebhook_<name>] | |
Timeout | 10 | seconds an end point has to answer |
MaxAttempts | 8 | tries per delivery |
RetryBackoff / MaxBackoff | 30 / 3600 | the backoff |
BatchSize | 200 | deliveries sent per run |
LogMaxBytes | 1M | size of the delivery log before it is rotated |
[GraphQLSettings] Subscriptions | enabled | |
AnonymousSubscriptions | disabled | |
MaxSubscriptions / PerUser / PerAddress | 200 / 5 / 10 | |
SubscriptionHeartbeat / MaxDuration / IdleTimeout / PollInterval | 15 / 280 / 0 / 500 ms | |
expqueue.ini [JobType_graphql.webhook] | class editorial, Timeout=60 | the job type of Delivery=queue |
Related pages
- Start here and glossary · Cache tags and invalidation · Operations · Cookbook
- The feature page: The GraphQL API, "Real time"