Operations: switching on, monitoring, logs, troubleshooting and tuning
What this is. Everything an operator needs to run the headless features in production: switching the API on per siteaccess, the files it keeps, what to monitor, where the logs are, a table of common errors with their fixes, and performance tuning.
When to use it. When you set up an installation for API clients, watch it, answer a client's error report, or make it faster.
Quick example: is the API on, and is it healthy?
./console exp:graphql:status --siteaccess=sitesiteaccess site
enabled yes
mutations yes
end point /api/graphql
library webonyx/graphql-php 15.43.0
limits depth 12, complexity 1000, list 100 (default 25)
rate limits 600 per user or key, 120 per anonymous address, in 60 s
persisted enabled, 1 stored, automatic: signed-in, persisted only: disabled
cache persisted queries, at most 86400 s
introspection signed-in
naming identifier
schema fd661f82e524, 92 classes, 894 fields
extensions eztags/1 explayouts/1 migration/1 expwt/1 cjw_newsletter/1 cjw_newsletter/events/1
string only cjwnewsletteredition cjwnewsletterlist cjwnewsletterlistvirtual
event kinds newsletter.subscription.confirmed (cjw_newsletter/events/1) object; fields listId:int status:string
PASS the GraphQL API can runContents
- Switching the API on
- A read-only public siteaccess
- Checklist before go-live
- The files the API keeps
- Monitoring
- Logs and the audit
- Finding a request by its id
- Troubleshooting: common errors and fixes
- Performance tuning
- Several servers
- Velocity
- Backups and disaster recovery
- Console commands
Switching the API on
The API is off until it is switched on (graphql.ini [GraphQLSettings] Enabled=disabled). It needs the library
webonyx/graphql-php 15 (composer require webonyx/graphql-php:^15.32.3, suggested by the kernel's
composer.json); without it /api/graphql answers 503 and everything else of Exponential works as before.
./console exp:graphql:enable # what would change (a diff), nothing written
./console exp:graphql:enable --siteaccess=site --apply # on, in the siteaccess site only
./console exp:graphql:enable --siteaccess=site --origin=https://shop.example.com --key-for=frontend --applyexp:graphql:enable writes settings/override/graphql.ini.append.php (Enabled=enabled, the siteaccess into
SiteAccessList[]), with --origin the CORS settings of rest.ini, with --key-for a personal API key (shown once;
--key-limited, --key-public, --scope, --days), checks that the schema builds, backs up every file it changes,
clears the INI caches, and prints the end point, a curl example and the playground. Or do it in Setup > GraphQL
(policy graphql/administrate).
By hand:
# settings/override/graphql.ini.append.php
[GraphQLSettings]
Enabled=enabled
SiteAccessList[]
SiteAccessList[]=sitephp bin/php/ezcache.php --clear-tag=ini --allow-root-user
curl -s https://www.example.com/api/graphql -H 'Content-Type: application/json' -d '{"query":"{ siteaccess { name } }"}'SiteAccessList[] empty means every siteaccess. Each siteaccess can override any setting in
settings/siteaccess/<name>/graphql.ini.append.php; settings/override/ wins over both.
Off again: ./console exp:graphql:disable --apply (every siteaccess), or --siteaccess=<name> to take one out of
the list. /api/graphql then answers 404 DISABLED; persisted queries, keys and the cache stay.
A read-only public siteaccess
./console exp:graphql:disable --siteaccess=site --mutations --apply # MutationsEnabled=disabled thereFor a public siteaccess also consider:
# settings/siteaccess/site/graphql.ini.append.php
[GraphQLSettings]
MutationsEnabled=disabled
Introspection=signed-in
PersistedQueriesOnly=anonymous
AutomaticPersistedQueries=signed-in
Subscriptions=disabled
Debug=disabledPersistedQueriesOnly=anonymous lets visitors run only the queries you stored; signed-in programs (your build, your
SSR server with a key) can still send anything.
Checklist before go-live
- The library is installed and
exp:graphql:status --siteaccess=<public>saysPASS. - The API is on only in the siteaccesses that need it.
- The role Anonymous reads only what the public may see; check with an anonymous request of a protected node
(
nullexpected). - Mutations are off on public siteaccesses unless needed; writing keys belong to dedicated users with narrow policies.
- Keys are limited to siteaccesses and have an expiry; a rotation date is in the calendar.
Introspection=signed-in,Debug=disabled.- CORS lists exactly the front end's origins, and
ExposedHeaders[]what the client reads. - The request shield exempts
/api/**from the browser check and gives the API a budget (CORS, rate limits and the request shield). - Trusted proxies are configured, so rate limits count visitors, not the proxy.
- Persisted queries are stored by the deployment (
exp:graphql:persist queries/ --apply), and the response cache answers them (X-GraphQL-Cache: HITon the second request). - Webhooks:
exp:graphql:webhooks --test=<name> --applypasses; the cron partgraphqlwebhooksruns (thefrequentgroup);ClassList[]set for external receivers. - Subscriptions: limits fit the PHP-FPM pool; proxies do not buffer
/api/graphql/subscribe. - Monitoring of the items below is in place.
exp:graphql:benchagainst the public end point meets the targets.
The files the API keeps
var/<site> is the installation's var directory (var/site by default); var/cache is the cache directory.
| Path | What | Safe to delete? |
|---|---|---|
var/cache/graphql/responses/ | the response cache, and the expired marker | yes (ezcache --clear-id=graphql) |
var/cache/graphql/credentials/ | remembered rights of keys and tokens | yes |
var/cache/graphql/rate/ | rate-limit counters | yes (limits restart) |
var/<site>/graphql/persisted/ | stored persisted queries (<sha256>.graphql, names.json) | no: clients call them; back it up |
var/<site>/graphql/events/ | the event journal (events-<n>.jsonl) | not while receivers are behind; rotation removes old files |
var/<site>/graphql/webhooks/cursor.json | where the webhooks read next | no (deleting it skips to the end) |
var/<site>/graphql/webhooks/outbox/ | deliveries waiting | no |
var/<site>/graphql/webhooks/failed/ | deliveries that gave up | after review |
var/<site>/graphql/webhooks/deliveries.jsonl (.1.jsonl) | the delivery log | rotated by size |
var/<site>/graphql/subscriptions/ | the open subscriptions (for the limits) | stale files only |
Files are written by both the PHP-FPM user and (with Velocity) root; they take the owner and group of their directory. Keep the directories writable by the web server's user.
Monitoring
| What | How | Alert when |
|---|---|---|
| The API answers | curl -s -o /dev/null -w '%{http_code}' -H 'Content-Type: application/json' -d '{"query":"{ siteaccess { name } }"}' https://www.example.com/api/graphql | not 200 |
| The cache works | the share of X-GraphQL-Cache: HIT in the access log (log the header) | drops sharply |
| Latency | exp:graphql:bench daily; your APM | cached rows over 33 ms |
| Errors | INTERNAL in answers; var/log/error.log lines of expGraphQL* | any |
| Rate limits | 429 in the access log, by key and address | rising |
| Webhook backlog | files in var/<site>/graphql/webhooks/outbox/ | above a few hundred, or not shrinking |
| Webhooks given up | new files in failed/, gave-up in deliveries.jsonl | any |
| Journal lag | the webhooks' cursor.json position versus the end of the newest journal file | far behind for long |
| Subscriptions | files in var/<site>/graphql/subscriptions/; busy PHP-FPM workers | near MaxSubscriptions or pm.max_children |
| Keys | exp:graphql:keys --list --format=json: keys expiring within 14 days, never used | expiring, unused for long |
| Refusals | the audit: access.apikey.use.failed by reason | bursts of secret/unknown |
| Library | exp:graphql:status exit code | not 0 |
A small check script for cron or your monitoring agent:
#!/usr/bin/env bash
# exp-graphql-health: PASS/FAIL lines, exit 1 on any FAIL
R=/path/to/installation; SITE=site; URL=https://www.example.com/api/graphql; rc=0
code=$(curl -s -o /dev/null -w '%{http_code}' -m 10 -H 'Content-Type: application/json' -d '{"query":"{ siteaccess { name } }"}' "$URL")
[ "$code" = 200 ] && echo "PASS api $code" || { echo "FAIL api $code"; rc=1; }
out=$(ls "$R/var/$SITE/graphql/webhooks/outbox" 2>/dev/null | wc -l)
[ "$out" -lt 500 ] && echo "PASS outbox $out" || { echo "FAIL outbox $out"; rc=1; }
failed=$(find "$R/var/$SITE/graphql/webhooks/failed" -name '*.json' -mmin -60 2>/dev/null | wc -l)
[ "$failed" = 0 ] && echo "PASS failed/ last hour 0" || { echo "FAIL failed/ last hour $failed"; rc=1; }
exit $rcLogs and the audit
| Log | Has |
|---|---|
var/log/error.log (and var/<site>/log/) | PHP exceptions behind INTERNAL errors (expGraphQLServer::formatError writes the class, message, file and line), library problems |
| the web server's access log | every request; add X-Request-Id, X-GraphQL-Cache and the status to its format |
var/<site>/graphql/webhooks/deliveries.jsonl | every webhook attempt: time, delivery, end point, event, status, ms, result, error |
| the audit (Setup > Audit trail) | content.graphql.mutation, content.graphql.mutation.failed (with the reason: get, anonymous, scope, form_token, a policy refusal, an error), access.apikey.create, .revoke, .use (first use), .use.failed (with the reason) |
| Setup > GraphQL | the state, the cache, persisted queries, keys, webhooks and their last deliveries |
| Setup > Job queue | jobs of Delivery=queue, the dead letter |
| Setup > Request shield | requests the shield refused or checked |
Debug=enabled (development only) puts the exception and trace into extensions.debug of the answer.
Finding a request by its id
Every answer has a request id (X-Request-Id, extensions.requestId, 16 hexadecimal characters). Ask clients to
quote it. Then:
grep -r 'a1b2c3d4e5f60718' /var/log/nginx/ /path/to/installation/var/log/ 2>/dev/nullErrors of the code are logged with the request's context; with the id in your access-log format you find the exact request, its time, its client and its status.
Troubleshooting: common errors and fixes
| Symptom | Cause | Fix |
|---|---|---|
404 {"errors":[{"message":"The GraphQL API is switched off in this siteaccess.","extensions":{"code":"DISABLED"}}]} | Enabled=disabled, or the siteaccess is not in SiteAccessList[], or the request landed in another siteaccess | exp:graphql:enable --siteaccess=<name> --apply; check the host or X-Siteaccess (an unknown name is ignored) |
503 "The GraphQL library is not installed." | webonyx/graphql-php missing or not version 15 | composer require webonyx/graphql-php:^15.32.3; or graphql.ini LibraryPath/GRAPHQL_LIBRARY_PATH |
404 for /api/graphql with an HTML page | the request did not reach index_rest.php | the web server's rewrite rules for /api/ (as for the REST API) |
401 {"error":"invalid_token"} | key wrong, revoked, limited to another siteaccess, owner disabled; or a key in the URL | check the key (exp:graphql:keys --list), the siteaccess, the header |
401 expired_token | key or OAuth token expired | a new key; refresh the token |
403 insufficient_scope | key without graphql:read, or the owner lost content/read | a key with the scope; give the role back |
429 {"error":"rate_limited"} | rest.ini [ApiKeySettings] RateLimitPerMinute | raise it; for a public key set 0 |
429 RATE_LIMITED | the GraphQL rate limit | honor Retry-After; raise the limit; trusted proxies |
429 with Request-Shield-Challenge | the shield's browser check | challenge-exempt /api/** |
a key seems ignored, signedInBy: anonymous | the web server drops Authorization | pass it through to PHP |
INTROSPECTION_DISABLED | anonymous introspection, or contentClasses anonymously | sign in; use exp:graphql:schema on the console |
VALIDATION "Cannot query field ..." | a field not in the schema: hidden, a class excluded, another naming style, another siteaccess | exp:graphql:schema --format=summary --siteaccess=<name> |
a node is null | not there, or the user may not read it, or its class is not in the schema | check with --as=<login> on the console; check ClassList[] |
COMPLEXITY_LIMIT | nested lists with large limits | smaller limit, separate requests, or MaxComplexity |
DEPTH_LIMIT | very deep nesting | flatten; MaxDepth |
PERSISTED_QUERY_NOT_FOUND | the query was not stored in this installation, or on this server | exp:graphql:persist queries/ --apply on every server (or share var/<site>/graphql/persisted/) |
PERSISTED_QUERY_REQUIRED | PersistedQueriesOnly | persist the query and send its id |
X-GraphQL-Cache never HIT | ad-hoc queries (always BYPASS); answers with errors; currentUser in a signed-in query; Debug=enabled; constant publishing; query string order varies | use persisted queries with stable variables |
| old content after a publish | your own cache or CDN not purged | check the webhook delivery log and your receiver |
FORBIDDEN "Sign in to change content." | mutation without credentials | a key with graphql:write |
FORBIDDEN "You may not do this to this content." | the owner's policies | give the role the policy for that class/section/subtree |
PENDING after a mutation | a workflow (approval) holds it | approve in the administration |
BAD_USER_INPUT "The value of the field ... could not be stored." | the datatype refused the string | see Datatypes in GraphQL |
| upload refused | MaxUploadSize, PHP's upload_max_filesize/post_max_size, an upload check | raise the limits consistently |
| webhooks not sent | the cron part does not run | runcronjobs.php -q frequent in cron |
| subscription stream closes at once | proxy buffering, max_execution_time, Velocity StreamTimeout | X-Accel-Buffering: no passes through; timeouts above SubscriptionMaxDuration |
Internal server error (INTERNAL) | a bug or a broken datatype | the error log with the request id; report it |
Performance tuning
What a request costs.
| Request | Cost |
|---|---|
| cached persisted query, early answer | a file read; no settings, no database; target under 13 ms |
304 of a cached persisted query | less |
| persisted query, cache miss | the kernel starts, the schema loads from its cache, the query runs |
| ad-hoc query | the same, every time |
| mutation | the kernel's operations: publish, workflows, caches, the journal |
| subscription | one process for up to SubscriptionMaxDuration seconds, a database connection per event sent |
Measure with the console:
./console exp:graphql:bench --url=https://www.example.com/api/graphql --id=articles
./console exp:graphql:bench --url=https://www.example.com/api/graphql --id=articles \
--variables='{"limit":50}' --query-file=queries/articles.graphql --requests=200 --runs=3
GRAPHQL_BENCH_TOKEN=$KEY ./console exp:graphql:bench --url=... --id=articles --rows=get,post,kernelRows: get (cached GET), 304, post (cached JSON POST), kernel (a form POST, which starts the kernel), uncached
(an ad-hoc query). Cached answers must come within 33 ms (hard limit), with targets of 20 ms and then 13 ms for the
median and p95. Exit code 1 when a cached row is over the limit.
Levers, most effective first:
- Persisted queries for every public page. They are cached and answered before the kernel starts.
- Stable request shapes. The cache key includes the query string as sent: always build it the same way
(
idthenvariables, the same JSON key order). - Fewer, wider queries. Aliases and fragments instead of several requests; the batch loader fetches a whole level of relations, owners and parents at once, so a page of 50 articles with authors costs a few queries.
- Small pages.
limit/firstas small as the page shows; never nest lists without need. ETag/304in clients.- Your own cache in the front end, purged by tags (Cache tags and invalidation).
- Velocity (persistent workers) for uncached requests: no bootstrap per request.
- Search with Solr (ezfind) on large installations; the kernel's own search engine queries the database.
- Image aliases made ahead (after publishing, by the job queue:
image.alias.generate) so a first request does not wait for one. - OPcache with enough memory for the kernel and the schema classes.
Settings that trade safety for speed:
| Setting | Effect |
|---|---|
CredentialCacheTtl higher | more signed-in requests answered early; a revoked token reads cached answers for that long (keys are forgotten at once when changed) |
ResponseCacheTtl | only matters without publishes; 0 keeps entries until the next expiry |
MaxComplexity, MaxListLimit higher | bigger queries allowed; more load per request |
SubscriptionPollInterval lower | faster events, more file reads per open stream |
Several servers
On several web servers behind a load balancer:
- Persisted queries must exist on every server: store them on each (part of the deployment), or share
var/<site>/graphql/persisted/(the DFS cluster's shared storage, or a shared mount). - The response cache, credential cache and rate counters are per server unless
var/cache/graphql/is shared. A per-server cache is fine; rate limits then count per server (the effective limit is multiplied by the number of servers). - The journal must be one: share
var/<site>/graphql/events/(andwebhooks/,subscriptions/) between servers, or a publish on server A is invisible to subscriptions on server B and to the webhooks run on B. Run the cron partgraphqlwebhookson one server only (the lock file is per directory: on a shared directory two servers are safe too). - Expiry: a publish on A expires A's response cache; B's expires when B clears its own view caches (cluster
handlers propagate them) or after
ResponseCacheTtl. - Keys are in the database: shared by definition. The key limit of
rest.ini(APCu) is per server.
Velocity
Under Velocity (Exponential's persistent-worker server) the API behaves the same, with three differences:
- Uncached requests are faster (no bootstrap). A changed kernel class or setting reaches the workers only after
exp:velocity restart(deploy withexp:velocity deploy). - Subscriptions are also available as WebSockets (
graphql-transport-ws); Velocity's bridge opens the SSE stream for each. Each open stream holds a worker withinStreamShare;SubscriptionMaxDurationmust stay below Velocity'sStreamTimeout(300 s). - Files under
var/may be written by root (Velocity) and the site user (PHP-FPM); the API makes them take the owner and group of their directory.
Backups and disaster recovery
| Back up | Why |
|---|---|
| the database | keys (expapikey), content, the audit |
var/<site>/graphql/persisted/ | clients call these queries by name |
settings/override/graphql.ini.append.php, rest.ini.append.php | the switches, webhooks, CORS |
the secret store (Setup > Secrets) and EXP_SECRET_KEY / var/secrets/exp_secret.key | webhook signing secrets; preview tokens depend on the secret key |
| the request shield rules | your API rules |
Not needed: the response cache, the rate counters, the journal (after a restore, receivers should resynchronize by a full walk), the outbox (lost deliveries can be replayed from the journal if it survived).
After a restore of an older database: keys made after the backup no longer exist (401), keys revoked after it are
valid again: revoke them anew.
Console commands
| Command | Does |
|---|---|
exp:graphql:enable / exp:graphql:disable | switch the API or the mutations on and off per siteaccess, CORS origins, a key |
exp:graphql:status | the state, library, limits, schema hash, classes, string-only datatypes, extensions, event kinds |
exp:graphql:schema | the schema: sdl, json or summary, --output |
exp:graphql:query | run a query as a user (--as), a file, a persisted query (--id), --format=table |
exp:graphql:persist | check, store, list and remove persisted queries |
exp:graphql:keys | list, create and revoke API keys with GraphQL scopes |
exp:graphql:webhooks | list, add, remove, test webhooks; deliver; the log |
exp:graphql:starter | write a starter front end (html, next, nuxt, astro, expo) |
exp:graphql:bench | measure the end point |
php bin/php/ezcache.php --clear-id=graphql | expire the response cache |
Every command that changes something shows what it would do and writes only with --apply.