Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

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…

Download as PDF

Address: https://doc.exponential.earth/learninminutes/exphelp/viewer/headless/events-and-webhooks.md

On this page

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

  1. The event journal
  2. Event kinds
  3. The event record
  4. Events of packages
  5. Events during migrations
  6. Webhooks: how they work
  7. Setting up a webhook
  8. The request a receiver gets
  9. Verifying the signature
  10. Retries and giving up
  11. Ordering
  12. Idempotency
  13. Replay
  14. Delivery by the job queue (expqueue)
  15. Operating webhooks
  16. Subscriptions
  17. Privacy
  18. Troubleshooting
  19. 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 expGraphQLEventListener wherever 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=enabled or 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 newest JournalKeep (3) files stay. A reader further behind than the oldest file kept goes on from the oldest one (and the webhooks report the loss as lost).
  • Positions. <generation>.<byte offset> (1.734211) is where the next read starts. It is the id: of each event in a subscription stream (what a client sends back as Last-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

KindWhenContentcontent of a subscription
publishthe first version of an object is publishedthe object, its locations and parentsthe content now
updatea later version is published (an edit, a new translation)as publish, version is the new onethe content now
trashthe object goes to the trash (every location removed)the object; locations may be empty, see belownull
deletethe object is removed for goodas trashnull
movea location moves to another parentoldParentNodeId, newParentNodeId, nodeIds the moved locationthe content now
hidea location is hiddennodeIds the hidden locationthe content now (if readable)
reveala hidden location is revealednodeIds the revealed locationthe content now
mutationa GraphQL mutation succeeded (also a package's mutation), or a migration's summarymutation names it (createContent, newsletterUnsubscribed, migration)the content now
clearthe content caches were cleared as a wholeno object; data.scope is content or graphqlnull
pinga webhook test (--test, the Test button); never in the journalno 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:

FieldTypeMeaning
idstringthe event's id: <microseconds since 1970>-<8 hex> (1796376216010281-d9f6e3ce); the same in every webhook and subscription
eventstringthe kind
timestringISO 8601 UTC with milliseconds (2026-12-04T09:15:02.120Z)
objectIdint or nullthe content object
remoteIdstring or nullits remote id
versionint or nullthe version published
classIdentifierstring or nullits class
namestring or nullits name at that moment
languagestring or nullthe language of the version (its initial language)
languagesstring[]its translations
nodeIdsint[]its locations (a move, hide or reveal: the one it happened to)
mainNodeIdint or nullits main location (0 when gone)
parentNodeIdsint[]the parents of its locations
oldParentNodeId, newParentNodeIdint or nulla move: before and after
mutationstring or nullthe GraphQL mutation, or migration for a migration's summary
migrationstring or nullthe id of the migration that made the change
objectIdsint[]a migration's summary: the objects it changed (at most 1000)
dataobjecta 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:

ModeEvents
each (default)every change its own event, with migration set to the migration's id
summaryno event per change; one mutation event at the end with mutation: "migration", objectIds and nodeIds (at most 1000 each)
nonenothing

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 graphqlwebhooks is in the frequent group; 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 --apply does 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 secret

Or 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
KeyDefaultMeaning
URLhttps:// (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 clearkinds, package kinds, or namespaces (shop.*); an unknown package kind is a warning, still sent
SiteAccessList[]every siteaccessonly content below the root node of these siteaccesses (content.ini [NodeSettings] RootNode), in their languages (SiteLanguageList[])
ClassList[]every classonly these class identifiers
SubtreeList[]the whole treeonly content at or below these nodes
Secretgraphql.webhook.<name>the name of the signing secret in the secret store (Setup > Secrets), or env:VARIABLE
Payloadeventevent: the event; query: the answer of a persisted query
Querywith Payload=query: the persisted query's name or SHA-256
QueryUseranonymouswith Payload=query: the login the query runs as
Deliveryoutboxqueue: one expqueue job per delivery
Enabledenableddisabled 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 --apply

The 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}}
HeaderMeaning
X-Exponential-Webhookthe end point's name
X-Exponential-Eventthe kind (publish, ping ...)
X-Exponential-Event-Idthe event's id (the same for every end point)
X-Exponential-Deliverythe delivery's id (one per end point and event, the same over its retries)
X-Exponential-TimestampUnix seconds when this attempt was signed
X-Exponential-Signaturesha256=<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):

<?php
$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__)

@app.post('/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 '', 204

Clocks. 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:

  1. Make the receiver accept two secrets (the current and the next): valid if either matches.
  2. Set the new value in Setup > Secrets (name graphql.webhook.<name>), or change the environment variable of Secret=env:....
  3. 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:

AttemptWaits before itAbout this long after the first
10
230 s30 s
360 s1.5 min
4120 s3.5 min
5240 s7.5 min
6480 s15.5 min
7960 s31.5 min
81920 s63.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).

IdSame forUse it to
X-Exponential-Delivery (extensions.delivery)one event to one end point, over all its retriesdrop a repeated delivery
X-Exponential-Event-Id (data.contentEvent.id)one event, in every end point and subscriptiondrop 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 nothing

Replay

What to replayHow
Deliveries that gave upafter 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 pointset 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 disconnectthe client sends Last-Event-ID (the SDK and EventSource do it by themselves)
Dead jobs of Delivery=queueSetup > Job queue, or ./console ext:expqueue:retry --dead
A full resynchronizationdo 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 --apply

From 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 --apply

Only 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 (kernel settings/expqueue.ini: class editorial, 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> in expqueue.ini limits 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 2xx

A 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 fieldEventsArguments
contentEventsthose of events: [ContentEventKind!] (none: every kernel kind but clear; package kinds only when named)events, classes, parentId (directly below), subtreeId (at or anywhere below)
contentPublishedpublish, updateclasses, parentId, subtreeId
contentUpdatedupdatethe same
contentDeletedtrash, delete (content is null)the same
contentMovedmovethe same
contentHiddenhide, revealthe same

One subscription asks for exactly one root field ("A subscription asks for exactly one field.", VALIDATION).

Transports.

TransportWhereProtocol
Server-Sent EventsPOST (or GET) /api/graphql/subscribe with Accept: text/event-stream, under PHP-FPM and Velocitygraphql-sse, "distinct connections" mode
WebSocketthrough Velocity onlygraphql-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: next with id: (the journal position after it) and the GraphQL answer as data:.
  • A comment (: heartbeat) every SubscriptionHeartbeat seconds (15) keeps proxies from closing the stream and finds clients that left; it may carry an id: when the stream skipped events the subscriber may not read, so a resume never sees them again.
  • The stream ends after SubscriptionMaxDuration seconds (280) or SubscriptionIdleTimeout seconds without an event (0: off). The client reconnects with Last-Event-ID: <last id> (or lastEventId in 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 query sent to /subscribe is answered as one next and complete; 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.

LimitDefaultOver it
MaxSubscriptions200 open at once on the installation429 SUBSCRIPTION_LIMIT "Too many subscriptions are open; try again later."
MaxSubscriptionsPerUser5 per signed-in user429 "You have 5 subscriptions open, the most allowed."
MaxSubscriptionsPerAddress10 per IP address429 "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 classes user and user_group are not in the schema. A webhook without ClassList[] receives them. Set ClassList[] (or SubtreeList[]/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 keep JournalKeep no larger than you need.

Troubleshooting

SymptomCauseFix
nothing is delivered, outbox/ growsthe cron part does not runcheck the frequent group in cron (runcronjobs.php -q frequent), or run graphqlwebhooks on its own
nothing in the outbox after a publishthe journal is not written (API off everywhere, no webhook, no subscriptions), or the end point's filters exclude the eventexp:graphql:status; check Events[], ClassList[], SubtreeList[], SiteAccessList[]
a new end point gets no old eventsby design: it starts at the end of the journalReplay from a position
every delivery retry with HTTP 401the receiver's secret differscompare with Setup > Secrets; rotate both
stale_timestamp at the receiverclocks differ by more than 300 sNTP on both servers
the signing secret ... is not setthe secret was removed or never storedset it in Setup > Secrets, or --add again
HTTP 301/302the receiver redirects (http → https, a trailing slash)use the final URL; redirects are never followed
deliveries repeatat-least-once delivery, a slow receiveranswer 2xx at once, de-duplicate by X-Exponential-Delivery
subscription ends every 280 sby designreconnect with Last-Event-ID (automatic in the SDK)
subscription ends after 60 sa proxy's idle timeoutraise it, or lower SubscriptionHeartbeat
subscription gets nothinganonymous and not enabled; filters; no read rightsign in; check the arguments; check the role
429 SUBSCRIPTION_LIMITtoo many open streamsclose unused ones; raise the limits within the process budget

Settings

graphql.iniDefaultMeaning
[GraphQLEvents] JournalMaxBytes5Msize of one journal file
JournalKeep3journal files kept
[GraphQLWebhooks] EndpointList[]the end points, each with [GraphQLWebhook_<name>]
Timeout10seconds an end point has to answer
MaxAttempts8tries per delivery
RetryBackoff / MaxBackoff30 / 3600the backoff
BatchSize200deliveries sent per run
LogMaxBytes1Msize of the delivery log before it is rotated
[GraphQLSettings] Subscriptionsenabled
AnonymousSubscriptionsdisabled
MaxSubscriptions / PerUser / PerAddress200 / 5 / 10
SubscriptionHeartbeat / MaxDuration / IdleTimeout / PollInterval15 / 280 / 0 / 500 ms
expqueue.ini [JobType_graphql.webhook]class editorial, Timeout=60the job type of Delivery=queue

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x