The addresses on this page were filled in with this server's own address, https://qm.weekday100.com.
Queue Manager: Operations Guide
This guide covers what you have to decide before putting this server in front of real traffic (configuration, the proxy/CDN setup that per-IP limits depend on, the API keys, and how a pass is bound to a visitor) and what you use once it is there: the operator console, scheduled drops, and metrics.
INTEGRATION.md documents the customer-site side (script tag, /api/check). This file documents the server side. Both are served by the running server at /docs, and linked from the dashboard header. Thai translations are served at /docs/th (sources in docs/th/); the English files are authoritative.
Environment variables
Everything is optional; defaults are safe for a single-instance install on localhost, and deliberately not safe to expose unchanged.
| Variable | Default | What it does |
|---|---|---|
PORT | 8080 | Listen port. |
HOST | (unset) | Listen address. Unset binds every interface, except while ADMIN_KEY is the default: then unset means loopback (127.0.0.1) only, and a HOST that is not loopback refuses to start (see Refusals). Set it to 127.0.0.1 to answer only on loopback. Do this when a reverse proxy on the same box is the only thing that should reach this process. |
DATA_DIR | (removed) | Removed in step 5: nothing is written to local disk. Set, it is ignored with a boot warning (DATA_DIR is set but ignored since step 5: nothing is written to local disk.), so an old manifest still deploys. Delete it from the manifest. |
ADMIN_KEY | admin-dev | Private API key: /api/admin/* (create/delete rooms, rates, flush, eject, metrics). Never distribute it. While it is the default the server listens on loopback only and refuses a non-loopback HOST. The default is printed in these docs, so it must never reach another machine. |
PUBLIC_API_KEY | (unset) | Public API key: the only thing it unlocks is vouching for an end client on /api/check?ip=&agent=. Sent as Authorization: Bearer only; ?key= is refused (401 credential_in_query). Safe to ship to every edge server / backend. Without it those calls need ADMIN_KEY, which is a privilege escalation, and a warning says so. |
ADMIN_HOST | (unset) | Comma-separated hostnames the operator console and /api/admin/* answer on. Unset, a snippet-only install answers anywhere; once a room is inline an unset value means the console answers only on an address literal (127.0.0.1, the pod IP), on localhost or on the PUBLIC_URL host (QM-440), and on any other Host the console surface and /__qm/ are a bare 404 while the queue itself keeps answering, exactly as with ADMIN_HOST set (QM-428; the customer's own hostname still serves the console under /__qm/). Set this to put the console on a real name: set, it is the only place the console answers: on every other hostname (and on the bare pod address) the console surface answers 404: /, /api/admin/*, /metrics, /docs, /progress and the console's own file /public/admin.html, and on a hostname that fronts an inline room the same paths under /__qm/. It gates only the console: the queue itself (/healthz, /snippet/qm.js, /w/<room>, /api/check, /api/join, status, events, notify, the waiting page) keeps answering on any hostname, so the snippet host and a probe by pod IP work unchanged. A room may not be put inline on an ADMIN_HOST name or the PUBLIC_URL host (400 reserved_host), and the console surface on those names is never handed to a room, even one saved before that was refused. Unset, the address literals and localhost are the console's too, so their /api/admin/* and /api/v1/admin/* are never handed to a room either, even one whose targetUrl is the server's own address (QM-439); the rest of such a host stays the room's, which is how inline mode runs on a laptop. And on any host, the proxy never forwards this server's own credential: an Authorization: Bearer carrying ADMIN_KEY or an operator key is dropped before the request reaches the origin, while the app's own Authorization passes unchanged. See Two deployments. |
ADMIN_AUTH_FAIL_PER_MIN | 20 | Failed admin authentications allowed per client address per minute (token bucket). Past it, every credential from that address (the right one included) gets 429 too_many_auth_failures with Retry-After until one failure's worth has refilled. Only failures spend it. 0 disables. See Two keys, two blast radii. |
SECRET | random per boot (memory); required with SIDESTORE=pg | Root signing secret for visitor tickets, monitor links, console sessions and operator-key verifiers. By default they are signed with it directly, as in earlier releases; with TOKEN_SIGN_V2=1 each purpose signs with its own key derived from it (HKDF-SHA256) and every token names it by a kid. Both forms are always accepted. Set it if you run more than one instance, or tokens minted by one are rejected by the others. Unset, a new key is made on every boot, so a restart voids every ticket, monitor link, console session and operator key (fine for development, where nothing else survives a restart either). Required with SIDESTORE=pg: the server refuses to start without it, because a new key on every deploy voids every pass (tickets, monitor links, operator keys) that Postgres still holds. See Signing keys and rotating SECRET. |
SECRET_PREVIOUS | (unset) | The SECRET being rotated out. Tokens signed under it still verify (either form, every purpose); new tokens are always signed under SECRET. Operator keys resolved under it are re-keyed to SECRET on use. Remove it once the rotation has settled; /api/admin/health lists it under hardening while it is set. See Signing keys and rotating SECRET. |
TOKEN_SIGN_V2 | 0 | 1 signs tokens and new operator verifiers in the v2 form: a key per purpose and a kid. 0 (default) signs the legacy form, raw SECRET and no kid, which the release before per-purpose keys also reads. Both forms are accepted either way. Once you turn it on, you can't roll back below this release without losing the queue (see Signing keys and rotating SECRET). Any value other than 0/1 counts as 0 and is named in warnings. |
TRUST_PROXY | 0 | Number of reverse proxies in front of this server. The client address is taken from X-Forwarded-For counted from the right, and only when the connection comes from an address in TRUST_PROXY_IPS. 0 means the socket address is the client. On DO App Platform leave it unset and use EDGE_SECRET (see DigitalOcean App Platform). |
TRUST_PROXY_IPS | (empty) | Comma-separated addresses or CIDR ranges of those proxies, IPv4 or IPv6 (10.0.0.7, 173.245.48.0/20, 2400:cb00::/32). An IPv4-mapped peer (::ffff:1.2.3.4) matches IPv4 entries. An entry that does not parse stops the server at startup, naming the entry. From any other peer, X-Forwarded-For is ignored. Required to get per-visitor throttling behind a CDN (see below). Not on DO App Platform: see DigitalOcean App Platform. |
EDGE_SECRET | (unset) | The secret a Cloudflare request-header rule adds as X-QM-Edge (see Cloudflare edge secret). Set, every request and WebSocket upgrade without a matching header is refused 403 (edge_required), except /healthz; the client address becomes cf-connecting-ip and TRUST_PROXY/TRUST_PROXY_IPS are ignored. Comma-separated for rotation (any listed value passes). An entry shorter than 16 characters stops the server at startup. Unset with STORE=valkey or NODE_ENV=production, a startup line says bypassing requests are accepted. |
LOADTEST_KEY | (unset) | Lets an authorized load test past the per-address limits (see Load testing through Cloudflare). Set, a request that passed the EDGE_SECRET check and carries X-QM-Loadtest: <key> is keyed on a synthetic address per X-QM-Loadtest-Client id instead of its real address. Ignored entirely while unset, and while EDGE_SECRET is unset (a warning says so). Shorter than 32 characters stops the server at startup. A warning stays up for as long as it is set: unset it after the test. |
TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY | (unset) | The Cloudflare Turnstile widget's public site key and its secret. Both set, a room can require a Turnstile check before it gives a place in line (see Turnstile challenge); one alone does nothing and a warning says so. The secret is never logged or returned. Also TURNSTILE_HOSTNAMES (optional hostname allowlist for the widget) and TURNSTILE_TIMEOUT_MS (default 3000). |
IPV6_PREFIX_BITS | 64 | What "per address" means for an IPv6 client: its first N bits (32..128). An IPv6 host is normally handed a whole /64 and may use any address in it, so every per-address limit (the join, check, notify, page and SSE budgets, the failed-login lockout, queueMaxPerIp, preQueueMaxPerIp and the traffic-classification record) is keyed on the /64, not the /128. 128 restores one key per address. IPv4 and IPv4-mapped (::ffff:1.2.3.4) clients are unaffected. Only the key changes: logs, the audit trail and the console still show the full address, and TRUST_PROXY_IPS still matches the real peer exactly or by its own CIDR. |
JOIN_LIMIT_PER_MIN | 600 | Per-address /api/join budget. 0 disables. Per instance with STORE=valkey: each instance keeps its own count, so N instances allow one client up to N× this across the fleet; Cloudflare's edge rate limiting is the fleet-wide control. |
CHECK_LIMIT_PER_MIN | 6000 | Per-address /api/check budget. 0 disables. Per instance with STORE=valkey: each instance keeps its own count, so N instances allow one client up to N× this across the fleet; Cloudflare's edge rate limiting is the fleet-wide control. |
RATE_LIMIT_MAX_KEYS | 200000 | Most distinct addresses each rate-limit bucket map holds. Past it the least recently used are evicted, never the whole map, so key churn cannot hand a throttled client a fresh budget. The ADMIN_AUTH_FAIL_PER_MIN lockout is held the same way. |
WAITING_LIMIT_PER_MIN | 120 | Per-address budget for the waiting page itself, and, in a bucket of its own, for the console page, /progress and /docs (also under /__qm/). 0 disables both. Stands down automatically for an undeclared proxy's address (that address only); see Rate limits. Per instance with STORE=valkey: each instance keeps its own count, so N instances allow one client up to N× this across the fleet; Cloudflare's edge rate limiting is the fleet-wide control. |
SSE_PER_IP | 200 | Concurrent /events streams per address. 0 disables. Sized for a whole office or CGNAT block sharing one address; SSE_MAX_TOTAL is the cap that protects process memory. Per instance with STORE=valkey: each instance holds its own ceiling, so N instances hold up to N× this in total; Cloudflare is the fleet-wide control. |
SSE_MAX_TOTAL | 5000 | Global SSE ceiling (visitors + admins). Sized by CPU, not memory: an update that moves every visitor costs one kernel send per open stream, about 0.1 ms each on the reference box (QM-381), so 5,000 streams is ~0.5 s of CPU per update against the 1 s engine tick and 20,000 would be ~2 s. The fan-out runs in slices of 256 streams, so a large one does not stall the event loop, but above this cap each visitor simply gets fewer updates. A visitor refused a stream (503 sse_capacity) is not turned away: the waiting page polls /api/status every 5 s instead. Raise it only on a faster box, after measuring. Frames whose content has not changed are not re-sent, except as a keepalive to a stream that has been quiet for 4 s. Per instance with STORE=valkey: each instance holds its own ceiling, so N instances hold up to N× this in total; Cloudflare is the fleet-wide control. |
ADMIN_SSE_RESERVE | 8 | Extra stream slots above SSE_MAX_TOTAL that only a console holding a write-capable credential may use (ADMIN_KEY, or a named owner/operator key), so the dashboard can still connect when visitors have filled the global ceiling, which is exactly when you need to look at it. A monitor share link is a read-only credential and gets no exemption: it competes for SSE_MAX_TOTAL like a visitor. |
ADMIN_ALIVE_MS | 5000 | How often every console stream is sent an alive event, in milliseconds. It is written by a timer that reads no store, so a console can tell a slow store (no stats frame, alive still arriving) from a dead stream, and keeps the stream instead of reconnecting into the same slow store. |
ADMIN_TICK_STUCK_MS | 30000 | The 2 s console tick reads the store once at a time and skips a tick while the last read is still out. A read still out after this long no longer holds the next tick back (its frame is still sent if it arrives and nothing newer went out), so a read that never returns cannot stop the consoles for good. |
MAX_CONNECTIONS | 50000 | Soft socket ceiling, enforced by this process itself: at and above this many open connections, every NEW request is answered 503 (see qm_connections_shed_total) instead of being routed or proxied. |
CONNECTION_RESERVE | 256 | Headroom ABOVE MAX_CONNECTIONS before Node's own hard ceiling (server.maxConnections) is reached. Without it, the socket that tips the count past MAX_CONNECTIONS has nowhere left to be answered from: Node destroys it in C++ before any 503 can be sent. |
TOKEN_MAX_AGE_SEC | 86400 | How long a signed token stays verifiable at all. A visitor still waiting keeps their place past it (QM-391): once their token is half the shorter of this and QUEUE_COOKIE_MAX_AGE_SEC old (6 h with both defaults), /api/status and /events re-sign the same place with the current keys and re-set both queue cookies. Only for the browser whose qms_<room> cookie holds the place, in the room's current generation, while the place is still waiting or pre-queued; a pass, a lapsed or ejected place, or a caller matched only by fingerprint gets nothing. A token already past this age is still refused. Lowering it therefore does not cut a long wait short for a visitor whose page is open; it bounds how long a token copied out of a log stays usable. |
REFRESH_ENDS_PER_SEC | 200 | At most this many open /events streams are ended per second for their token refresh (QM-391). Streams that fall due together wait their turn, still receiving status frames, instead of all reconnecting in the same instant. The drain goes faster only when this rate would not end every waiting stream before its token lapses. |
SSE_FANOUT_CONCURRENCY | 32 | How many /events status pushes one fan-out slice keeps in flight at once (Notion 719; minimum 1). On STORE=valkey each push is one Valkey round trip, so a pass over many streams is bound by that latency unless pushes overlap. Each stream still has at most one push in flight, and its frames go out in order. |
SSE_FRAME_GOVERNOR | 1 | Frame governor for /events (Notion 747, P2-0). 1: a waiting visitor far from the front is sent a new frame (place, ETA) at most every T = the ETA × SSE_FRAME_ETA_PERMILLE/1000, kept between SSE_FRAME_MIN_INTERVAL_MS and SSE_FRAME_MAX_INTERVAL_MS (SSE_FRAME_NULL_ETA_MS when there is no ETA), instead of on every promotion. A displayed place is never better than the truth, only up to T behind it. Anything else reaches the stream at once: a state change (paused, resumed, bypass), the rate, the operator message or other room settings, the schedule and the doors opening, an eject (also of the visitor's own ticket), a room reset, an admission, an expiry. Visitors within SSE_FRAME_NEAR places of the front always get every change. The 5 s heartbeat then re-sends a stream's last frame without reading the store (a scheduled frame gets a fresh now), so the waiting page's watchdog (13 s +-2 s, fixed per page load) stays quiet. 0 restores a store read per stream per change and per heartbeat. |
SSE_FRAME_MIN_INTERVAL_MS, SSE_FRAME_MAX_INTERVAL_MS | 1000, 15000 | Floor and ceiling of T. A far visitor's presence is refreshed only when its frame is computed, so in a room that judges presence (presenceSec and maxConcurrent both set) T is also cut to keep the longest gap between computed frames (T + the 5 s heartbeat grid − 1 s) within a third of presenceSec (default 30 s: T ≤ 6 s, never below 1 s). |
SSE_FRAME_ETA_PERMILLE | 50 | T as a share of the visitor's ETA, in thousandths (50 = 5%). |
SSE_FRAME_NULL_ETA_MS | 5000 | T for a visitor with no ETA (paused room, rate 0, no drain data yet). |
SSE_FRAME_NEAR | 100 | Visitors this close to the front (or past it) are never governed: every change reaches them at once. |
SSE_FANOUT_MIN_PASS_MS | 250 | At most one change-triggered fan-out pass per room per this many ms (0 disables). The first change after a quiet spell runs at once; any number of changes inside the interval become one trailing pass, so the last change is never lost. The 5 s heartbeat pass is not limited. |
SSE_MAX_AGE_MS | 600000 | Longest a visitor /events stream is held open (0 disables), plus 0-50 % per stream. At the end the server sends refresh and closes; the waiting page reopens once. It is what reaps a stream whose client is gone behind a proxy (writes still succeed, nothing else tells). A stream whose ticket is terminal (expired, ejected, passed, closed room) is closed right after its final frame regardless (Notion 843); see qm_sse_streams_ended_total{reason}. |
SSE_FAR_POLL | 1 | 0 turns the far-poll hint off (Notion 850): every visitor streams, as before. |
SSE_NEAR_POSITION | 20000 | A ticket at this position or nearer streams; one farther is told transport: "poll" unless SSE_NEAR_SEC makes it near (Notion 850). Sized so one room's streams stay a small share of the edge's concurrent-connection ceiling seen in the 2026-11-13 windows (about 285-300k fleet-wide). |
SSE_FAR_POLL_MIN_SEC | 20 | The shortest pollMs a far ticket is told, in seconds (Notion 854). It was 10 s until the 2026-11-14 windows 26-27, where about 90 /api/status requests per source IP and second were blocked by the DO edge; the far polls are the volume the edge sees. |
SSE_FAR_POLL_MAX_SEC | 120 | The longest pollMs, in seconds, and the value when the ticket has no ETA (Notion 854). Raised from 60 s with the minimum. At most 120 s after a failed poll too. A far ticket sees its place move at this pace, and a ticket that becomes near is still noticed in time: pollMs is ETA / 10, so it shrinks as the turn approaches. |
SSE_NEAR_SEC | 300 | A ticket within this ETA (seconds) streams, up to position SSE_NEAR_MAX_POSITION (Notion 850). Five minutes: a far ticket that becomes near is noticed within one poll (at most SSE_FAR_POLL_MAX_SEC, 120 s) and is streaming well before its turn. |
SSE_NEAR_MAX_POSITION | 100000 | The most places the ETA test of SSE_NEAR_SEC may reach (Notion 850). Without it the streams grow with the drain rate (5 minutes at about 950 admissions/s is 285k, the edge's ceiling). |
HOT_SNAPSHOT | off | Room snapshot fast path (Notion 748, Phase 2a; STORE=valkey only, no effect on STORE=memory). off: every status poll and SSE frame is answered by the Valkey script. rooms: only the rooms in HOT_SNAPSHOT_ROOMS use it. all: every room. With it on, each instance keeps a snapshot of every room it was asked about in the last HOT_SNAPSHOT_HOT_MS (one cheap room_snap call per room every HOT_SNAPSHOT_REFRESH_MS, and at once, within HOT_SNAPSHOT_EARLY_MS of the last, when the room changes on any instance) and answers a waiting visitor's /api/status and /events frame from it plus two reads of the visitor's own records, with no script. Notion 773: so is the waiting page's POST /api/join that follows the page load of a new visitor (the /w/ route has just given them a ticket, so this second join used to cost a second join script): when it presents a waiting ticket of the room's current generation, held by the caller, whose stored session, fingerprint and address already match the request (so the script would only confirm them), it is answered from the snapshot plus three reads (own, ej, liveg) with the same reply and the same token handling. Any request that would change a stored identity, address or live count, or that is not a waiting ticket, still runs the script. Follows HOT_SNAPSHOT_STATUS. Anything else still takes the script, unchanged: admission and every write; an admitted, passed or expired ticket; a visitor within HOT_SNAPSHOT_NEAR places of the front; an open that is due or within 500 ms; admin lookups; a fenced, recovering or mid-draw room; a token of a later generation than the snapshot's; and any request while the snapshot is older than HOT_SNAPSHOT_MAX_AGE_MS. What changes for a visitor: the place and ETA may trail the truth by up to one snapshot age (typically 250 ms, never more than HOT_SNAPSHOT_MAX_AGE_MS) after an admission, a purge or a room reset; a place is never shown better than the truth, and an eject shows at once. With HOT_SNAPSHOT on, a waiting visitor's frame may lag a change by up to HOT_SNAPSHOT_MAX_AGE_MS. A bypass room is always answered by the script. Safe in a rolling deploy (old and new instances write the same fields). Roll it out as a room allowlist first (rooms), watch qm_snapshot_* (see Metrics), and widen it only after a week of clean metrics. Rollback is unsetting it and restarting. |
HOT_SNAPSHOT_ROOMS | empty | Comma-separated room ids for HOT_SNAPSHOT=rooms. Read at boot: changing it needs a restart. |
HOT_SNAPSHOT_STATUS, HOT_SNAPSHOT_SSE | 1, 1 | Switch the status polls and the SSE frames of the rooms above on and off separately (0 = that kind takes the script). |
HOT_SNAPSHOT_REFRESH_MS | 250 | How often a hot room's snapshot is refreshed on this instance (0 turns every automatic refresh off: tests only). N instances cost N × 1000/this room_snap calls a second per hot room, about 60 to 250 µs of Valkey each. |
HOT_SNAPSHOT_MAX_AGE_MS | 1000 | A snapshot older than this (counted from when its refresh was sent) is refused: the request takes the script. This is the hard bound on how stale a place can look, including when Valkey stalls. Keep it above HOT_SNAPSHOT_REFRESH_MS. |
HOT_SNAPSHOT_EARLY_MS | 100 | A change notice (a promotion, an eject, a state or config write, on this or another instance) refreshes the snapshot early, but not sooner than this after the previous refresh. A lost notice costs at most HOT_SNAPSHOT_REFRESH_MS. Lower than the default means fresher status polls, re-joins and the SSE frames between passes, and more room_snap calls per second per instance; the SSE pass itself no longer depends on it. |
HOT_SNAPSHOT_HOT_MS | 30000 | A room nobody has asked about for this long is dropped from the cache and no longer refreshed. |
HOT_SNAPSHOT_NEAR | 100 | A visitor with at most this many places ahead is answered by the script, so the last places and the moment of passing are exact. 0 leaves only the visitor at the very front to the script. |
HOT_SNAPSHOT_EJ_CAP | 8192 | A room with more live ejects than this (holes in the line) does not use the snapshot (the script answers; qm_snapshot_requests_total{reason="ej_overflow"}). |
HOT_SNAPSHOT_EXACT_EJECT | 1 | 1: the visitor's own ejected state is read from Valkey on every answer, so an eject shows at once (one extra read). 0: it shows at the next snapshot refresh. |
HOT_SNAPSHOT_SEEN_FLUSH_MS | 1000 | Presence (last-seen) of waiting visitors answered from the snapshot is buffered and written once per interval per room (seen_put), not on every answer. Presence only matters in a room that sets presenceSec and maxConcurrent; keep the interval well under a third of presenceSec. In a room with presenceSec >= 60 a ticket already written less than presenceSec / 3 ago is not written again (Notion 836, qm_presence_skipped_total), so the stored last-seen is up to 20 s older than the last request at 60 s. The Valkey judge allows for it: it counts a holder absent after presenceSec + presenceSec / 3 (80 s at 60) without a stamp, which still covers a holder whose gaps reach 40 s (a dead stream before the page falls back to polling). The cost: an absent holder's slot is held up to presenceSec / 3 longer than before and than the in-process store; never shorter. Rooms below 60 s, or without maxConcurrent, are unchanged. |
HOT_SNAPSHOT_CHECK | 0 | 1 (needs HOT_SNAPSHOT=rooms or all; for rooms the room must be in HOT_SNAPSHOT_ROOMS) answers /api/check for a visitor who already holds a live door session from one atomic Valkey read (check_read: 6 to 8 µs idle, 18 to 20 µs under the local 3-instance bench) instead of the check script (54 µs idle, 100 to 125 µs under the same bench). A new admission, a re-key, a queue answer, a due schedule, a fenced room, stale URL rules and anything the read cannot prove all run the script exactly as with the flag off (qm_snapshot_requests_total{kind="check",path="fallback",reason=…}); it never admits anyone the script would refuse. A fast answer sends no door key (none is bound). Read at boot, per room, off by default. A room whose idle limit (sessionTtlSec) is under ten times HOT_SNAPSHOT_TOUCH_MS + HOT_SNAPSHOT_TOUCH_FLUSH_MS (50 s at the defaults) stays on the script (reason="short_session"), because the buffered session slide could otherwise land after the sweep that ends the session. Cost of turning it on: a visitor who falls back costs one extra read first. |
HOT_SNAPSHOT_TOUCH_MS | 4000 | With the check fast case on: a live session's last-used time (adm.last, which the idle limit counts from) is written only when the stored one is at least this old. Together with HOT_SNAPSHOT_TOUCH_FLUSH_MS it is how much earlier than the visitor's last page view a session can end: 5 s at the defaults, never later. 0 writes on every check. |
HOT_SNAPSHOT_TOUCH_FLUSH_MS | 1000 | The buffered last-used times are written to Valkey once per interval per room, one adm_touch call per 1,000 sessions (a compare-and-set: it never revives an ended session or moves a time back). |
HOT_SNAPSHOT_PAT_FLUSH_MS | 1000 | With the check fast case on: URL-rule hit counters (the ones the console shows per rule) are summed in the process and written once per interval per room (pat_put). Hits counted against rules that were edited before the write are dropped. |
MONITOR_TOKEN_TTL_SEC | 604800 | How long a Share monitor link stays live before it expires on its own; seven days by default. Expiry is independent of revocation: a link can be revoked earlier from the console, and an expired one cannot be re-copied. |
EMAIL_NOTIFY | (unset) | 1 (also true/yes/on) enables POST /api/notify, the turn-notification capture, and the e-mail field on the waiting page. Off by default and the page hides the control entirely when it is off, because without SMTP (below) this server records the intent and sends nothing itself, and offering a channel that goes nowhere is worse than not offering one. With it off the route answers 404 email_notify_disabled. When on, an address is kept with its place in line and deleted when the ticket ends, or up to LAPSED_TTL_MS (24 h) later if its entry window lapsed: the ticket ends when it is admitted, ejected or purged, or its room is deleted; after a lapse, a visitor who comes back keeps the address on the new ticket. No entry is kept more than 24 h after it was filed, and a request against a ticket that has ended is refused (409 ticket_ended). With STORE=memory it is in this process's memory, and every restart or deploy loses all of them. With STORE=valkey it is in the shared Valkey (qm:notify:{room}), so the console on every instance sees it. Valkey RDB snapshots and provider backups can hold a copy after deletion until they rotate out. It is never written to Postgres (events or audit), the logs or /metrics, and never shown to anyone unmasked (the console's visitor drill-down sees al•••@e••••••.com). Nothing in this build can export them. This build sends mail only when SMTP_HOST and SMTP_FROM are also set (two e-mails per address, Notification e-mail); without them it sends nothing, and POST /api/notify answers delivery: "recorded". Turning it on raises a warning at boot and in /api/admin/health warnings, so the console badge says so too; the waiting page tells the visitor the same. |
SMTP_HOST | (unset) | The SMTP relay that sends the notification e-mails (Notion 746, Notification e-mail). Unset: nothing is sent. Mail goes out only with EMAIL_NOTIFY on, this set and a valid SMTP_FROM. |
SMTP_PORT | 587 | The relay's port. The default is 465 when SMTP_SECURE=tls. |
SMTP_SECURE | starttls | starttls (the connection is upgraded to TLS; a server that does not offer it is refused, never used in the clear) or tls (implicit TLS, port 465). none sends in the clear and is accepted only for a loopback host or with SMTP_ALLOW_PLAINTEXT=1. |
SMTP_USER, SMTP_PASS | (unset) | AUTH PLAIN, or LOGIN when PLAIN is not offered. Never printed or logged; set them as secrets. |
SMTP_FROM | (unset) | The sender, [email protected] or Queue <[email protected]>. Required for mail to be sent. |
SMTP_HELO | (the host name) | The name sent in EHLO. |
SMTP_CA_FILE | (unset) | A PEM file of extra trusted certificate authorities for the relay (a private CA). Certificates are always verified. |
SMTP_ALLOW_PLAINTEXT | (unset) | 1 lets SMTP_SECURE=none talk to a host that is not loopback. Do not, over an untrusted network. |
SMTP_TIMEOUT_MS | 15000 | How long one SMTP step may take before the attempt fails temporarily. |
SMTP_QUEUE_MAX | 1000 | E-mails that may wait in this instance's send queue. A full queue refuses more (qm_email_dropped_total). |
SMTP_RATE_PER_SEC | 5 | E-mails this instance may start per second. |
SMTP_RATE_PER_MIN | 300 | E-mails the whole fleet may start per minute (one counter in Valkey). |
SMTP_CONCURRENCY | 2 | SMTP connections this instance holds open at once. |
SMTP_MAX_ATTEMPTS | 4 | Attempts at one e-mail before a temporary failure is given up on. |
SMTP_RETRY_BASE_MS | 5000 | The wait before the first retry; 4x for the second, 16x for the third, with jitter. |
EMAIL_NOTIFY_AT | 50 | The place at or below which a visitor is e-mailed that their turn is near, for a room with no notifyNear of its own. |
NOTIFY_SCAN_MS | 5000 | How often the leader looks for e-mails that are due. |
ENV_CHECK | (unset) | The boot comparison of the environment with ops/prod-env.json (Env drift). Unset: on under NODE_ENV=production, off elsewhere. 0 off, 1 on. |
ENV_MANIFEST | ops/prod-env.json | The manifest file the boot check reads. |
MANDRILL_WEBHOOK_KEY | (unset) | The key Mandrill shows for the webhook that reports what happened to your mail after SMTP said 250 (Notion 753, Delivery status). Unset, POST /api/hooks/mandrill is off and answers 404 to every method. At least 16 characters and different from ADMIN_KEY, PUBLIC_API_KEY, SECRET, EDGE_SECRET, STOCK_API_KEY and LOADTEST_KEY, or the server refuses to start. Needs MANDRILL_WEBHOOK_URL. |
MANDRILL_WEBHOOK_URL | (unset) | The webhook's URL exactly as it is typed in Mandrill's webhook settings, for example https://qm.weekday100.com/api/hooks/mandrill. Mandrill signs it, so scheme, host, port, path, a trailing slash and a query string must match character for character. It is not derived from PUBLIC_URL or the request's Host, which behind Cloudflare may differ from what Mandrill was given. Required with MANDRILL_WEBHOOK_KEY and must be an http(s) URL, or the server refuses to start; a path other than /api/hooks/mandrill is a boot warning. |
NOTIFY_LIMIT_PER_MIN | 20 | Per-address POST /api/notify budget. A visitor sets an address once and maybe corrects it once; more than a handful a minute from one address is a script. 0 disables. Per instance with STORE=valkey: each instance keeps its own count, so N instances allow one client up to N× this across the fleet; Cloudflare's edge rate limiting is the fleet-wide control. |
REDEEM_LIMIT_PER_MIN | 60 | Per-address POST /api/redeem budget. A code is typed once or twice; more than that from one address is guessing. 0 disables. Per instance with STORE=valkey. |
STOCK_API_KEY | (unset) | The shop's key for the stock API (POST and GET /api/stock/:roomId, Stock control) and for POST /api/release (a buyer's session ended at once when they reach payment, same section). Its own secret: not PUBLIC_API_KEY (which is distributable and sits in every connector, Worker secret and WordPress option) and not ADMIN_KEY; neither of those opens the stock API, and this key opens nothing but the shop's own two calls (stock and release). Sent as Authorization: Bearer only. Unset, the shop stock API is off and answers 404 stock_api_disabled to everyone; the operator's POST /api/admin/rooms/:id/stock is unaffected. At least 32 characters and different from ADMIN_KEY, PUBLIC_API_KEY, SECRET, EDGE_SECRET and LOADTEST_KEY, or the server refuses to start (openssl rand -hex 32). Give it to the shop's server and nobody else; rotate it by changing it on both sides. |
STOCK_LIMIT_PER_MIN | 1200 | Per-address budget for the shop's stock calls, POST and GET /api/stock/:roomId (POST /api/release has a bucket of its own of this size). A shop is a few addresses calling once per order, so this is a ceiling, not a pace. 0 disables. Per instance with STORE=valkey. |
REDEEM_FAIL_LIMIT, REDEEM_FAIL_WINDOW_SEC | 5, 600 | A waiting place that presents this many invalid codes inside the window is refused (429 redeem_locked, Retry-After) until the window ends, even with the right code. Per instance and per ticket: a fresh ticket starts clean, which is why the per-address budget exists too. |
NOTIFY_MAX_ENTRIES | 50000 | Hard ceiling on stored notification intents, so an address book cannot be pushed into this process until it runs out of memory. Oldest entries are evicted first. STORE=memory only: with STORE=valkey an entry needs a signed ticket, so a room's hash is bounded by the places it has handed out, and each entry goes when its ticket ends. |
QUEUE_COOKIE_MAX_AGE_SEC | 43200 | Lifetime of the queue cookies (qm_<room>, qms_<room>), counted from when they were last set. A waiting page that stays open has them re-set with its token refresh (see TOKEN_MAX_AGE_SEC); a browser that closes the page for longer than this loses the qms_<room> proof and, with it, the place. |
COOKIE_SECURE | (unset) | 1 forces Secure on cookies even when this server sees plain HTTP (TLS terminated upstream by a proxy that sends no X-Forwarded-Proto, or is not on TRUST_PROXY_IPS). Without it, cookies are still Secure on a request whose Host is the host of an https:// PUBLIC_URL. |
CLAIM_COOKIE_DOMAIN | (unset) | A bare parent hostname shared by the waiting room and the protected site (weekday100.com). Set, POST /api/claim also sets the 60 s qm_claim_<room> cookie on it (Domain=<this>; Path=/; HttpOnly; Secure; SameSite=Lax) so a server-side connector can forward it as X-QM-Claim. Anything but a bare hostname (scheme, port, path, leading dot, an address) is ignored and logged once at start. See The waiting-room claim below. Also the domain of the qm_w_<room> waiting marker (see Waiting cap and closing a room). |
PROXY_TIMEOUT_MS | 30000 | Inline mode only: how long to wait for the app behind a room's proxyOrigin before answering 504. See Two deployments below. |
PROXY_ALLOW_PRIVATE | unset | 1 lets a room's proxyOrigin (and the health probe of it), and the health probe of a snippet room's targetUrl, reach loopback, RFC1918, link-local/cloud-metadata and other private addresses, which are refused by default. A refused probe reads down, with targetHealth.blocked naming the address; nothing is sent to it. Autotune makes no decision on a refused probe and holds the rate; after 3 refused in a row it undoes its own raise, once, back to the rate the room had before autotune raised it (a cut is held, and a rate an operator set is left alone). The base is kept in the room's config (written with the rate), so it survives a failover or a restart: the new leader falls back the same way. An operator's rate set while the fallback is being written is not overwritten. Set it only when the app really is on the LAN. See Two deployments below. |
PROXY_IDLE_TIMEOUT_MS | 60000 | Inline mode only: how long a response that has already started may go without a byte before both sockets are cut. A gap, not a total: a stream or a download is never cut while it is delivering. Lower it if your app has no long-lived streams. |
HEADERS_TIMEOUT_MS | 20000 | Slowloris guard. |
REQUEST_TIMEOUT_MS | 60000 | Whole-request timeout. |
PROTECTION_MODE | monitor | Server default for bot scoring: off, monitor (score and count, refuse nothing) or enforce (refuse a place in line above the threshold). Per-room protection.mode overrides it. Start on monitor and read the Security panel before you enforce anything. |
PROTECTION_WARN_AT | 40 | Score at which a request is counted as a warning. |
PROTECTION_BLOCK_AT | 70 | Score at which enforce refuses a place in line. Raising it makes the classifier more forgiving; lowering it below ~55 starts putting circumstantial-only clients in reach of a block. |
PROBE_EVERY_MS | 12000 | How often the server probes each room's target itself, on a fixed clock; measurement and autotune do not stop when a dashboard tab closes, and every operator sees the same numbers. Drives the target_down alert and the response-time figure. 0 disables probing; otherwise the minimum is 1000, and a lower value is raised to 1000 with a startup warning. Each distinct URL is probed once per interval however many rooms share it, and the probes are spread over the first 80 % of the interval. |
PROBE_TIMEOUT_MS | 8000 | How long one of those probes waits before the target counts as down. The probe only times the response headers and discards the body. A status under 500 counts as reachable; a 5xx counts as down, along with a network error or a timeout. An app answering every request with 500 is not up, and "something is listening" is not the question you are asking during an incident. |
PROTECTION_ALLOW_IPS | (empty) | Comma-separated addresses that are never scored. Your own synthetic monitoring and load tests belong here. |
SHUTDOWN_GRACE_MS | 250 | How long an idle or SSE connection gets before it is cut. A socket that is mid-proxy-response (inline mode) is never cut here (only the hard ceiling below applies to it), so a deploy does not sever a customer's own page mid-transfer. |
SHUTDOWN_DRAIN_MS | 2000 (15000 when any room is inline) | Hard ceiling on the whole stop. A stuck socket must never turn a deploy into a hang. An inline deployment holds proxied responses to a longer floor by default (2000ms was measured truncating a real proxied download on every deploy), but an operator who sets this explicitly always gets exactly that value, inline or not: with SHUTDOWN_DRAIN_MS=3000 set explicitly on an inline install and a hung origin, the process used to still drain for the full 15000ms, which SIGKILLs mid-drain under any terminationGracePeriodSeconds below that. Set it yourself if 15s is longer than your platform's grace period. |
QM_FORCE_LOCK | (removed) | Removed in step 5 with the data-directory lock. Set, it is ignored with a boot warning, like DATA_DIR. |
QM_IGNORE_CORRUPT_SNAPSHOT | (removed) | Removed in step 5 with snapshot.json. Set, it is ignored with a boot warning, like DATA_DIR. |
HISTORY_RETAIN_DAYS | 90 | How long hourly rows are kept: in Postgres with SIDESTORE=pg, in this process's memory with SIDESTORE=memory. Reports stop showing a row once it is older than this, and older rows are deleted. |
SIDESTORE | memory | Where operators, monitor links, the audit log, timeline notes, metrics buckets and hourly history are kept: memory or pg. memory keeps them in this process only, so a restart empties them (development and tests). pg keeps them in Postgres at DATABASE_URL: the schema is migrated at boot and everything is loaded before the server listens. pg needs SECRET set. With STORE=memory it assumes a single instance (another instance does not see a new monitor link or operator until it restarts); with STORE=valkey every instance re-reads operators, monitor links and timeline notes when another changes them (see RESYNC_MS). file was removed in step 5 and refuses to start by name (see Refusals); anything else refuses to start too. |
STORE | memory | Where queue state lives. memory: diskless, development only. The in-process engine writes nothing to disk, so every restart starts empty (with the demo room), and NODE_ENV=production refuses it. valkey keeps room state in Valkey at VALKEY_URL and journals every change to the events table in Postgres; it requires SIDESTORE=pg, SECRET and VALKEY_URL, and refuses to start naming each one that is missing. What works on Valkey: rooms and their config, join, status, the door check, ticks and admission, sessions and door keys, admin eject, flush and purge, URL targeting (urlPatterns, hit counters, the URL tester), autotune, stats and metrics, scheduled opens (opensAt, branding.opensAt, setOpensAt), the pre-queue (preQueueMaxPerIp) and its random draw at the open; no call answers not_supported_yet. Several instances can share one Valkey and one Postgres behind a load balancer with no sticky sessions: see Several instances (STORE=valkey). The drawn order of each open is kept in the Postgres table open_orders (about 8 bytes per pre-queue entry, one row per 20 000 entries; the open event refers to it). The leader prunes both (see EVENTS_RETENTION_HOURS): open_orders rows go once the open event they belong to has, and a deleted room's rows go at once. Size the Postgres disk for the retention window and watch it. A room whose rebuild finds an open it cannot replay (the open_orders rows for it missing or short, or its order naming a pre-queue entry the journal never enrolled) stays fenced rather than mint tickets nobody owns: every call on it answers recovering, the rebuild is retried, and the console logs recovery rebuild <room>: rebuild <room>: … (naming the seq for missing rows) at most once a minute. To recover it, restore that room's open_orders and events rows from a Postgres backup taken after the open; the next retry rebuilds the room and unfences it. Never delete or edit its events rows to get past it. Changing IPV6_PREFIX_BITS needs the queue drained first, because the per-network keys already in Valkey were written with the old prefix. Any request (visitor or console) whose room-state call fails because Valkey is unreachable, not serving (READONLY, LOADING, MASTERDOWN, CLUSTERDOWN, TRYAGAIN) or does not answer within VALKEY_COMMAND_TIMEOUT_MS answers 503 storage_unavailable with Retry-After: 2; a command whose reply was lost is never re-sent, so a retried join cannot mint a second ticket. A Postgres failure is not this: joins and admissions answer 503 storage_unavailable when their journal commit fails (queries time out after 10 s), and other routes keep their own handling. Any other value refuses to start. |
VALKEY_URL | none | Valkey connection URL, read only with STORE=valkey (required then). rediss:// connects over TLS verified against the system CAs. The db index in the path is the one used. |
VALKEY_PREFIX | qm: | Prefix of every key the server writes in Valkey, and of its control channel (<prefix>ctl), with STORE=valkey. Two deployments on one Valkey need different prefixes. |
QM_LUA_COST | 8 | With STORE=valkey, how much server-side time per Lua script is measured (Notion 844). 0 = off: the scripts run exactly as before and nothing is written. 1 = every call is timed. N = a random 1 call in N is timed and its time and call scaled up by N. Integer, 0 to 1000; anything else is 8 (a bad value is named at boot, with the 8 it falls back to). Cost, measured on Valkey 8 (interleaved runs, best of 9 of 40,000 calls; lua-micro.mjs run-to-run noise is larger than this): about 1 to 2 µs more per script call at the default 8 (a 45 µs join is 2 to 4% slower), about 3 µs at 1, nothing at 0. The timed calls write two counters (HINCRBY) into the hash <VALKEY_PREFIX>stat:luacost, so a script that only read before writes on 1 call in N. Results: qm_valkey_lua_server_* in Metrics, and tools/capture-window.mjs. |
VALKEY_FUNCTIONS | on | With STORE=valkey, how the Lua scripts are called (Notion 848). On (the default; anything but the values below): at boot the server loads every script as one Valkey Function library named after a hash of the script sources (qm_<16 hex>) and calls them with FCALL, which does not rebuild the shared Lua helpers on every call (Notion 846: about 20 µs a call hot, about 40 µs at concurrency 1). 0, off, false or no: the old path, EVALSHA of each script, nothing loaded with FUNCTION. The old path is also taken, with a log line saying why, when Valkey refuses FUNCTION LOAD. qm_valkey_script_path in /metrics shows which one is in use. See Valkey Functions. |
VALKEY_COMMAND_TIMEOUT_MS | 2000 | With STORE=valkey, how long one Valkey command may go unanswered before it fails and the request answers 503 storage_unavailable. Integer, 100 to 60000: a value outside the range is clamped to it and a value that is not a number falls back to 2000, each with a boot warning that names the variable. Raise it only if a slow or distant Valkey trips it under normal load; a higher value holds requests open longer while Valkey is stuck. It does not bound what each Valkey connection sends when it (re)connects (AUTH, SELECT and the INFO ready check): those may take up to 10 s (the connect timeout) before the connection is dropped and retried, so a Valkey that is up but answers slower than this value still connects. |
NODE_ENV | (unset) | production (read trimmed and in any case) is the production rule: the server refuses to start unless STORE=valkey and SIDESTORE=pg are both set, and names each one that is missing (see Refusals). It also lists an unset EDGE_SECRET under hardening (see Cloudflare edge secret) and switches off test-only hooks (QM_TEST_VALKEY_COUNT, which adds a per-request Valkey command count header, QM_TEST_DROP_CTL, which drops pub/sub messages, QM_TEST_ROOM_EVENT_DELAY_MS, which delays room events, QM_TEST_STORAGE_FAIL_FILE, which makes storage read as failing to alerts, QM_TEST_JOURNAL_FAIL_FILE, which makes this instance's journal commits fail, QM_TEST_ALERT_HOLD_FILE, which holds one alert frame past its bound, QM_TEST_HISTORY_SAMPLE_MS, which shortens the history sample period, QM_TEST_NO_TICK, which stops one instance's engine tick, QM_TEST_NOTIFY_TTL_MS, which shortens the notify intent bound, QM_TEST_NOTIFY_FAIL_FILE, which makes notify deletes fail, and QM_TEST_ADMIN_ACK_MS, which shortens how long an admin write waits for its commit). |
QM_TEST_VALKEY_COUNT | unset | Test hook, never set in production: 1 with STORE=valkey adds x-qm-valkey-commands (the Valkey commands the request sent) to every response and turns off the Valkey client's auto-pipelining. |
RESYNC_MS | 5000 | With STORE=valkey, how often each instance checks that its copy of the operators and monitor links is current (the side_rev row in Postgres) and asks Valkey about the console sessions on its open admin streams. A change made on another instance normally arrives at once over Valkey pub/sub; this check repairs a lost message within this long. Operator keys, operator console sessions and monitor links are refused with 503 storage_unavailable once the copy has not been confirmed for 3× this (at least 15 s), for example while Postgres is unreachable; ADMIN_KEY still works. The same check compares the rooms revision in Valkey (<prefix>roomsrev, moved by every room create, edit and delete) and, when it moved, rebuilds this instance's copies of the room config that decide whether a request is gated: sentinel protection, the inline host index, and the last known config onBackendDown answers from while Valkey is unreachable. A copy that fails to rebuild is retried on the next check, then less often while it keeps failing (doubling up to 60 s, for example while a room is being recovered); a moved revision and a reconnect to Valkey always rebuild them all at once. Integer, 100 to 600000. |
QM_TEST_ROOM_EVENT_DELAY_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): holds back the Postgres commit of every room config event (upsertRoom, schedule change) by this many ms, to test that another instance's open waits for it (Notion 627). A boot warning names it when it is on. |
QM_TEST_DROP_CTL | unset | Test hook, never set in production (ignored with NODE_ENV=production): comma-separated pub/sub message kinds (acct, revoked, rooms, notes) this instance never publishes, to test the RESYNC_MS repair. A boot warning names it when it is on. |
QM_TEST_JOURNAL_FAIL_FILE | unset | Test hook, never set in production (ignored with NODE_ENV=production): with STORE=valkey, while the named file exists, this instance's events-journal commits (and its storage probe) fail, to test one instance's storage fault in a fleet. A boot warning names it when it is on. |
QM_TEST_JOURNAL_FAIL_DELAY_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): with QM_TEST_JOURNAL_FAIL_FILE, a commit refused while that file exists is refused only after this many ms (a Postgres that hangs, then fails), so a test can see what is held while a commit is pending. A boot warning names it when it is on. |
QM_TEST_STORAGE_FAIL_FILE | unset | Test hook, never set in production (ignored with NODE_ENV=production): while the named file exists, this instance reports its storage as failing to the alert frame, to test storage_failing across instances. A boot warning names it when it is on. |
QM_TEST_ALERT_HOLD_FILE | unset | Test hook, never set in production (ignored with NODE_ENV=production): the named file holds a point in an alert frame (evaluate, load or save); the first frame to reach that point renames the file to <file>.held.<n> and waits until that is removed, to test that a frame held past its bound saves and sends nothing. A boot warning names it when it is on. |
QM_TEST_HISTORY_SAMPLE_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): the history sampler runs every this many ms (at least 100) instead of every 15 s, to test that several instances write one history row per room-hour. A boot warning names it when it is on. |
QM_TEST_ADMIN_ACK_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): an admin write's answer waits this many ms (instead of 15 s) for its batched Postgres commit before answering 503 storage_unavailable (the change is already in force), to test that bound (Notion 673). A boot warning names it when it is on. |
QM_TEST_NO_TICK | unset | Test hook, never set in production (ignored with NODE_ENV=production): 1 runs no engine tick on this instance, so a test can tell which instance's tick made a change. A boot warning names it when it is on. |
QM_TEST_SSE_PUSH | unset | Test hook, never set in production (ignored with NODE_ENV=production): 1 writes an SSE comment : qm-push {...} after every /events status push (its sequence number on the stream, its Valkey commands with QM_TEST_VALKEY_COUNT=1, the most fan-out pushes ever in flight, any push that overlapped another on one stream, and the error code of a push that failed). A boot warning names it when it is on. |
QM_TEST_SSE_PUSH_DELAY_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): every odd-numbered /events push of a stream waits this many ms before its status read, so a test can see pushes overlap or reorder. A boot warning names it when it is on. |
QM_TEST_NOTIFY_TTL_MS | unset | Test hook, never set in production (ignored with NODE_ENV=production): bounds each notify intent to this many ms (at least 100) from when it was filed, instead of 24 h, to test that an old entry goes in a room that keeps writing. A boot warning names it when it is on. |
QM_TEST_NOTIFY_FAIL_FILE | unset | Test hook, never set in production (ignored with NODE_ENV=production): while the named file exists, deleting or clearing notify intents fails as an unreachable Valkey would, to test that eject, purge and room delete answer 503 then. A boot warning names it when it is on. |
LEADER_LEASE_MS | 15000 | With STORE=valkey, the lease that makes one instance the leader: the only one that probes targets (PROBE_EVERY_MS), runs autotune and threshold activation, and delivers alerts to ALERT_WEBHOOK_URL, so each happens once for the fleet and not once per instance. The leader renews the lease (<prefix>leader in Valkey) every third of this and stops acting as leader once half of this has passed without a renewal, before the lease can expire, so two instances never act at once; another instance takes over within about this long of the leader dying, and at once after a clean stop, which hands the lease back. The other instances still evaluate alerts and show the leader's target health and autotune notes, read from Valkey. While Valkey is unreachable no instance is leader: probes, autotune, threshold activation and alert delivery pause until it answers again, and nothing falls back to every instance acting. The one alert still sent then is valkey_unreachable (see VALKEY_ALERT_AFTER_MS); keep an external monitor on /healthz as well. Autotune and threshold-activation writes carry the leader's epoch and are refused once another instance has taken the lease, so a stale leader's late write never lands after the new leader's. leader on /healthz says whether this instance leads. With STORE=memory the one process is always the leader. Integer, 1000 to 600000. |
EVENTS_RETENTION_HOURS | 1 | With STORE=valkey, how long the Postgres events journal keeps a room's events that a rebuild no longer reads. The leader deletes a room's events below its rebuild horizon (the oldest checkpoint the checkpoint job keeps; never a rebuilt marker, never the row at the horizon) once they are older than this, so a rebuild or restore folds to exactly what it did before. A room with no checkpoint yet is not touched; a deleted room's events, checkpoints and drawn orders below its delete go at once, whatever this says. Nothing else reads older events (reports come from the hourly history), so this is only a window for looking at raw events by hand. It must exceed the longest rebuild you can have: a rebuild reads Postgres in several statements without a lock, and a prune that reached events it has not yet read would make it commit a wrong room (a long read, then the checkpoint job writing two newer checkpoints, and the prune moving past what the rebuild started from); one hour is far above a rebuild's seconds to minutes. 1 to 8760; 0 is raised to 1 with a warning. |
EVENTS_PRUNE_INTERVAL_SEC | 60 | With STORE=valkey, how often the leader prunes the events journal (see EVENTS_RETENTION_HOURS). 0 turns pruning off and the journal grows without bound (~10 GB an hour at 8 000 joins a second). Up to 86400. |
EVENTS_PRUNE_BATCH | 5000 | Rows one prune statement deletes at most. Each statement is its own short transaction holding row locks only, which never block the journal's inserts. 1 to 5000. |
EVENTS_PRUNE_MAX_ROWS | 1000000 | Rows one prune run deletes at most; the next run continues from the room where this one stopped. Keep it above the journal's write rate times EVENTS_PRUNE_INTERVAL_SEC (8 000 joins a second for 60 s is 480 000) or the backlog never shrinks. GET /api/admin/health shows the last run (eventsPrune.last), /metrics the rows deleted (qm_events_pruned_total). |
EVENTS_PRUNE_PAUSE_MS | 20 | The pause between two prune statements, so a large backlog never takes a Postgres connection or the disk away from the hot path for long. 0 to 60000. |
VALKEY_ALERT_AFTER_MS | 30000 | With STORE=valkey, an instance that has not reached Valkey for this long sends a valkey_unreachable alert to ALERT_WEBHOOK_URL itself, and a resolved once Valkey answers again. With Valkey down no instance leads and every other alert delivery pauses, so this is the page for that outage. Each instance that cannot reach Valkey sends its own: expect one per instance, since duplicate pages are better than none. The value used is at least one lease renewal (LEADER_LEASE_MS/3) plus the Valkey command timeout (VALKEY_COMMAND_TIMEOUT_MS) plus 1 s, because that is how often a healthy instance hears from Valkey; a lower value is raised to that with a startup warning naming both (at the defaults the floor is 5000 + 2000 + 1000 = 8000 ms). The floor grows with VALKEY_COMMAND_TIMEOUT_MS: at its 60000 maximum it is about 66 s, so a real outage pages that much later. A delivery of this alert the webhook did not take is sent again on each later check, up to 5 times in all. Integer, 1000 to 3600000. |
QM_INSTANCE_ID | (unset) | With STORE=valkey, this instance's display name: the instance label on every /metrics series, the instance in GET /api/admin/health and the name alerts give it. A label only: every internal identity (leases, staging keys, pub/sub sender, the counters key <prefix>ctr:<name>:<random>) is <name>:<random>, new on each boot, so instances sharing a name, or a rolling deploy that reuses it, stay correct. Unique names make metrics and alerts easier to read, and are required per scrape target when Prometheus scrapes with honor_labels: true (see Metrics and monitoring). Unset, the name is i:<random>, new on each boot. 1 to 64 characters of A-Z a-z 0-9 . _ -; anything else refuses to start. With STORE=memory it only adds the /metrics label. |
DATABASE_URL | none | Postgres connection URL, read only when SIDESTORE=pg (required then). The connection always uses TLS verified against PG_CA_FILE; any sslmode in the URL is ignored. To use a schema other than public, add options=-c search_path=<schema> to the URL; that schema is the one migrated. |
PG_CA_FILE | certs/do-ca.crt | CA certificate the Postgres server is verified against when SIDESTORE=pg. Verification is never turned off; a missing file refuses to start. |
PG_POOLER | (unset) | Set to 1 (also true, yes, on) when DATABASE_URL points at a connection pooler (DigitalOcean's pgbouncer, Transaction mode) instead of Postgres directly. The app then does not send statement_timeout when it connects (pgbouncer rejects it) and refuses to start unless the database role already has one, greater than 0 and less than 12 s. See Connection pool (pgbouncer). Unset for direct connections. |
PUBLIC_URL | (derived) | Absolute origin this server is reached at, used to build install commands, connector download URLs, waiting-room links and the copyable commands on /docs when the request's own Host is not the public one (behind a proxy that rewrites it). An https:// value also marks cookies Secure on requests for that host, whatever the socket says. With ADMIN_HOST unset its host is also where the console lives: the console answers there once a room is inline (QM-440), no room may be put inline on it (400 reserved_host), and its console surface is never handed to a room. |
ALERT_WEBHOOK_URL | (unset) | Where alerts are POSTed as JSON. Unset means nothing is delivered; conditions are still evaluated on the server and listed in Diagnostics → Alerting, so the console is the alerting. See Alerting below. |
ALERT_WAIT_SEC | 900 | Estimated wait, in seconds, at or above which a room pages. 0 disables. |
ALERT_DEPTH | 0 | Queue depth at or above which a room pages. 0 (default) disables: depth alone is not an incident; a wait nobody will sit through is. |
ALERT_STALL_SEC | 120 | People waiting and nothing let through for this long pages as critical. 0 disables. |
ALERT_FROZEN_SEC | 300 | People waiting in a room that is paused or set to 0/min for this long pages as critical (the forgotten paused room). 0 disables. |
STOCK_CHECK_EVERY_MS | 3000 | How often the fleet leader asks each room's shop stock URL (rooms with the stock check turned on), on its own clock, one request in flight per room. The minimum is 1000; a lower value is raised to 1000 with a startup warning. |
STOCK_CHECK_FAIL_SEC | 120 | A room whose stock check has failed continuously for this long pages as a warning (stock_check_failing) and resolves on the next accepted answer. A failed check never holds or releases the line by itself. 0 disables the alert. |
ALERT_HOLD_SEC | 30 | How long a condition must hold before it fires. Stops a four-second spike from paging anyone. |
ALERT_REPEAT_SEC | 900 | Re-page cadence while a condition is still firing. |
ALERT_EVERY_MS | 15000 | Evaluation cadence. |
GET /api/admin/health reports the effective values, the storage state and any misconfiguration warnings. Check it after every deploy.
The dashboard renders that report behind its Diagnostics button: status, version, uptime, room and visitor counts, SSE streams, rate limits, storage, proxy, memory and every warning, plus two counters to watch: checks for unknown rooms (a snippet pointing at a room id that does not exist here, i.e. a typo or a deleted room) and blocked return URLs (see returnOrigins below). It is a readable view of the payload rather than the raw JSON; pid, the server clock and the key-configuration block are only in the API response. The header also carries an insecure config badge for as long as any warning stands.
Behind a CDN or load balancer (read this one)
Per-IP limits key on the address this server can prove: the socket peer. Behind a CDN every visitor shares that address, so the per-IP limit silently becomes a global limit (600 joins/min for your entire site) unless you tell the server who the proxy is:
TRUST_PROXY=1 # hops between the client and this server
TRUST_PROXY_IPS=10.0.0.7 # the address(es) those hops connect FROM
X-Forwarded-Foris believed only from a peer inTRUST_PROXY_IPS. From anyone else, including every peer whenTRUST_PROXYis set on its own, the client address is the socket address, whatever the header says. That one address is what everything uses: the throttle and SSE caps, the pre-queue identity,PROTECTION_ALLOW_IPSand the bot signals, the audit trail'sip, and theX-Forwarded-Foran inline app receives. So one machine forging 900 different values cannot buy 900 visitors' worth of joins, claim an allowlisted address, or reset its own bot score, and a CDN stays collapsed into one bucket until you addTRUST_PROXY_IPS.- With both set, each visitor gets their own bucket and the proxy is exempt from the socket-address bucket.
- Multiple hops (CDN → your LB → here):
TRUST_PROXY=2, and list the address your LB connects from. - A CDN that connects to you directly comes from a published set of ranges, not one address. List them as CIDR, IPv4 and IPv6 alike:
TRUST_PROXY_IPS=173.245.48.0/20,103.21.244.0/22,2400:cb00::/32,.... There is no built-in preset for any CDN: copy the provider's current list, and update it when they do. A range they add and you have not is a proxy whose visitors share one bucket. Every entry is checked at startup, and one that is not an address or a range (173.245.48.0/33, two entries missing their comma, a hostname) stops the server with that entry in the error: a typo in a trust list either untrusts your real proxy or trusts machines you never meant to. TRUST_PROXY_IPSis also what lets a visitor keep their pass while a CDN moves them between edge nodes; see How a pass is bound to a visitor. Forwarded identities are never accepted from a peer that is not on this list.X-Forwarded-ProtoandX-Forwarded-Hostfollow the same rule. From a peer inTRUST_PROXY_IPSthey decide whether the visitor used HTTPS (theSecureflag on every cookie, the scheme an inline app is told in its ownX-Forwarded-Proto/-Port, the URL your room's rules are matched against) and which host the absolute URLs this server hands out name (the connector manifest, the WordPress update feed, the rendered docs, whenPUBLIC_URLis unset). From anyone else, including every peer whenTRUST_PROXYis set on its own, both are ignored: the scheme is the socket's and the host isHost. A TLS-terminating proxy you have not listed therefore gets cookies withoutSecure; list it, or setCOOKIE_SECURE=1.
The same rule applies to the SSE per-IP cap.
A proxy you have not listed is named, not silent. When forwarded-address headers (X-Forwarded-For, Forwarded, CF-Connecting-IP, X-Real-IP, True-Client-IP) keep arriving from a peer that is not in TRUST_PROXY_IPS (10 or more such requests from the same address within a minute, whether TRUST_PROXY is set or not), the server treats that peer as an undeclared proxy. Behind it, every visitor shares the proxy's one address, so queueMaxPerIp (16 places per address by default) and preQueueMaxPerIp cap the whole room at that many visitors, and the join and check budgets become one budget for the site. The server then:
- adds a warning to
warningson/api/admin/healthnaming the address and the exactTRUST_PROXY_IPS=…line to set (your existing entries plus it), setsproxy.ok: false,proxy.forwardedFromUndeclaredPeer: trueand lists the address inproxy.undeclaredPeers(the console shows it in the header badge); - logs one line, and at most one every 10 minutes while it keeps happening.
One request with a forged header does not trip it. A script sending a stream of them can, so read the address before you copy it: add it only if it is your load balancer or CDN. An address you do not recognise is a client forging the header, and listing it would let that client choose its own address. Changing TRUST_PROXY_IPS is the fix; the warning never changes whose header is believed.
Setting only one of the two is the failure mode to watch for. They are one setting in two variables, so the server refuses to let a half-configuration be silent: it prints the warning at startup, returns it in warnings on /api/admin/health with proxy.ok: false, and the dashboard header turns it into the insecure config badge (the Proxy row reads … · INCOMPLETE). A measured surge through a half-configured proxy loses roughly 94% of its joins to HTTP 429, and the behaviour is otherwise indistinguishable from the queue working correctly.
Cloudflare edge secret
In production this server is reached only through our Cloudflare zone, but its own address (the DO App Platform URL, the container) answers too. A request sent there directly skips every Cloudflare rule, cache and rate limit, and can put any value it likes in CF-Connecting-IP. EDGE_SECRET closes that door: Cloudflare adds a secret header to every request it forwards, and this server refuses any request without it. On DO App Platform this is required, not optional: see DigitalOcean App Platform.
Set it up (in this order, so nothing is refused while you do it):
- Generate a long random value, e.g.
openssl rand -hex 32. Entries shorter than 16 characters stop the server at startup: a guessable secret is worse than none, because it looks like protection. - In the Cloudflare dashboard for the zone: Rules → Overview → Create rule → Request Header Transform Rule (older dashboards: Rules → Transform Rules → Modify Request Header), with Set static header
X-QM-Edge= the value. Deploy the rule. Match only this app's hostname(s) (e.g. Hostname equalsqm.weekday100.com), never All incoming requests. A zone-wide rule adds the secret to every request Cloudflare sends to every origin in the zone: your other apps, and any third-party service a hostname is CNAMEd to (a help desk, a shop platform, a status page). Any of them can log it, and anyone holding it can call this app's own address directly and be treated as Cloudflare, with aCF-Connecting-IPof their choosing. - Set
EDGE_SECRETto the same value on the app and deploy.
What it does once set:
- Every HTTP request (API, console and admin API, SSE, static files, the waiting page, and every inline gate and proxied path) and every WebSocket upgrade must carry
X-QM-Edgeequal to one listed value. Otherwise the answer is403with{"error":"edge_required","code":"edge_required"}, or a minimal403page for a browser navigation. Neither names the header. An upgrade is refused before any socket to the origin is opened. /healthzis the one exemption, because DO App Platform's health check reaches the container directly. It coversGET/HEADof exactly/healthz(a query string is fine;/HEALTHZ,//healthzor an encoded variant are not), and only on a host that fronts no inline room (on an inline host/healthzis the app's own path). The list is one constant,EDGE_EXEMPT, inserver.js.- The client address is
cf-connecting-ip, on every request that passed the check: throttle keys, SSE caps, the pre-queue identity, bot signals, the audit trail'sip, and the rightmostX-Forwarded-Forhop an inline app receives. A forgedX-Forwarded-Formoves nothing. Ifcf-connecting-ipis missing or not an address, the socket address is used and counted (edge.clientIpFallbackTotalon/api/admin/health,qm_edge_client_ip_fallback_total); behind Cloudflare that stays at 0. TRUST_PROXYandTRUST_PROXY_IPSare ignored (see Behind a CDN or load balancer). If they are still set, a warning says so.X-Forwarded-Protois believed on a request that passed the check;X-Forwarded-Hostis not, since Cloudflare passes a client's own through.- The value is never logged, audited or put in a metric, and the header is removed before any request or upgrade is forwarded to a room's
proxyOrigin. - Refusals are counted per instance:
qm_edge_refusedon/metrics(with theinstancelabel onSTORE=valkey) andedge.refusedTotalon/api/admin/health. A steady rate means something is calling the app's own address; a jump to every request means the Cloudflare rule andEDGE_SECRETno longer match.
Rotate without refusing anyone: add the new value to the list (EDGE_SECRET=old,new) and deploy; switch the Cloudflare rule to the new value; then remove the old one (EDGE_SECRET=new) and deploy again.
Unset, nothing changes from earlier releases. With STORE=valkey or NODE_ENV=production the server prints EDGE_SECRET is not set: requests that bypass Cloudflare are accepted at startup and lists it under hardening on /api/admin/health.
Load testing through Cloudflare
A load generator (k6 and the like) reaches production through Cloudflare from a handful of source addresses, so every per-address budget would bound it and the test would mostly measure 429s. LOADTEST_KEY lets an authorized load test be counted per load-test client instead: each client id is one visitor, with one visitor's budgets.
Headers (on every request the load generator sends):
X-QM-Loadtest: <LOADTEST_KEY>X-QM-Loadtest-Client: <id>: one id per virtual user (vu-17, a uuid); 1-128 characters ofA-Z a-z 0-9 . _ : -. Missing or anything else, every such request shares one synthetic visitor (still limited).
What it changes. Only on a request that passed the EDGE_SECRET check and carries the right key, the client address becomes a synthetic one derived from the client id (inside 3fff::/20, a documentation-only range no visitor can have). Every per-address budget follows it, so it applies per load-test client: the join, check, notify, waiting-page, console-page and preview budgets, the SSE per-address cap, queueMaxPerIp, preQueueMaxPerIp, the bot signals and the address an inline app receives in X-Forwarded-For. A client id that exceeds them gets the same 429 a visitor would.
What it does not change. MAX_CONNECTIONS, SSE_MAX_TOTAL, body and URL size limits, room capacity and rates all stay in force. The admin failed-auth lockout (ADMIN_AUTH_FAIL_PER_MIN) and the audit trail's ip stay on the real address. A vouched /api/check?ip= keeps its own key.
Safety. Unset, the headers are ignored. Without EDGE_SECRET they are ignored too, and a warning says so. A wrong value is treated exactly like no header (same answer, same budget) and counted. The value is compared in constant time, never logged, audited, returned or put in a metric, and both headers are removed before a request is forwarded to a room's proxyOrigin. NODE_ENV=production changes nothing: the feature works the same everywhere, and the LOADTEST_KEY is set warning lights the health badge for as long as it is set. Since a key holder can open up to one visitor's budgets per client id, it is a production secret: give it only to whoever runs the test, only for the test. A leaked key lets its holder mint fresh visitor budgets at will (joins, notify e-mails, queueMaxPerIp), and churning client ids can push real visitors' buckets out of the limiter tables (RATE_LIMIT_MAX_KEYS), so rotate it per test. The server refuses to start when it equals EDGE_SECRET, ADMIN_KEY, PUBLIC_API_KEY or SECRET. With IPV6_PREFIX_BITS below 64 the synthetic addresses spread over fewer keys (12 bits at 32), so a large run has load-test clients sharing budgets; keep it at 64 for a test.
Telling the traffic apart. qm_loadtest_requests_total (accepted) and qm_loadtest_rejected_total (wrong value) on /metrics; loadtest.requestsTotal, loadtest.rejectedTotal and loadtest.enabled on /api/admin/health.
Checklist:
- Generate a key:
openssl rand -hex 32(shorter than 32 characters stops the server at startup). - On DO App Platform, set
LOADTEST_KEYon the app (as a secret) and deploy. Check/api/admin/health:loadtest.enabledistrue. - Give the key to the load-test operator over a private channel. The load generator must go through the Cloudflare hostname (the edge check is what makes the key count) and send both headers.
- Run the test; watch
qm_loadtest_requests_totalgrow andqm_loadtest_rejected_totalstay at 0. - When it is over, remove
LOADTEST_KEYand deploy.loadtest.enabledisfalseand the warning is gone. Use a fresh key next time.
Two deployments: snippet and inline
There are two ways to put this queue in front of a site, and they fail differently. Choose on that, not on which is easier to install.
Snippet (default). The site loads a small script; the script asks this server whether the visitor may proceed and sends them to the waiting page if not. The queue sits beside the traffic. If this server dies, the script's check fails and the pages are served unqueued: the site stays up and the protection is gone.
Inline (proxy). DNS for the site points at this server, and every request for that host arrives here. Admitted visitors are forwarded to the app; everyone else gets the waiting page at the URL they asked for. The queue sits on the traffic. If this server dies, the site is unreachable, which is why the CDN failover page in When the queue itself is down is not optional for an inline deployment.
The three shapes side by side. With the snippet, pages come from your site and the tag in the browser asks the queue; if the queue is down, pages load unqueued. The edge connector is a snippet-mode deployment too, but a Cloudflare Worker asks the queue before your site sees the request; if the queue is down, it forwards the request to your site unqueued and marks the response X-QM-Failover. Inline, every request passes through the queue; if the queue is down, the site is unreachable unless the CDN serves a failover page.
Turn it on in the console: Edit (or + New room) → tick Serve this room inline and fill in Internal address of the site behind the queue. Clearing the tick returns the room to snippet mode, behind a confirmation that says so. Or over the API:
curl -sX POST "$BASE/api/admin/rooms" -H "Authorization: Bearer $ADMIN_KEY" \
-H 'Content-Type: application/json' -d '{
"id": "shop",
"targetUrl": "https://shop.example",
"proxyOrigin": "http://10.0.0.5:3000"
}'
targetUrlis the public address: the host visitors' browsers send, and what this server matches an incoming request against.proxyOriginis the internal one, reachable only from this server. Bare origin: scheme, host, port, nothing else. Pointing it back at the public host is refused (proxy_origin_loop); that is an infinite loop through your CDN.- A private or internal
proxyOriginis refused unlessPROXY_ALLOW_PRIVATE=1, including the10.0.0.5in the example above. These are refused: loopback (127.0.0.0/8,::1),0.0.0.0/8, RFC1918, CGNAT100.64.0.0/10, link-local (169.254.0.0/16, which holds the169.254.169.254cloud metadata endpoint;fe80::/10), unique-localfc00::/7(holdsfd00:ec2::254),::and the IPv4-mapped forms of all of them. Whoever can edit a room could otherwise make this server fetch its own network. The check is on the address actually connected to, after DNS, on every new connection, so a hostname that starts resolving to127.0.0.1later (DNS rebinding) is refused at that point; a name with any private answer is refused outright. The server's health probe of the origin is held to the same rule. If your app really is on the LAN, setPROXY_ALLOW_PRIVATE=1. - No
proxyOriginmeans snippet mode. Nothing about an existing install changes because this feature exists. ratePerMinuteacceptsrateas an alias, which is whatGET /api/admin/roomscalls the same field, so a script that reads a room and POSTs it straight back does not have to rename anything first. Sending both is fine if they agree; disagreeing is400 conflicting_field. Any field name outside the documented set is refused (400 unknown_field), not silently dropped. A typo would otherwise look exactly like a change that took.
What changes once a room is inline:
| Snippet | Inline | |
|---|---|---|
| Queue's own routes | /api/*, /w/<room> | under /__qm (/__qm/api/join, …) |
| Monitoring routes | /healthz, /api/version, /metrics | the same, and also under /__qm. Which one a probe gets depends on the address it uses, not on the path: reached on the customer's hostname these are the customer's paths and the visitor gate answers them 503 for ever. Probe the process directly, or use /__qm/healthz and metrics_path: /__qm/metrics. |
| Operator console | / on the queue's own host | /__qm/ on the customer's host: the same page, addressing the same prefixed routes. Bookmark that address, not /: / on that host is the shop. |
| Console sign-in | qm_console, HttpOnly, Path=/api/admin | qm_console, HttpOnly, Path=/__qm/api/admin: the customer's scripts cannot read it, and the key itself is never stored in the browser |
| Door key | in the URL (?sess=), readable by the script | qm_dk_<roomId>, HttpOnly cookie only: nothing in a query string, even under /__qm. Scoped to the room, so clearing one room's key leaves another's alone. |
Ticket token qm_<room> | readable cookie + localStorage + ?token=; this host is ours and the page's own script is the reader | HttpOnly cookie only: nothing in localStorage, nothing in a query string, even under /__qm |
| URL targeting | matches whatever the snippet reported | matches the real request URL |
returnOrigins / tagOrigins / CORS | load-bearing | unused: nothing is cross-origin |
| This server down | site up, unqueued | site down; needs CDN failover |
The prefix is reserved, not decorative: the campaign app has its own /api/*, and the queue must never shadow it. Anything on a proxied host that is not under /__qm belongs to the app.
Room ids starting with dk_ are reserved the same way (QM-533). Room dk_x's ticket cookie would be qm_dk_x, the exact name of room x's door-key cookie: the two overwrite each other in the browser, and the per-host cookie cap files the ticket under room x and expires it with x's cookies. Creating such a room answers 400 invalid_room_id. A dk_ room made before this rule keeps working and can still be edited, but it keeps the collision: recreate it under another id and move the tag over.
The rest of the reserved ids follow from the same rule (546): a room's ticket is kept under qm_<room>, as a cookie and as a localStorage key on the queue host, so no room id may make that name one the queue already uses. Refused on create with 400 invalid_room_id, case-sensitive:
- ids starting with
meta_,notify_oremail_(the waiting page's per-roomqm_meta_<room>,qm_notify_<room>,qm_email_<room>); - exactly
console,theme,lang,admin_key,autotune,autotune_cfg,wait_samples,hidden_series,selected_room,alerts,offline_attempts,origin_down_attempts,preview_theme.consolewould be the console sign-in cookieqm_console; the others are the storage keys of the console and the waiting, offline and origin-down pages on the same origin. A room namedadmin_keywould write its ticket where the console keeps its key.
When the server looks for a ticket among a request's cookies (/api/status, /events), qm_console is never read as one, and cookies under a reserved name are tried only after every other qm_ cookie, so eight rooms' door keys cannot crowd out the real ticket.
The ticket-token row is the same reasoning as the prefix, applied to credentials. Inline, our cookies and our localStorage land on the customer's origin, shared with every analytics tag, chat widget and ad script the site ships, so the token is kept somewhere none of them can reach, and the waiting page persists nothing. It does not need to: /api/join returns the token in its response body on every load, and /api/status and /events authenticate from the cookie when no token= is sent.
Forwarding preserves the visitor's Host and adds X-Forwarded-Host, -Proto, -Port and -For, so a Next.js app behind this builds its own absolute URLs correctly. All four describe the VISITOR's hop, never proxyOrigin: -Port is the port named in their Host, or 443/80 to match -Proto when they did not name one. WebSocket upgrades carry the same four.
The rightmost X-Forwarded-For entry is always the client address this server resolved, so an app that trusts one hop (this server) reads the truth. From a proxy in TRUST_PROXY_IPS the chain it sent is kept to the left of that entry, and its Forwarded, X-Real-IP, CF-Connecting-IP and True-Client-IP pass through. From any other peer those headers are the caller's own words: all of them are dropped and X-Forwarded-For is the socket address alone. TRUST_PROXY / TRUST_PROXY_IPS still apply: they are how this server learns the visitor's address and scheme from your CDN. The -Proto (and the default -Port) sent onward is the scheme your proxy reported only when that proxy is in TRUST_PROXY_IPS; from any other peer it is the scheme of the connection this server actually received, whatever the caller claimed.
When the app itself is the problem:
| What happened | Visitor sees | Also |
|---|---|---|
| App refused the connection / unreachable | 502 + X-QM-Origin: origin_unreachable (origin-down.html on a navigation, JSON to an XHR) | counted per room; one log line a minute naming the room |
proxyOrigin is a private/internal address and PROXY_ALLOW_PRIVATE is not 1 | the same 502 + X-QM-Origin: origin_unreachable (a WebSocket gets 502 too); nothing is sent to the address | counted per room under phase blocked; the room's originErrors.reason and a log line (once a minute per room) name the refused address; the probe reads down with targetHealth.blocked saying why |
| App accepted, then never answered | 504 + X-QM-Origin: origin_timeout after PROXY_TIMEOUT_MS | same |
| App answered, then stalled mid-body | the transfer is cut; headers are already gone, so there is no status code left to send and no honest way to finish the page | counted per room under phase body_stall after PROXY_IDLE_TIMEOUT_MS; a visitor who stopped reading is counted as client_reset instead |
| Queued visitor's XHR or API call | 503 queued + Retry-After + X-QM-Queued: 1 | anything a browser renders gets the waiting page instead; see below |
This process at MAX_CONNECTIONS | 503 + Retry-After (no X-QM-Queued): the offline page, not the waiting page | qm_connections_shed_total; /healthz answers its own 503 with ready:false too; see CONNECTION_RESERVE above |
Past MAX_CONNECTIONS a request is deliberately shed, not queued: there is no "try again in a moment and you'll be let in", the process genuinely has no room. It carries no X-QM-Queued, on purpose: a CDN failover rule that keys on 503 is meant to fire here and show its own outage page, the same as any other real outage. Without CONNECTION_RESERVE, this state was unreachable to answer at all: Node's own server.maxConnections destroyed the socket first, silently, and a hung origin pinning two sockets per stuck visitor for the whole PROXY_TIMEOUT_MS made that ceiling reachable in well under a minute during exactly the failure this product exists for.
X-QM-Queued is what stops a CDN failover rule keyed on 503 from replacing a healthy queue with the outage page, and it is also the signal a customer's app can key on to reload a page whose pass lapsed mid-session instead of failing silently. X-QM-Origin says the site behind the queue is the thing that broke.
Which of the two a request gets. The test is whether a browser will show the answer to a person, not whether the method is GET: Sec-Fetch-Mode: navigate (any method), a browsing Sec-Fetch-Dest, or, for clients that send no Fetch Metadata, Accept: text/html. A <form method="post"> submitted after the pass lapsed is a navigation, so it gets the waiting page; a fetch() asking for JSON gets JSON.
Recovering a page whose pass lapsed. The queued envelope names the room and the engine's own reason (expired, ejected, stale_generation, waiting, at_capacity, …), and Access-Control-Expose-Headers is set so the header is readable even when the call is cross-origin:
{ "error": "…", "code": "queued", "roomId": "shop", "reason": "ejected", "reload": true }
Inline there is no separate waiting-room address (the waiting page is served at the URL the visitor asked for), so re-requesting the current URL is the whole recovery:
const r = await fetch('/api/cart');
if (r.status === 503 && r.headers.get('X-QM-Queued')) { location.reload(); return; }
Without that line the site keeps rendering whatever its code does with a failed request. A visitor who is simply put back in line is told so by the waiting page itself, which names the cause rather than presenting itself as a fresh arrival.
On a hostname this server fronts no room for, the operator console is a bare 404. See ADMIN_HOST above: inline, the console answers on an address literal, localhost and the PUBLIC_URL host, or with ADMIN_HOST set on the names you list, and nowhere else. An inline room whose targetUrl is an address literal (the usual local-development setup) gets that host's pages, but with ADMIN_HOST unset never its /api/admin/*: that address is the console's too, so an admin call sent there is answered by the queue, not forwarded (QM-439). With ADMIN_HOST set that includes the customer's hostname: its /__qm/ console, /__qm/api/admin/* and /__qm/public/admin.html answer 404, and only the visitor paths under /__qm/ remain. A hostname that fronts no room is withheld the console only, ADMIN_HOST set or not (QM-428); the snippet, /healthz, the waiting page and the visitor API still answer there, since that is the address the customer's script tag names.
This is easy to walk into (QM-454): with neither ADMIN_HOST nor PUBLIC_URL set, saving the first inline room from a console on a hostname (say qm.weekday100.com) makes that console, and every monitor link on that host, answer 404 from the next request on. The save still succeeds, and its answer carries a warning (warnings[], code: "console_host_withheld", naming the host) that the console shows after saving. While any inline room exists with both unset, /api/admin/health lists the same reason under configWarnings. The fix is to set ADMIN_HOST (or PUBLIC_URL) to that hostname and restart.
Switching the last inline room on a host back to snippet mode takes the queue's own /__qm/* surface off that host with it, including the console you are probably reading this from, if you administer the queue through the customer's domain. The console warns before that save and moves you to PUBLIC_URL afterwards; a stale /__qm/… address answers 404 {"code":"not_inline_host"} naming where the console went, rather than the generic not-found. Set PUBLIC_URL so it can name it. (With ADMIN_HOST set the console never lived on the customer's domain, so there it is a bare 404.)
None of these make this instance unhealthy: a customer origin going dark is not a reason to take the pod out of rotation, so /healthz stays 200. See Readiness. The counts are on /api/admin/health under inline: gatedTotal, bypassedTotal, originErrorsTotal and a per-room/per-phase originErrors breakdown. The whole block is absent on an install with no proxied room.
What skips the gate
Static subresources are forwarded without a queue check. This is about cost, not politeness: one page of a modern app is 30 to 80 subresource requests, and gating each one would run a queue check, a bot score and a cookie write per file, turning the queue into the bottleneck it was installed to prevent while protecting nothing. Downloading a stylesheet takes nobody's place in line.
A request skips the gate only when all four hold:
- the method is
GETorHEAD; - the path ends in a static-media extension:
js mjs cjs css map, images, fonts, audio/video. Deliberately not.json,.txtor.xml, which are as often an API's answer as a file on disk; - the path as the app will receive it is a plain one: no
;, no percent-escape (%3b,%2f,%2e, even%20), no backslash, and nothing the queue's URL parser had to rewrite (a..segment). The request line is forwarded to your app verbatim, and frameworks strip or decode before they route (/api/stock;.jsis/api/stockto Tomcat and Spring), so a path like that is gated like any page. Its cost is one queue check; nobody loses a place; Sec-Fetch-Dest, when the browser sends it, is not a browsing context (document,iframe,object,embed).
The app's own API is never bypassed. POST /api/checkout is where the scarce thing happens; letting it through would mean anyone willing to skip the browser buys the item without ever waiting. Sec-Fetch-Dest is forgeable, but forging it wins nothing except a file from the list above.
The edge case to know: an app that serves capacity-heavy dynamic content from a URL ending in .js, or routes a trailing segment like /api/stock/x.css to a protected handler, or treats .js as a format suffix the way Rails does, would skip the gate for a subresource request. There is no switch for this yet (restricting the bypass to declared asset prefixes is an open product decision). If your app does that, say so.
Streaming and WebSockets
Nothing is buffered in either direction. A streamed response starts reaching the visitor as the app produces it (a Next.js App Router shell paints at the same moment it would with no queue in front), and an upload streams through without being held in this process.
WebSocket and other connection upgrades are forwarded, and they are gated like a page, not like an asset: a socket that stays open for the length of a visit is not a subresource, and letting one through unqueued would be a way to sit inside the app without ever taking a place in line. A visitor who is still waiting gets 503 on the upgrade, with no waiting page because there is no page there; the app's own reconnect logic is left in charge of trying again. Once the handshake is through, the two sockets are joined and nothing in this process looks at the bytes again.
Upgrades on /__qm/* are refused with 501: the queue's own live updates are Server-Sent Events, which are ordinary HTTP.
Privacy Policy and Terms of Service (/privacy, /terms)
Two static pages, English and Thai in one file each (public/privacy.html, public/terms.html), served by this process ahead of any room or proxy handling, so a visitor can read them on a gated, saturated or proxied host. The waiting page footer links to both (?lang= follows the visitor's language). They are a draft written from what the server does (cookies in SPEC.md, retention in "Privacy: what is kept, and for how long" above), not legal advice. The company details are filled in; the log retention (30 days), account retention (90 days after closure), transfer safeguards (standard contractual clauses), liability cap (12 months of fees) and governing law (Thailand, Bangkok courts) are recommended defaults that counsel has to confirm, and the 30 and 90 day figures have to be made true in operation. Counsel also has to read both languages before the text is final. When a cookie, a subprocessor or a retention period changes, change the policy in the same commit; test/qm814-legal-pages.test.js pins the cookie names against server.js.
Rate limits
Every throttled route answers with X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset (seconds), and adds Retry-After on 429, so a client can pace itself instead of discovering the limit by being cut off.
The waiting page is throttled too
The page is 141 KB and is the largest thing an anonymous stranger can ask this server for. It is rendered and compressed once per room and served from memory (private, no-cache + ETag, so a visitor's reload during a long wait costs a 304 and not another page), but a client that simply refuses Accept-Encoding still takes the full body every time. Measured on one laptop at 120 connections:
| bytes pulled in 10 s | other requests on the process | |
|---|---|---|
| before | 2,212 MB | 21x slower |
| after | 29 MB | 1.3x slower |
WAITING_LIMIT_PER_MIN (default 120) is roughly two page loads a second from one client, far above any real visitor. A refused navigation gets a 941-byte page that reloads itself after Retry-After; a refused XHR gets plain text. The queue is untouched: the visitor keeps their session and their place, and the status endpoint keeps answering.
It stands down when it cannot tell visitors apart. With TRUST_PROXY unset, every visitor behind a proxy looks like one client (the proxy's own address), and a per-address limit there would take the customer's whole site down, which is far worse than the flood. So once a peer is recognised as a proxy (forwarded-address headers from the same address 10 times within a minute, or WAITING_LIMIT_PER_MIN times if that is lower, so it is recognised before its budget runs out) the guard stands down for that address only. Every other address is still throttled. /api/admin/health then reports waitingPage.enforced: false while it stands down for any address, and the console's Proxy row says an undeclared proxy is in front. Fix the proxy settings and the guard comes back for it on restart.
One forged X-Forwarded-For does not switch the guard off for every address or for the life of the process. A client that sends a steady stream of forged headers can still exempt its own address this way (with TRUST_PROXY unset the server cannot tell it from a proxy) but never anybody else's. Declaring your proxy (TRUST_PROXY + TRUST_PROXY_IPS) removes that too: the guard then never stands down, because it can charge each visitor. The list of exempt addresses is capped at 1024 and dropped when full; a real proxy is recognised again within a few requests.
So are the console and the docs
The console page is about half a megabyte, and /docs/* is rendered from markdown. /, /progress and /docs* take the same guard as the waiting page (on an inline host that includes /__qm/, /__qm/docs and /__qm/progress on the customer's own domain): WAITING_LIMIT_PER_MIN per address, the same small self-reloading refusal, the same stand-down behind an undeclared proxy. They are charged to a separate bucket, so an operator reading the guides never spends a visitor's waiting-page allowance, and the admin API is not touched. Each guide is rendered once per file version and served from memory after that.
What churn cannot do
Each budget is a map of per-address buckets. It holds at most RATE_LIMIT_MAX_KEYS (default 200,000) and evicts the least recently used address past that. Clearing the map instead would reset every throttled client's budget for anyone able to mint 200,000 keys (a Public API key holder naming a new ?ip= per vouched check, or a client rotating IPv6 addresses). A client that is being limited is, by definition, the most recent key in the map, so eviction never reaches it.
Vouched /api/check calls are charged to the visitor they vouch for (?ip=), by design: one connector speaks for thousands of visitors from a handful of addresses. Those buckets live in a map of their own, so however many visitors a key holder names, it cannot evict a direct caller's bucket.
Two keys, two blast radii
PUBLIC_API_KEY | ADMIN_KEY | |
|---|---|---|
GET /api/check with ?ip=&agent= | yes | yes |
/api/admin/* (rooms, rate, flush, eject, schedule, visitors, metrics, health) | no (401) | yes |
GET /metrics (Prometheus exposition) | no (401) | yes |
Set both. Distribute only the first.
The shop's stock calls use a third key, STOCK_API_KEY, for the same reason: PUBLIC_API_KEY is in every connector, so it must not be able to change what a room may sell. Neither of the two above opens /api/stock/:roomId, and the stock key opens nothing else but the shop's own two calls, stock and release (see Stock control).
Wrong keys are rationed. Each client address may fail admin authentication ADMIN_AUTH_FAIL_PER_MIN times a minute (default 20). Past that, every credential it presents (right or wrong, Bearer or SSE ticket) is answered 429 too_many_auth_failures with Retry-After, before it is checked, so a lockout never confirms a guess. On STORE=valkey an instance skips that check for an address for up to 1 s (AUTH_NONE_TTL_MS) after it found the address had no bucket, so a right credential from an address another instance has just locked out can pass for up to that long; wrong guesses are always charged and refused. A correct key, a valid monitor link and a valid key used on a route it is not scoped for (403) spend nothing; a request that presents no credential at all is not counted either. The public-key door (/api/check?ip=&agent=, /api/verify) shares the same allowance because it accepts ADMIN_KEY too: a wrong key there is charged, and a locked-out address's key is treated as absent (401, and connectors fail open). Behind a CDN the address is the forwarded client only when TRUST_PROXY_IPS names the CDN; otherwise every visitor shares the CDN's socket address and one guesser can lock the console out for a minute, which is another reason to set it.
No credential travels in a query string. Every admin route takes Authorization: Bearer and nothing else, and so does the Public API key on /api/check and /api/verify. ?key= is refused there with 401 {"code":"credential_in_query"} on a vouched check, counted in qm_refused_key_checks_total like any refused key, and reported by /api/verify as "Public API key sent in the URL". Every shipped connector already sends the header. A hand-written integration that still sends ?key= fails open (its pages go unqueued) until it is moved to the header; the counter and the stderr line are how you find it. The one exception is the event stream, where EventSource cannot set a header: the console mints a single-use ticket (POST /api/admin/sse-ticket, over Bearer, scoped to whatever credential asked for it) and spends it on GET /api/admin/events?ticket=…. A ticket lives 30 seconds and is destroyed on first use, so one landing in a log is worth nothing by the time anybody reads it. Operator tooling that opens the stream must mint a ticket per connection.
The console keeps a session cookie, never the key (QM-349). The console does not keep ADMIN_KEY or an operator key in localStorage: on an inline install the console is served from /__qm/ on the customer's origin, so any script that site ships could read it. Signing in sends the key once, in the body of POST /api/admin/session ({"key":"…"}, header X-QM-CSRF: 1), and the answer sets qm_console: HttpOnly, SameSite=Strict, Path=/api/admin (or /__qm/api/admin on an inline host), Secure whenever the request arrived over TLS, lasting 12 hours. Its value is a signed payload naming who signed in and a session id, never the key. DELETE /api/admin/session signs out: it clears the cookie and revokes that session server-side (the cookie was already cleared in that browser). The revocation is remembered in memory with STORE=memory, so a restart forgets it, and in Valkey with STORE=valkey, so a Valkey data loss forgets it: the instances that received the sign-out's hint still refuse the session until they restart, an instance booted after the loss does not. Revoking an operator ends their sessions on the next request; changing ADMIN_KEY ends every session the old key opened. A wrong key at sign-in spends the ADMIN_AUTH_FAIL_PER_MIN allowance exactly like a wrong Bearer, and a locked-out address is refused there too: the key rides in the body, so the right key is looked at against the address's allowance again after the body is read (a key found wrong is checked then too, before its charge), so a request held open across the lockout is refused as well, whichever key it carries and on either store, Valkey unreachable or erroring included (a wrong key then takes its token from this instance's bucket in the same step as that check). A 401 clears qm_console only when that cookie was the credential that failed: a request carrying Authorization: Bearer is judged on the Bearer alone, so a dead monitor link opened in the owner's browser does not sign the owner out (QM-460).
Revocation reaches open live streams too (QM-442). The console's live stats stream (/api/admin/events) is one long request, so checking the credential only when a request arrives was not enough. Each stream remembers what opened it: the Bearer (ADMIN_KEY, an operator key or a monitor link) or the console session cookie, carried through the SSE ticket. When a monitor link is revoked, Revoke all runs, an operator is revoked, or a console signs out, every stream opened with that credential ends at once. The admin tick checks all of them again every 2 s, which also catches expiry. The last thing the stream sends is event: revoked ({"error":"unauthorized"}), and the console shows its signed-out screen or the dead-link screen instead of reconnecting. An unspent SSE ticket whose credential was revoked is refused with 401. Removing SECRET_PREVIOUS takes a restart, and the restart closes every stream anyway.
qm_console never crosses the inline proxy (QM-427). A browser scopes a cookie by host, not port, so wherever the console and a room share a host (the console under /__qm/ on the customer's name, or both on one address) the session cookie would otherwise ride proxied requests to the app, and the app's own Set-Cookie: qm_console=… would replace the operator's session. The proxy removes qm_console from the Cookie header of every proxied request and WebSocket handshake, and drops any Set-Cookie line from the app that names it. Every other cookie passes both ways unchanged, the visitor's queue cookies included.
A change made with the cookie (any method but GET) must carry the X-QM-CSRF header, and a browser that sends Sec-Fetch-Site must say same-origin; otherwise 403 {"code":"csrf_required"}. No form can send a custom header, and a cross-origin script cannot either without a preflight this server never grants, so a page elsewhere cannot drive the console's session. Bearer callers are unchanged: a request with an Authorization header is judged on that header alone, the cookie is ignored, and no CSRF header is needed. That is also why a #monitor= link opened in an operator's browser stays read-only. A console that still has a key in localStorage from an older version moves it on first load: the key is taken out of storage, used once to sign in, and dropped.
There is a third, much smaller credential: the dashboard's Share monitor link carries a scoped viewer token in the URL fragment (#monitor=…), which no browser ever sends to a server, so it appears in no access log, no CDN log and no Referer, including the customer's own logs on an inline install. It is the read grant, not "the stats stream and nothing else". The holder can read the live stats SSE, the room list, the metrics, the security and reports panels, GET /metrics, GET /api/admin/alerts (without a blocked probe's refusal text, the webhook address or delivery errors, each of which can name an internal address; its Send test alert button is disabled), and GET /api/admin/health (which names the process id, memory and whether the proxy settings are coherent, but not the configuration warnings, the hardening list, the proxy peer addresses, whether EDGE_SECRET is enforced or PUBLIC_API_KEY is set, Valkey's maxmemory-policy (backend.maxmemoryPolicy is left out and its incident says only that the policy is not noeviction), or the text of a storage or warehouse error, which can name a path or a host: a default ADMIN_KEY, a short SECRET or a missing EDGE_SECRET is not something to tell whoever the link was forwarded to; refused qm_return URLs appear as a count per room, never the URL, for any credential). Four things it is deliberately not shown, because the link is meant to leave the team: a room's proxyOrigin (your internal address), its origin allowlists and URL rules, the per-visitor drill-down, and the audit trail, which names every operator on your team, what each of them changed, and the IP each of them did it from. All four answer 403 insufficient_role to a monitor token. A named viewer operator key sees all of them, because that is a person on your team. The share link can change nothing: any write answers 403 insufficient_role, and it can never manage operators.
And a fourth, which is the one your team should actually be using day to day: named operator keys.
Operators, roles and the audit trail
ADMIN_KEY is a shared secret with no name attached, so "who paused the room" has no answer. Mint one key per person instead, from the dashboard's Access panel or the API:
curl -sX POST https://qm.weekday100.com/api/admin/operators \
-H "Authorization: Bearer $ADMIN_KEY" \
-d '{"name":"Night ops","role":"operator"}'
# → {"operator":{"id":"535dddaa","name":"Night ops","role":"operator",...},
# "key":"qmo_535dddaa_...","shownOnce":true}
The key is returned exactly once. Only an HMAC verifier is stored, so a lost key is replaced, never recovered.
| Role | Can |
|---|---|
owner | everything ADMIN_KEY can, including minting and revoking operator keys, deleting rooms, and creating or repointing inline rooms |
operator | run the queue: rates, state, flush, eject, schedule, room settings (branding, targeting, origins, a snippet room's target URL), empty a queue |
viewer | read only: stats, metrics, security, reports, audit |
A key with insufficient role gets 403 {"code":"insufficient_role"}, not a 401, so the holder can tell "wrong key" from "not your job".
Deleting a room needs owner (or ADMIN_KEY). It is the one irreversible action here: everybody standing in the line is discarded and the room, its configuration and its schedule are gone. Emptying a queue (POST /api/admin/rooms/<id>/purge) is destructive too, but the room survives, so it stays with operator. The console hides Delete entirely for a key that may not use it, rather than letting the 403 arrive after the confirm.
Inline deployment needs owner (or ADMIN_KEY). An inline room's targetUrl names the public host this server answers for and its proxyOrigin the address that host's traffic is forwarded to, so together they decide whose traffic this server captures and where it goes. Creating an inline room, changing an inline room's targetUrl or proxyOrigin, clearing its proxyOrigin, or giving a snippet room one (which makes it inline) is refused to operator with 403 {"code":"inline_requires_owner"}, and the refusal is audited (room.create / room.update, ok: false). The refusal on an update says every other setting of the room is still the operator's to change; on a create, where there is no room yet, it says the room can still be created as a snippet room (no proxyOrigin) (QM-458). Only a change counts: a save that sends the room's current targetUrl and proxyOrigin back unchanged (the whole-body save a script or the console makes) goes through, and every other setting of an inline room stays with operator. Each accepted change is audited as room.inline, with the old and new value of each field. The console disables the inline toggle and the internal address for an operator key, and the target URL too on an inline room, and says why under the toggle.
# revoke immediately; the key stops working on the next request
curl -sX DELETE "https://qm.weekday100.com/api/admin/operators/535dddaa" \
-H "Authorization: Bearer $ADMIN_KEY"
Revoked operators are disabled, not deleted, so their past audit entries still resolve to a name. ?purge=1 is the escape hatch for one added by mistake.
Revoking an operator also closes every monitor link they shared, in the same write, so it survives a restart exactly as revoking one link does. A share link that outlived its author would be the one credential the revocation missed, and the most widely forwarded one. Links shared by other operators and by ADMIN_KEY stay open. The response carries linksRevoked, the single operator.revoke (or operator.purge) audit entry names the count (Night ops; closed 2 monitor links), and the console's confirm dialog says how many will close before you click. GET /api/admin/operators reports each operator's liveLinks.
A link is matched to its author by operator id, which is recorded when the link is minted (createdById on the link), never by name: names are free text, two operators can share one, and an operator can even be called ADMIN_KEY. Links minted before this release carry only the name and cannot be attributed, so revoking an operator leaves them open. If one of those may be in the wrong hands, revoke it from the monitor-link list, or use Revoke all; they also expire on their own after MONITOR_TOKEN_TTL_SEC (seven days by default), after which every live link is attributable.
Every state-changing admin action is appended to the audit trail (Postgres with SIDESTORE=pg) with the actor, the target, the time and the caller's address, including the server's own actions, which appear under a system actor (autotune rate changes, threshold activation flips). Field names are recorded for a room edit, not the values: the values are readable from the room, and an audit line outlives the config it describes.
Restarts are in the trail too. server.start is written when the process begins listening, and server.stop on a clean shutdown. The start line says whether the previous run stopped cleanly: the one fact that cannot be reconstructed afterwards, and the normal case on Windows, where every stop is a kill (see Stopping the server). GET /api/admin/health carries an absolute startedAt beside uptimeSec, /metrics exposes qm_process_start_time_seconds (alert on a change), and an open console raises a toast the moment the value moves under it.
curl -s "https://qm.weekday100.com/api/admin/audit?roomId=checkout&format=csv" \
-H "Authorization: Bearer $ADMIN_KEY"
There is no SSO. No SAML, no OIDC, no SCIM, no MFA. /api/admin/health reports access.sso: false so a procurement review gets a straight answer rather than a discovery.
Bot protection
Traffic asking for a place in line is scored from what this server can actually observe (a declared automation client, missing browser headers, a forged X-Forwarded-For, machine-regular arrival timing, one address holding an implausible spread of tickets), and each signal adds or subtracts points on a 0 to 100 scale.
PROTECTION_MODE=monitor(the default) scores and counts and refuses nothing. Run here first. The dashboard's Security panel shows the totals, which signals are firing and the recent decisions.PROTECTION_MODE=enforcerefuses a place in line abovePROTECTION_BLOCK_AT, with403 {"code":"blocked_by_protection"}and anX-QM-Protection: block score=NNheader.- Per room,
protection: {"mode":"enforce"}overrides the server default;nullinherits it.
Two properties to know before you enforce:
- Enforcement refuses a ticket, never entry to your site.
/api/checkstays fail-open for everyone. The cost of a false positive is a bot-looking visitor losing their place, not you losing a customer. - A shared address cannot block itself. The scoring is calibrated so that no combination of signals a corporate NAT or CGNAT pool can produce on its own reaches the block threshold; only a client that declares itself automation gets there without help. The direct consequence is that a botnet on residential addresses driving real browsers is not caught by this; fairness against that is structural (FIFO, signed passes, one pre-queue entry per identity), not classification.
Declared crawlers (Googlebot, bingbot, Pingdom, UptimeRobot, Prometheus and the rest of the list in lib/sentinel.js) are reported and not scored, unless the same User-Agent also names an HTTP library or a scripted browser. python-requests/2.31 googlebot is scored as python-requests: a crawler's name appended to a string that already said what it is buys nothing. A UA that says only Googlebot is still taken at its word; checking it against reverse DNS is not done (it would need a network lookup per new address) and is an open product decision.
The queue cookie only counts when it is real. "Presented the queue cookie" is what keeps a returning browser away from cookieless_repeat, and it means a qm_<room> token this server signed, for that room, still in date; any other value is treated as no cookie.
Put your own synthetic monitoring in PROTECTION_ALLOW_IPS so it is never scored. It matches the resolved client address, which is a forwarded one only when the connection comes from TRUST_PROXY_IPS; naming an allowlisted address in X-Forwarded-For from anywhere else changes nothing.
Places per address in the live line (queueMaxPerIp)
presenceSec (see Passes vs sessions) stops a client that never polls from stalling the room. It cannot stop a client that does poll from hoarding: sixty tickets spread down the line, a pass at each one's turn. That takes a ceiling on how many places one address may hold in the waiting line at once:
| Field | Default | Meaning |
|---|---|---|
queueMaxPerIp | 16 | Places one client address may hold in the waiting line. 1 to 100000; null for no ceiling. |
Over it, POST /api/join answers 429 {"code":"queue_identity_limit"} with Retry-After: 30 and hands back nothing: no token, no cookie. A visitor presenting a ticket they already hold is never charged; a place is freed the moment one of that address's tickets reaches the front (or is ejected). It is charged to the same address as preQueueMaxPerIp, the one thing a caller cannot mint a fresh copy of per request, and it survives a restart (it is derived from the recorded ticket owners).
The default is 16, the same as the pre-queue's. A busy live line can hold more than 16 real people behind one mobile-carrier CGNAT address at the same moment, and the ceiling refuses them, not the attacker. Raise it on a room whose audience sits behind carrier-grade NAT, or set null for no ceiling (a load test driving thousands of places from one address needs this). A room saved before the default changed, with no value stored, gets 16; one that stored null keeps no ceiling:
curl -X POST http://localhost:8080/api/v1/admin/rooms \
-H "Authorization: Bearer $ADMIN_KEY" -H 'Content-Type: application/json' \
-d '{"id":"drop","queueMaxPerIp":64}'
Turnstile challenge
Bot protection scores a request from what the server can see. For a drop where a thousand real browsers driven by scripts each hold a fair place, that is not enough, and a room can ask each new visitor to pass a Cloudflare Turnstile check before it mints their place in line. It is off everywhere until you turn it on for a room.
Set it up
- In the Cloudflare dashboard open Turnstile and Add widget. Give it a name, add the hostname(s) the waiting page is served from (the queue host, and for an inline room the customer's host: the page is served there), choose Managed mode, and create it.
- Copy the site key (public) and the secret key (private) from the widget.
Set them on the server and restart:
| Variable | Default | Meaning |
|---|---|---|
TURNSTILE_SITE_KEY | (unset) | The widget's public site key. Sent to the visitor's browser. |
TURNSTILE_SECRET_KEY | (unset) | The widget's secret. Used only to call Cloudflare's siteverify; never logged, returned by any route, shown in /api/admin/health or put in a metric. Set it as a secret (on DO App Platform, as an encrypted value). Shorter than 16 or longer than 256 characters, or with spaces, stops the server at startup. |
TURNSTILE_HOSTNAMES | (unset) | Optional comma-separated hostnames. When set, a response whose hostname (the page the widget ran on) is not listed is refused. Left unset, the hostname list on the widget in the Cloudflare dashboard is the only check. |
TURNSTILE_TIMEOUT_MS | 3000 | How long to wait for siteverify before it counts as unreachable (500 to 10000). |
Both keys must be set for the feature to exist. With one of them a warning says so, and no room can use it. A room cannot be switched to Turnstile (400 challenge_not_configured) on a server without them.
Then turn it on for a room, in the room editor (Human check (Turnstile)) or in the API:
curl -X POST http://localhost:8080/api/v1/admin/rooms \
-H "Authorization: Bearer $ADMIN_KEY" -H 'Content-Type: application/json' \
-d '{"id":"drop","challenge":{"mode":"turnstile","failOpen":true}}'
challenge is null or {mode, failOpen}. mode is "off" or "turnstile"; failOpen (default true) is what to do when Cloudflare cannot be asked, below.
What a visitor and a script see
POST /api/jointo a room that asks answers403 challenge_required(with the site key and the widget's address inchallenge) when it carries no response, and mints nothing: no ticket, no pre-queue entry, no cookie. The waiting page then draws the widget, which is invisible unless Cloudflare wants the visitor to do something, and joins again with the response in thechallengefield. A response Cloudflare rejects is403 challenge_failed; the page draws a fresh widget.- Only the first join that would mint a place is asked. A visitor who already holds a live place (a refresh, a second tab, the pre-queue's re-joins every two seconds) is not asked again, and that is decided by their queue session cookie matching the place's recorded holder, not by their token: a token copied without its cookie gets
challenge_required, so one solved check does not buy a ticket per bot. A visitor who cleared their cookies is asked again. A place that ended (ejected, the entry window lapsed) is replaced by a new one, and the new one is asked for. - A response is single use. Nothing is cached: a replay fails at Cloudflare with
timeout-or-duplicate, and a join that is refused after the check (a full pre-queue, a per-address ceiling) needs a fresh response to retry; the page takes care of that. - A room in
bypassis never asked: nobody queues there. A paused room is. - The waiting page is built to need JavaScript for such a room. A visitor without it sees a card saying so, in English, Thai, Spanish, German and French, and the page's server-side head start (a ticket minted when the page is served, so a script-less visitor is still in line) is switched off for that room, since it cannot carry a response.
- Every route that puts a visitor into a queue ends at the waiting page's join: the snippet, the WordPress and GTM connectors, the Cloudflare Worker and the inline gate all send the visitor to
/w/<room>(or serve it in place). None calls/api/joinitself, so none needs a change. A custom front end that calls/api/joindirectly has to run the widget and send the response, or its joins getchallenge_required.
When Cloudflare cannot be reached (failOpen)
siteverify unreachable, slow past TURNSTILE_TIMEOUT_MS, answering 5xx or unreadable, or refusing our own secret (invalid-input-secret) is not the visitor's fault, and the room decides:
failOpen | The join | Trade-off |
|---|---|---|
true (default) | is admitted to the queue unverified and counted as error_open | The queue stays open through a Cloudflare outage, and traffic that arrives during it is not checked. |
false | answers 503 challenge_unavailable with Retry-After, nothing minted, counted as error_closed | Nothing unchecked gets in, and the room is closed to new visitors until Cloudflare answers. |
failOpen: true trades protection for availability: whatever stops the check from answering, the room keeps admitting, unchecked. Choose it only if a closed room is the worse outcome.
It only ever covers "we could not ask". A response Cloudflare rejected is never admitted, whichever you choose. Two things are refused with 503 whatever failOpen says, so that provoking them cannot be used to skip the check:
- Cloudflare answering
429(it is rate-limiting this server): treated like the cap below. - The cap on
siteverifycalls in flight (256 per process). The trade-off is the other way round: a flood of junk responses from many addresses at once (one address is stopped first by its ownJOIN_LIMIT_PER_MIN) can fill the cap and turn real joins away with503andRetry-Afterfor as long as it lasts. The alternative, letting a full cap fail open, would let the same flood switch the check off, which is worse.
Other HTTP errors from Cloudflare (401, 403, 404: a blocked address, a revoked account) and a refused secret are still "could not ask", so failOpen decides, but they are logged as ERROR: Turnstile siteverify is refusing this server (at once, then at most every 10 seconds) and kept as challenge.lastProblem in GET /api/admin/health, because every join will hit them until someone fixes it.
A wrong or rotated TURNSTILE_SECRET_KEY looks exactly like an outage. A room that fails open then admits everyone, so watch error_open (below).
Watching it
/metrics carries qm_challenge_total{result="pass|fail|error_open|error_closed|skipped_loadtest"} (all five always present) and qm_challenge_required_total; GET /api/admin/health carries the same under challenge, with available. Alert on error_open: it is the challenge silently not protecting. skipped_loadtest counts requests that carried the LOADTEST_KEY (see Load testing through Cloudflare), which skip the check so a load test can run; it is counted apart so it can be subtracted.
Things to know
- Content-Security-Policy. The waiting page sends none, so there is nothing to widen. If you add one in front of it (a Cloudflare Transform Rule, a proxy) allow
https://challenges.cloudflare.cominscript-srcandframe-srcfor such rooms, and nothing else. - A third-party dependency, by choice. This is the one place the waiting page loads something that is not served by this process: Cloudflare's widget script, and only for a room that asks, only after the first join was answered
challenge_required. See No public-internet dependency: an airgapped install cannot use it. Cloudflare sees the visitor's address and browser signals; say so in your privacy notice. - Cookies are required. The exemption for a returning visitor is their queue session cookie. A browser that blocks cookies is asked on every join.
- Removing the keys switches the check off, for every room, without changing their settings; the rooms resume asking when the keys return. A room that is already set to Turnstile can still be edited or switched off meanwhile. It is not silent: while any room is set to Turnstile and the keys are not both set, the boot log and
GET /api/admin/healthcarry a warning naming the rooms (it lights the health badge), andchallenge.roomsUnprotectedis their count. - Scoring still runs first. A client the room's bot protection refuses (
blocked_by_protection) never costs asiteverifycall.
Testing it
Cloudflare publishes keys that behave the same from any domain, localhost included. Use them; never test with a real secret.
| Site key | Behaviour |
|---|---|
1x00000000000000000000AA | passes, visible widget |
2x00000000000000000000AB | always blocks, visible widget |
1x00000000000000000000BB | passes, invisible |
2x00000000000000000000BB | always blocks, invisible |
3x00000000000000000000FF | forces an interactive challenge |
| Secret key | Behaviour |
|---|---|
1x0000000000000000000000000000000AA | every response passes |
2x0000000000000000000000000000000AA | every response fails |
3x0000000000000000000000000000000AA | every response fails with timeout-or-duplicate |
A test site key makes the widget produce the dummy response XXXX.DUMMY.TOKEN.XXXX, which only a test secret accepts (and a production secret refuses). Their siteverify answer reports hostname localhost, so with TURNSTILE_HOSTNAMES set while testing, include it.
TURNSTILE_SITE_KEY=1x00000000000000000000AA \
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA \
ADMIN_KEY=dev-admin node server.js
The server's own tests do not call Cloudflare: QM_TEST_TURNSTILE_VERIFY_URL points siteverify at a local stub, and QM_TEST_TURNSTILE_MAX_IN_FLIGHT lowers the cap on checks in flight. Both are ignored under NODE_ENV=production.
Room firewall
A room can say who may come in: refuse a list of network addresses and countries (deny), or admit only a list (allow). It is an access rule, for a drop that is open to one market, or a source of abuse you have already identified. It is not bot detection (see Bot protection) and it is not a substitute for a Cloudflare WAF rule in front of the whole site: it decides who gets a place in this room and past this room's door, nothing more.
Off everywhere until you set it on a room. In the room editor (Access rules (firewall)) or the API:
curl -X POST http://localhost:8080/api/v1/admin/rooms \
-H "Authorization: Bearer $ADMIN_KEY" -H 'Content-Type: application/json' \
-d '{"id":"drop","firewall":{"mode":"allow","countries":["TH"],
"ips":["203.0.113.0/24"],"message":{"en":"Sold in Thailand only.","th":"จำหน่ายเฉพาะในประเทศไทย"}}}'
firewall is null (no rules) or {mode, ips, countries, message}:
| Field | Meaning |
|---|---|
mode | "deny": the listed addresses and countries are refused, everyone else is let in. "allow": only the listed are let in. |
ips | CIDR ranges, IPv4 or IPv6 (203.0.113.0/24, 2001:db8::/32); a bare address is that one host. At most 200. |
countries | ISO 3166-1 alpha-2 codes (TH, CN), and T1 for Tor. At most 50. |
message | Optional words for a refused visitor: a string (English) or {en, th}, each one line of at most 300 characters, shown as plain text. |
At least one range or country must be listed (an empty allow list would admit nobody; to close a room use its state). Ranges are normalised as they are saved: host bits are cleared (10.0.0.5/24 becomes 10.0.0.0/24), IPv6 is written in its shortest form, ::ffff:a.b.c.d is the IPv4 address, and duplicates and ranges inside a wider listed one are dropped. 0.0.0.0/0 and ::/0 are refused (they match everyone). A bad entry is a 400 naming it: invalid_firewall, invalid_firewall_mode, invalid_firewall_ip, invalid_firewall_country, invalid_firewall_message, firewall_empty, firewall_too_many_ips, firewall_too_many_countries.
One person usually has two addresses. A browser on a dual-stack network reaches the server over IPv6 when it can, and its IPv4 address (when it uses one) is often not the one a command-line check on the same machine reports. To refuse or admit one person or office, list their IPv4 address and their IPv6 prefix, usually a /64 (2001:db8:da:5f17::/64), not the single IPv6 host: the last 64 bits change as the device rotates its privacy address. Find both from the browser itself, not from curl on the same machine.
Which address, which country
- The address is the real one: the address that connected through Cloudflare (
CF-Connecting-IPonceEDGE_SECRETis set; otherwise the socket, or the forwarded address of a declared proxy: see Behind a CDN or load balancer). A request that carries theLOADTEST_KEYis judged on its real address, never on the synthetic one that keys its throttles, so a load test neither slips past a rule nor trips one by the addresses it invented. - An IPv6 range means what you wrote. It is matched exactly:
2001:db8:1::/48is that /48, and a single/128is one host.IPV6_PREFIX_BITS(which groups addresses for the rate limits) has no part in it. - The country is Cloudflare's
CF-IPCountry, and it is believed only on a request that passed theEDGE_SECRETcheck. WithoutEDGE_SECRETthe header is anyone's to type, so no country is trusted and a country rule cannot work: the server refuses to add one (400 firewall_countries_need_edge), and a room that has some from before (a restart without the secret) is named in a health warning and infirewall.roomsCountryUnverifiable. Address rules need no edge secret. - Unknown is in no list. A visitor whose country is not known (no header, Cloudflare's
XX, anything that is not a country code) matches no country rule. In deny mode that means they are let in; in allow mode they are turned away, unless an address rule lets them in.XXcannot be listed, and neither canUK(useGB).T1(Tor) can: list it in deny mode to refuse Tor exits. - A listed address beats a country in allow mode: an office range you list gets in whatever country it geolocates to.
Where it is enforced
Before anything is minted and at the door, so a place held from before a rule changed does not get past it:
| Path | Refused caller gets |
|---|---|
POST /api/join (including the pre-queue) | 403 firewall_blocked, no ticket, no pre-queue entry, no cookie |
GET /w/<room> (the waiting page; the inline gate) | for a browser navigation, a plain page that says the room is not available (in the visitor's language, with your message), status 403; for a script, the 403 JSON. No ticket, no cookie. |
GET /api/check (the door) | 200 {action:"queue", reason:"firewall_blocked", blocked:true, waitingRoomUrl}: the same shape every connector already acts on, which sends the visitor to the waiting page, where they read why. It admits nothing and issues no door key. |
| the inline gate, a WebSocket upgrade | 403: the request is not forwarded to your site. |
GET /api/status, GET /api/events | 403 firewall_blocked: the waiting page shows its "not available" card and stops asking. |
POST /api/redeem (a priority code) | 403 firewall_blocked: the code is not spent and the place does not move, so a place held from before the rule cannot be pushed to the front. |
POST /api/notify (an e-mail address for a turn notice) | 403 firewall_blocked: no address is filed, none already on file is changed, no mail is sent, so a refused caller cannot spend your sender quota on a link it cannot open. A withdrawal (an empty email) is let through: refusing it would keep someone's address on file after they asked for it to go. |
The door answers 200 and not 403 on purpose: the snippet, the Node middleware, the Worker and the WordPress plugin read a 403 from /api/check as "the key is wrong" and fail open, which would wave a refused visitor through to your site. A queue verdict is what they all send to the waiting page.
Streams already open when you save a rule are re-judged: those the new rule refuses get a final event: firewall and are closed, and the page shows its card.
Things to know:
- It refuses the visitor your site too, not only the queue. A refused visitor is not let through the door either (
/api/checknever passes them, the inline gate never forwards them). The exception is a page your room's URL targeting does not queue: that page is not the room's, and a visitor the firewall refuses reads it like anyone else. - It is not content protection for static files on an inline host. The inline gate lets subresources through first (What skips the gate: scripts, styles, images, fonts, and so on), before any queue or firewall decision, so a refused visitor can still fetch those files from your origin. What is refused is the page and its data, not the assets. If a file must not reach a country, block it at Cloudflare.
- Established WebSockets are not re-judged. A WebSocket is judged when it is upgraded; one already open when a rule changes stays open until it closes. (Open event streams of the waiting page are ended.)
- A room in
bypassstill refuses. Bypass lifts the queue, not the rule about who may come in. - A refused visitor's existing place stays in the line until it lapses (the firewall does not eject), and cannot be used. This is known behaviour: such a place that reaches the front is admitted into a door nobody can pass through, and holds a capacity slot until its entry window lapses. Eject it from the console, or set
presenceSecso a place nobody is watching is dropped. In a room with stock the same place also takes a unit when its pass is minted (it comes back when the entry window lapses unclaimed, or at once on an eject), and if its owner filed an address for e-mail the turn e-mail goes to it, with a link that meets the same refusal. - Rolling back, or a deploy still in flight. A build from before Notion 743 does not know the
firewallfield (nornotifyNear, Notion 746): a room saved on it, from the console or the API, is written without them, so the rule is gone and the room is open to everyone. Do not save rooms while old and new builds run together, and after a rollback read each room's firewall again. - Connectors vouching for a visitor (
/api/check?ip=&agent=, which needs the Public API key) are judged on the address they vouch for, and on the country they vouch for as&country=TH. A country rule only works for a connector that sends the country, because the queue server never sees the visitor's own request there. Without&country=the country is unknown: a deny room lets the visitor in, an allow room turns them away at the door (after the waiting page, which sees the visitor's own request, queued them). - The Cloudflare Worker (1.2.2) sends
request.cf.country, which Cloudflare writes and a visitor cannot. - The Node (1.3.20) and WordPress (1.2.4) connectors send it only if you switch it on, and only behind Cloudflare:
countryHeader: 'cf-ipcountry'orvouchCountryfor Node;define( 'QM_COUNTRY_HEADER', 'CF-IPCountry' );or theqm_client_countryfilter for WordPress. A header at an origin a visitor can reach directly is theirs to write, and they would choose their country. - The browser snippet and the GTM tag do not vouch (the server sees the visitor's own request), so they need nothing.
- The server notices a connector that does not send it: every vouched check without
&country=for a room that has country rules is counted inqm_firewall_vouched_without_country_total, andGET /api/admin/healthnames those rooms infirewall.vouchedWithoutCountryand in a warning. - An address rule needs the visitor's real address from the connector: a Node connector without
trustProxyorvouchIpbehind a proxy (or a WordPress plugin withoutQM_TRUSTED_PROXY) is judged on its own egress address, so an allow room, which does not list it, turns every visitor away. - Console monitor links (shared dashboards) show the room's mode but not its lists or message.
- Propagation. The rules are kept in memory off the store's room-change event, like Bot protection's per-room mode: a save is effective on the instance that took it at once, and on the others as that event reaches them over the store's pub/sub (a second or so). A lost event is repaired by the periodic resync,
RESYNC_MS(default 5 s), so that is the worst case; withRESYNC_MS=0there is no resync, and an instance that missed the event keeps the old rules until it restarts. - Boot, and a store outage. Until the boot fill of the room copies has finished, a request reads the room's rules from the store. If the store is down then, the firewall cannot be consulted and the request goes on to the room's own
onBackendDownhandling, as any request would: withopenit is not firewalled during that outage.
Watching it
/metrics carries qm_firewall_blocked_total{reason="ip|country|allowlist"} (all three always present) and qm_firewall_blocked_by_room_total{room,reason} for the first 50 rooms that refused anyone since boot. ip and country are deny-mode refusals; allowlist is an allow-mode room turning someone away (including every unknown country). GET /api/admin/health carries the same under firewall (rooms, blockedTotal, the three reasons, roomsCountryUnverifiable, vouchedWithoutCountry). Counts are per instance and per refused request: one visitor who keeps retrying counts every time. Every change to a room's rules is its own audit entry, room.firewall, with the old and the new rules in brief (counts and countries, not the ranges); saving rules that did not change writes none.
Priority codes
A priority code lets a person you chose go ahead of the line: a guest, a member, a press pass. Codes belong to one room; a code of another room is no code here. Make them in the console (a room's Priority codes panel) or with POST /api/admin/rooms/:id/codes (see SPEC.md).
| Effect | What the holder gets |
|---|---|
skip | Admitted at the next tick, without waiting for the rate's pacing, into a free slot only: maxConcurrent and the door are never exceeded, and a paused or not-yet-open room admits nobody. |
jump | Moved in front of every ticket without a code and admitted at the normal pace. Among code holders, skip first, then jump, each group in ticket-number order. |
Everybody without a code keeps FIFO order among themselves; they are pushed back by at most the number of people who redeemed.
- One use, unless you say otherwise.
usesis 1 to 100000 or"unlimited"(a printed card for a crowd). An optionalexpiresAtends it. - The code is shown once, and can be copied again. The answer to the create call (and the console dialog) carries the code and a ready link
/w/<room>?code=…. The server keeps an HMAC of it under a key derived fromSECRET(what redeeming checks) and, for a code made since Notion 840, the code itself encrypted (AES-256-GCM under a different key derived fromSECRET, bound to the room and the code). The code list never returns the code or the ciphertext; each row's Copy link and Copy code buttons askPOST /api/admin/rooms/<room>/codes/<n>/reveal, which answers with the code and is audited ascode.reveal. A code made before Notion 840 has nothing to decrypt: its buttons are disabled ("Made before codes could be copied; make a new one"); revoked, expired and used-up codes have no copy buttons. IfSECRETchanged and the old one is gone, the reveal fails with500 code_decrypt_failedinstead of answering. A dump of the database or journal holds no code, but anyone holding both the dump andSECRETcan decrypt the codes made since 840. WhileSECRET_PREVIOUSis set (a rotation), codes made under either still work; after the rotation ends, codes made under the retired secret stop working, so re-issue long-lived codes after rotating. - Delete. A row's Delete button (
POST …/codes/<n>/delete, audited ascode.delete) removes the code entirely: it leaves the list and can no longer be redeemed. It cannot be undone. People who already redeemed it keep their place. Revoke, by contrast, keeps the row listed. - Redeeming. The visitor opens the link (the page redeems it by itself and removes
codefrom the address bar) or types it into Have a priority code? on the waiting page. They need a waiting place; one code per place. Revoking a code stops further redemptions; people who already redeemed keep it. - Hiding the button. A room's
showCodeButton(the console's Show the priority-code button box; defaulttrue) set tofalseremoves Have a priority code? from that room's waiting page. A?code=link is still redeemed and its confirmation still shows. Any non-boolean is400 invalid_show_code_button. - Guessing. An unknown, expired, used-up or revoked code answers the same
code_invalid. A code is 59 bits, so guessing is not feasible; the limits (REDEEM_LIMIT_PER_MIN,REDEEM_FAIL_LIMIT) keep it visible.qm_priority_redeem_total{result}counts every outcome. - Roles and audit. Owner and operator create and revoke; a viewer lists.
code.create,code.revoke,code.revealandcode.deleteare audited. Redemptions are audited for a code's first use, its last and every 25th, so a drop does not push the operators' own actions out of the audit ring; the exact count is on the code. - Several instances. A use is taken atomically in Valkey: two visitors redeeming the last use at once, on two instances, give exactly one winner. Codes, uses left and who holds one are journaled and survive a rebuild of Valkey from Postgres.
Stock control
A room guarding a fixed amount of something (200 pairs, 500 seats) can carry a stock: how many visitors it may still admit. No stock set means no limit, and nothing about the room changes. Set it in the console (a room's Stock panel: Set to, Add, Take, Remove limit), with POST /api/admin/rooms/:id/stock {set} or {delta}, or let the shop do it (INTEGRATION.md, Stock control). The panel's Hold button sets the stock to 0 in one click (it asks first); release the line with Add, Set to or Remove limit. The room can also ask the shop whether it is sold out (Stock check, below) instead of waiting to be told.
- Admission takes a unit a pass. In the same step as the promotion, so two instances cannot take the last unit twice and the stock never goes below 0. The clock, a flush (
force: trueoverrides the concurrency ceiling, not the stock: add stock to let more through; a flush it cut short answerslimitedBy: "stock") and a skip code all stop at it. A pass for a visitor who is not there (a ghost) takes one too: if they come back they hold a valid pass.bypassadmits nobody and takes none. Setting the stock below the passes already minted is just the new remaining; those passes stand and are not given back. - At 0 the line is held, not ended. Nobody is admitted, no place is lost, new visitors still join at the back, and the waiting page says everything has been taken for now (in every language it speaks), with no wait estimate. When stock comes back, admission resumes from the head, in order, at the room's rate. The card shows
sold out · line held;soldOutis in the room's stats andqm_room_sold_out{room}is 1. A held line is not a stalled outflow: it is not paged asoutflow_stalledand the console does not flag it as stalled. - Units come back on their own, in two cases. A pass that lapses unclaimed (its holder never used it at the door before the grant ran out, a ghost's included) gives its unit back, and the tick that finds it admits the next visitor in line. An eject gives back the unit of any pass, claimed or not. A pass that was claimed and then ends by itself (its grant or its session running out) does not: the visitor used it, and the shop returns the unit if it comes back (
delta+1, with a key), or sendssetwhen its own count is the truth. Only a pass minted while the room has a stock holds a unit, and asetis the truth: the units out before it are not given back after it, so the stock never goes above what you or the shop set plus what was added since. (A negative delta that stopped at 0 is not remembered: send asetrather than correcting a count with a delta.) A drop that sells out with units still unsold frees them by itself as the unclaimed passes lapse; add stock to go faster. - The shop.
POST /api/stock/:roomIdwithSTOCK_API_KEY(see Two keys; unset, the shop API is off). Adeltaneeds a key (the order id): a retry is answered, not counted twice, and the room remembers the last 5000 keys. The answer waits for the journal, so a200is never ahead of the disk. Calls are limited per address (STOCK_LIMIT_PER_MIN) and counted inqm_stock_adjust_total{source,result}. - Release a visitor's slot at payment.
POST /api/release {roomId, token}(also/api/v1/release), called by the shop when the buyer reaches the payment page, with the sameSTOCK_API_KEY,404 stock_api_disabledwhen it is unset, the same failed-key lockout. The token is the visitor's own queue token; the room ends that visitor's door session and any pass they have not used, at once, so the slot is free and the next person in line goes on the next tick instead of aftersessionTtlSec(300 s idle on weekday-100). Only a visitor who is inside is released: a ticket still waiting is answeredreleased:false, reason:"not_inside"and never touched, so a shop cannot knock the line out. Idempotent (200 released:falsethe second time). The visitor is not sent back into the line (coming back from payment they queue again as a new visitor) and the stock is not touched (the unit stays spent: if the payment fails the shop returns it itself with adelta). A body that is not JSON, not an object or over 4 KB is400 invalid_json,400 invalid_bodyor413 payload_too_large, whichqm_release_totaldoes not count. The change is journaled as an ordinaryejectwithout a stock figure, so a rebuild keeps it. Effect on the entry rate: every release is capacity that appears now, so while shoppers pay and the shop calls, the room admits faster than idle expiry alone would let it (still at mostratePerMinute): watchqm_room_occupancyagainstmaxConcurrentand the shop's own load when you turn the integration on. Counted inqm_release_total{result}(released,already,invalid,unauthorized,rate_limited,disabled; per instance). - Audit. Every operator change is
stock.setorstock.adjustwith what it did and what the stock was. The shop's calls are not written one by one (the audit log is a bounded ring and a shop calls once per order); the two moments that matter are:stock.sold_outwhen a call took the room to 0 andstock.restockwhen one gave it stock again or removed the limit of a held room (Remove limit on a stock of 0). Admissions that sell the last unit out are visible asqm_room_sold_out. A release is written one by one,release.shop(actorshop, the ticket number, never the token), because it is an action on a visitor: on a very busy drop that is one entry per paying visitor in the same bounded ring. - Several instances, and a rebuild. The counter is a field of the room in Valkey and is journaled (
stock, andskon everypass), so a Valkey rebuild from Postgres restores it with the keys of the calls it remembers. Roll a deploy that adds stock to every instance before you set one: an older build refuses the newer snapshot format, and an older script would mint passes without taking units. Rolling back to a build from before stock control is the same hazard the other way: while a room holds stock, an instance on the old scripts mints passes and takes no unit (it does not read the field, which stays in Valkey unchanged), so the room oversells for as long as one old instance answers, and a rebuild on an old build does not restore the count. Before a rollback, note each room's stock (GET /api/admin/rooms/:id/stock) and treat the limit as off for the time the old build runs (close the room to the shop, or hold the door yourself); when you roll forward again, set the count from the shop's own figure, not from the number that was left in Valkey. - Metrics.
qm_room_stock_remaining{room}(-1 with no stock),qm_room_sold_out{room}andqm_stock_adjust_total{source,result}. Alert onqm_room_sold_out == 1while the shop still shows units, which is a stock that was set wrong or units that were never returned. A share (monitor) link is not shown the count (the Stock panel and the stock route are hidden from it, and the stats it reads dropstock), but a monitor token may scrape/metrics, which carriesqm_room_stock_remaining: do not hand one to someone who must not know it. The stock check addsqm_stock_check_total{room,result}andqm_stock_check_enabled{room}(see Stock check below).
Stock check
Instead of (or as well as) the shop pushing its stock, the room can ask the shop whether it is sold out. A room has a stockCheck {enabled, url, round, roundParam} (null by default; a writable room field, set in the room form's Stock check section). The fleet leader asks the shop every STOCK_CHECK_EVERY_MS (3 s), holds the line when the shop says it is sold out and releases it when the shop has stock again. The check only knows sold out or available, never how many. POST /api/stock still works as before; with the check on the shop does not need to push anything, unless it wants the numbers in the console.
- The shop's side (the contract the shop team gets is in INTEGRATION.md, Stock check URL). QM sends
GET <url>?<roundParam>=<round>(roundParamdefaults toround; a query already in the URL is kept and the parameter is added to it), withAccept: application/jsonand the User-Agentqueue-manager-stockcheck/1.0. Theurlishttpsonly, has no credentials, is at most 2048 characters and does not already carryroundParam. A private address is refused (unlessPROXY_ALLOW_PRIVATE=1, as for the target probe; that lifts the address guard only,httpstays refused). Redirects are not followed. The whole request has a 3 s deadline and the body is read up to 4096 bytes. An accepted answer is HTTP200with a JSON object that holds{"stock": <whole number>}or{"soldOut": <boolean>}. Sold out issoldOut: true, orstockat 0 or below (a negative whole number counts as sold out); with both fields, either one saying sold out is enough. Astockthat is a string or a fraction, with nosoldOutbeside it, is a failed check. - A failed check is any other answer, and carries one reason:
timeout(the 3 s deadline, or a socket gone quiet),blocked(not https, or a private address),unreachable(DNS, connection refused or reset, TLS),status(anything but200, a redirect included),not_json(not a JSON object),too_large(over 4096 bytes) andno_field(no usablestockorsoldOut). A failed check never holds or releases anything: the line keeps the state it had. - QM acts only when the answer changes. The leader remembers the last accepted answer per room, in its memory only:
- available to sold out: the room's stock is set to 0 through the same path as the Hold button (audit
stock.sold_out), unless it is already 0; - sold out to available: the limit is removed (stock set to
null, auditstock.restock:limit removed (stock-check): admissions resume), but only when the stock is still 0. A stock somebody has set since, an operator's Add or Set to or the shop'sPOST /api/stock, is never overwritten while the shop still has stock. A release is damped: it needs 2 available answers in a row and at least 30 s since the hold, so a shop that flips between sold out and available cannot make the line flap (a hold acts on the first sold-out answer). The 30 s are counted from the hold, not renewed by the sold-out answers that follow it. For a handful of rooms a release comes about 2 checks (6 s) after the shop restocks, and never earlier than 30 s after the hold; a sold-out answer in between starts the count again. With many rooms every check is later, see the cap below. The two numbers are fixed (no setting); - the first answer after the leader started, after the check was turned on, or after its
url,roundorroundParamchanged only ever holds (when the shop is sold out and the stock is not already 0). It never releases, because QM cannot know who held the line. Nothing is written while the answer stays the same, so a steady sold-out shop puts no event in the journal every 3 s. - What follows from that, plainly.
- A manual Hold made while the shop says it has stock is not undone by the check (it only releases after a change from sold out to available). A hold made after the check has already seen the shop sold out cannot be told from the check's own, and the next change to available releases it.
- A manual Add, Set to or Remove limit is not taken back unless the shop's answer changes.
- A leader failover resets the memory. If the shop restocks while no leader is polling (a failover, or a restart of the only instance), the new leader's first answer is "available" and it never releases: the line stays held until the shop's answer changes again or an operator releases it (Add, Set to or Remove limit). Every deploy restarts the instances, so a deploy made while a drop is sold out can leave the hold in place this way. A held room does not page
outflow_stalled(a sold-out room is held on purpose), so nothing will tell you. - The check runs on the leader only, on its own timer, one request in flight per room. At most 16 checks are started per tick, in turn (a room that did not fit is first in line on the next tick, so none starves). So with N rooms that have the check on, each room is checked about every
ceil(N / 16)×STOCK_CHECK_EVERY_MS: up to 16 rooms every 3 s, 200 rooms about every 39 s. A hold or a release can be late by that much. This is deliberate: the cost of the check is bounded (16 outbound requests per tick at most), so it never loads QM, and a slow or hanging shop (each request has a 3 s deadline) can hold up only its own turn. The "failing for how long" timer lives in the leader's memory too and starts again from zero on a leader change or a restart. - Off means off. With
enabled: false(or the room deleted) there are no requests and no stock writes, and an answer already on its way when it was turned off is dropped. Changing theurl, theroundor theroundParamstarts fresh, as if it had just been turned on (an answer for the old settings is dropped too). Changing theroundis how an operator moves to the next drop: each round is its own count at the shop. - Moving to the next drop leaves a hold in place. If the check had held the line and the operator then changes the
round(or theurl), or switches the check off and on, the line stays held at 0 until the operator presses Remove limit (or the new round goes sold out and then available). The fresh start never releases, and nothing pages for it, because a held room does not raiseoutflow_stalled. When you move to the next round, release the hold by hand (Remove limit) if the new drop is on sale. - When the check keeps failing. After
STOCK_CHECK_FAIL_SEC(120 s;0turns it off) of failures in a row the alertstock_check_failing(warning, afterALERT_HOLD_SECmore: about 120 + 30 s, up to about 165 s counting the 15 s evaluation) names the room, and it resolves on the next accepted answer. The message has no URL. Meanwhile the line keeps its last state (held stays held, released stays released): a shop outage does not open or close the door by itself. - The console. The room form's Stock check section has the toggle, Stock check URL, Round and, under Advanced: round parameter name, the parameter (default
round), with the server's own messages. A room with the check on says so under its Stock panel. Test the saved settings callsPOST /api/admin/rooms/:id/stock-check: one real request with the saved settings (the button waits for a save when the form has unsaved changes), so the operator sees the shop's real answer before turning the check on. It is read-only: it never touches the stock or the poller's memory, and it runs on any instance. The answer is{ok, state, stock, soldOut, ms}(stateissold_outoravailable;stockisnullwhen the shop sent onlysoldOut) or{ok:false, reason}with a reason from the list above. Other answers:400 stock_check_not_configured(no saved url and round),404 room_not_found, and429 stock_check_busywithRetry-After: 1when a test for that room is running or ran less than a second ago (one test per room at a time, at most one a second). Owner and operator may call it; a viewer and a monitor (share) link get403. - The URL may be a secret. It can carry a token in its query (
https://shop.example.com/api/stock?token=...). Every operator who can open the room form sees it; a monitor (share) link does not (the room readsstockCheck: nullfor it and the section is hidden). QM never writes it to a log, an audit entry, an alert or a metric, and a failure reason is one of the fixed words above, never the shop's text. - Metrics.
qm_stock_check_total{room,result}counts the answers the leader got, byresultofsold_out,availableorfailed(per instance, since start: only the leader's count moves, so a non-leader reads 0) andqm_stock_check_enabled{room}is 1 while the check is on. Watchstock_check_failing, orfailedrising on the leader; a flatqm_stock_check_totalwith the check enabled means no leader is polling.
Waiting cap and closing a room
Two controls for a crowd bigger than the line should hold. A cap (maxWaiting) stops new arrivals once the line is that long; closing a room ends the line (sold out, thank you). Both refuse only people with no place; nobody who already holds a place in line loses it to the cap, and closing ejects nobody. The point is that a refused visitor costs almost nothing: they are sent to a cached static page, and through the Cloudflare Worker they need not reach this server at all.
The settings, in a room's editor (Edit) or POST /api/admin/rooms:
| Field | Meaning | Limits |
|---|---|---|
maxWaiting | The most visitors the line may hold. null (empty box) is no limit, exactly as before. | A whole number from 1 to 100000000, else 400 invalid_max_waiting. |
fullUrl | Where a refused visitor goes when the line is full. null is the default page below. | An https:// URL with no credentials, at most 2048 characters, else 400 invalid_entry_url. |
closedUrl | Where visitors go when the room is closed. null is the default page. | The same rule. |
Lowering maxWaiting below the current line ejects nobody; it only stops new arrivals. Closing is not a field: it is the console's Close room button, or POST /api/admin/rooms/:id/close and .../reopen (below), so a room write cannot flip it. The waiting count is the room's own (tickets not yet promoted); people already admitted do not count, so the cap is about the line, not the door.
The three states (what a visitor arriving now meets; qm_room_entry_state):
open: no cap, or the line is shorter than the cap, and the room is not closed.full:maxWaitingis set and the line has reached it (computed, never stored), or an operator marked the room full (stored and journaled; below).closed: an operator closed the room. Stored and journaled.
| Visitor | open | full | closed |
|---|---|---|---|
| New (no place) | joins at the back | sent to the full page; no ticket is minted | sent to the closed page |
| Waiting | as today | as today, even refreshing at the cap | told to leave within one poll (below) |
| Pre-queued (a scheduled drop) | as today | as today: the cap does not apply to the pre-queue, and the drawn order is kept whole | told to leave; nobody enrols while closed |
| Holding a pass | as today | as today | as today: passes stay valid and the door still lets them in |
| Bypass room | admits everybody | the cap never applies (nobody waits); a room an operator marked full refuses newcomers | newcomers are refused; a visitor holding a pass for the room still passes |
Priority and skip codes do not bypass the cap or the close: a code only reorders a line a visitor is already in. The cap is exact at the store: two joins at the same moment cannot both take the last place, and the line never goes over maxWaiting. A visitor who lost their session cookie but is still recognised (same fingerprint and address) keeps their place at the cap; one who presents a ticket it cannot prove is treated as a new arrival and refused. Precedence for a request: the room firewall's verdict, then closed, then full, then normal.
The answer connectors follow. GET /api/v1/check answers a refused visitor, and a waiting one in a closed room, with the same 200 shape every connector already acts on (it is the shape the firewall door uses):
{ "action": "queue", "reason": "room_full" | "room_closed", "waitingRoomUrl": "<absolute URL of the page>" }
waitingRoomUrl is the one field connectors follow, so the browser snippet, the Node middleware, the WordPress plugin, the GTM template and the Worker need no change: they send the visitor to the page as they send them to the firewall's page. A qm_return parameter that a connector appends is ignored by a static page. The other ways in end up on the page too: GET /w/<room> for a visitor with no ticket is a 302 to it, decided from the one shared entry read with no script call, and POST /api/join answers 200 {"refused":"full"|"closed","url":…} that the waiting page acts on (INTEGRATION.md, A full or closed room).
Closing a room, and reopening it
- Close. The room card's Close room button asks first, and the dialog says how many are waiting (and pre-queued) and what happens: everyone waiting is sent to the closed page, new visitors are refused, people holding a pass can finish.
POST /api/admin/rooms/:id/closeanswers{roomId, closed, changed, waiting, cleared}; it is idempotent (changed: falsethe second time, and only a change is audited). Owner and operator may close; A viewer cannot close (403), nor can a share (monitor) link. - Waiters leave within one poll. A status poll or SSE frame for a waiting or pre-queued ticket now carries
closed: trueand the page's absolute URL, and the waiting page doeslocation.replaceto it, so everybody is gone in a few seconds. Passes are answered as before. Nothing is ejected and the leader's tick stops promoting while the room is closed. - Reopen starts a fresh line. The people who were sent to the closed page do not get their place back: Reopen clears the whole waiting and pre-queue line (the response's
clearedsays how many) and nobody is promoted from it. Pass holders are untouched. A visitor who comes back with an old ticket is told it is gone and joins like anyone else. That cannot be undone for the people sent away, which is why the dialog counts them, and Reopen asks again when anyone is still in the line. Audit:room.closeandroom.reopen(with the count). - While closed the old count stays. Nothing removes the tickets of people who left, so
qm_room_waitingkeeps its last value until Reopen; a closed room with waiting above 0 is normal and is not a line.
Marking a room full, and unmarking it
An empty room is never full by itself (maxWaiting is at least 1), so an operator who wants the door shut without closing the room, for example to hold a sale back while the stock is checked, marks it full.
- Mark full. The room card's Mark full button asks first. From then on the room's entry state is
fullwhatever the line holds: new visitors are sent to the full page (fullUrl, else the default/full/<room>) and no ticket is minted, exactly as at the cap. People already waiting keep their place and are admitted as usual; pass holders and pre-queued visitors are untouched. Unlike the cap, it applies before a scheduled room opens too: a newcomer is not enrolled in the pre-queue (an entry already enrolled is kept). It also turns newcomers away in a bypass room. Closed wins: a closed room that is also marked full isclosed, and the mark is still there after Reopen. The card's badge reads Full (forced), the Entry panel says an operator marked it, andqm_room_entry_statesaysfull. - Unmark full is the way back and needs no confirmation. The next visitor joins as usual.
- API.
POST /api/admin/rooms/:id/mark-fulland.../unmark-full(two verbs, like/closeand/reopen; no body) answer{roomId, fullForced, changed, waiting}. Both are idempotent (changed: falsewhen nothing moves, and only a change is audited). Owner and operator may; a viewer and a share (monitor) link cannot (403). The room list row carriesfullForced: trueonly while the mark is on; a room write cannot set or clear it. Audit:room.mark_fullandroom.unmark_full(with the waiting count). The entry route's answer is the existingfullone, so connectors need no change.
The default pages and the templates
With no fullUrl / closedUrl, the server serves a default at /full/<room> and /closed/<room>: plain static HTML, Thai first and English second, no script, no timer, no background image, identical bytes for every visitor of a room, and Cache-Control: public, max-age=60. The only per-room parts are the logo centred at the top (branding.logoUrl, the one image the page may load) and, on the full page, a Back to home button (branding.homeUrl), plus on both pages a My order button (branding.myOrderUrl, same tab); a room with none of them gets the file's own bytes, and a store error serves the file too. The layout fits phones from 320 px wide: the card shrinks under 360 px and in a landscape phone, every button is at least 44 px high, and the page keeps clear of a notch (viewport-fit=cover and env(safe-area-inset-*)); desktop is unchanged. Cloudflare does not cache HTML or extension-less paths by default, so add a Cache Rule on the queue host for /full/* and /closed/* (see the rate-limit section); with it a refresh is a cache hit and the origin sees about one fetch per colo a minute. An unknown room is 404. The full page has no automatic retry (a synchronised retry would release a crowd in one second the moment the line dips) and tells a visitor already in line how to get back to it. To use your own page set fullUrl / closedUrl; public/examples/room-full.html and room-closed.html are plain templates to start from.
The default page's address is built from PUBLIC_URL when it is set, else from the host of the request. On a proxied (inline) customer hostname only /__qm/ is routed to the queue, so without PUBLIC_URL the fallback is <customer host>/__qm/full/<room> and /__qm/closed/<room>; set PUBLIC_URL for inline and proxied hosts, so a refused visitor is sent to the queue host's own cached page.
The waiting marker (qm_w_<room>)
A visitor in line sits on the queue host, and their place is bound to cookies there. If they press Back to the customer's page, the Worker sees no pass cookie, so a visitor already in line would look like a new arrival and be sent to the full page. To tell them apart, when CLAIM_COOKIE_DOMAIN is set the server sets qm_w_<room>=1 (Domain=<CLAIM_COOKIE_DOMAIN>; Path=/; HttpOnly; Secure; SameSite=Lax, session length) whenever it mints or re-attaches a waiting ticket. It identifies nobody and holds no place.
- Only with
CLAIM_COOKIE_DOMAIN, a bare parent of both the queue host and the protected site (for exampleweekday100.com). Without it the marker cannot reach the customer's domain, and nothing is set (nor on an inline host). - It is a parent-domain cookie, outside the per-room cookie cap that bounds the queue host's own cookies: about 75 B per room a browser waited in, bounded by the deployment's room count, gone at the end of the session.
- It is cleared when a status poll answers passed, closed or expired, but it cannot be expired on an SSE stream (the headers are long sent). So a stale marker can outlive the line, which is harmless: it only sends the Worker to the check call, and in a
closedroom the Worker ignores it.
The Worker shortcut, and how fresh the edge is
This section applies only if you run the Cloudflare Worker in front of the protected site. A shop that uses a server-side connector (WordPress, Next.js, Node) has no Worker: its server asks /api/v1/check and follows the queue answer to the full or closed page, and every refresh costs one check call to this server (the entry state it reads is cached 1 s per room per instance). Nothing in this release requires the Worker.
Workers plan limits. The Workers Free plan allows 100,000 requests a day (the figure the dashboard shows under Workers & Pages, Usage; the paid plan allows far more: check Cloudflare's current pricing). Every request that matches the Worker's route counts, a refresh flood included, so a crowd of 150,000 people pressing Refresh can use a Free day's allowance in minutes. What happens at the limit depends on the route's failure mode (let the request through to the origin, or answer with an error): check it before relying on the Worker for a big sale. A Worker that is not in front of the site shows 0 requests under Usage even while the zone is busy.
The Cloudflare Worker (connectors/cloudflare/README.md) reads GET /api/v1/entry?roomId= (public, cached 5 s) and, after its normal scope test (pages the room does not protect are never touched), redirects a visitor who has no pass cookie, no qm_token straight to the page with a 302 (once the Worker has the room's targeting rules loaded; until then it takes the check path), with no /api/v1/check call and nothing reaching this server.
closed: always on, no switch. Anyone without a pass is redirected, marker or not: a waiting visitor of a closed room is meant to leave.full: off by default, switched on with the Worker variableQM_ENTRY_SHORTCUT_FULL=1. The Worker cannot see whether this server sets the marker, and a full-room redirect without it would strand waiting visitors who pressed Back. Turn it on onceCLAIM_COOKIE_DOMAINis a parent of the Worker's site (waiting visitors then carry the marker and still take the check path) and a crowd at the cap is expected. Off, a full room still works: each refused request costs one check call.- Fail-open to the check path. A failed, slow (over 800 ms), malformed or unusable entry answer counts as
open, so the check still protects the room; a failure can never turn into a redirect. - Loop guard. If the request is for the page itself (same origin and path as the target), the Worker serves it. So the default page must not sit on a path the Worker gates unless it is on the same host, where it is then served; the default pages live on the queue host, which the Worker does not gate.
- Freshness: about 10 s. The Worker keeps the answer 5 s per isolate and Cloudflare caches the route 5 s, and a stale answer is kept while one background refresh runs (at most 800 ms), so a reopen can take up to about 10 s plus one request to be seen at the edge (a close likewise). The store's own refusal is exact, so the line never goes over the cap meanwhile; only the number of requests reaching this server is bounded by the TTL. This server's own routes (
/w/,/api/join,/api/v1/entry) share one read per room per second per instance, whateverHOT_SNAPSHOTsays, so another instance can lag a close by up to a second.
Rate limiting the crowd that presses Back
People turned away press Back and refresh again and again. The layers in order: the Worker (if you run one) answers from the cached entry state; the page is cached static content; the page does not retry by itself; Cloudflare rate limiting rules per IP (below); and what the server already has (queueMaxPerIp, CHECK_LIMIT_PER_MIN, the bot sentinel and Turnstile). The server's own limits are per instance; Cloudflare is the fleet-wide control. These rules are configured in Cloudflare (Security, WAF, Rate limiting rules), not here.
What a plan allows (how many rules, which counting characteristics, which window and block durations) differs by plan and changes: check your plan before copying anything. Design for the tightest shape (one rule, counted per IP, a window of 10 seconds). The thresholds are suggestions to tune against your own traffic, not measured limits:
| Rule (expression) | Suggested threshold per IP | Why |
|---|---|---|
| The room's protected page paths on the customer's zone (not the whole site: a page load pulls many assets) | 20 requests / 10 s, then block or challenge for a short while | Keeps a refresh flood off the Worker (and its daily request allowance) or, with a server-side connector, off this server. A person pressing Back and Refresh is at most a request or two a second. |
On the queue host: /w/ and /api/join | 20 requests / 10 s per IP (WAITING_LIMIT_PER_MIN is 120 for /w/ and /api/join is 600 per instance by default) | The entry paths a refused or cookieless browser can hit. Leave /api/status and /events out: a waiting page polls by itself. |
/full/, /closed/ | Needs a Cache Rule first (below); then leave out, or 60 requests / 10 s | Cloudflare does not cache HTML or extension-less paths by default whatever Cache-Control says, so without a Cache Rule every refresh reaches this server. |
/api/v1/entry | Leave out, or 60 requests / 10 s | The Worker fetches it with a 5 s edge cache, so a refresh is a cache hit. |
Do not rate limit /api/v1/check per IP. The shop's server connector (Node, WordPress) and the Cloudflare Worker call it from their own address for every visitor, so a per-IP rule limits the connector, not the crowd (the server's CHECK_LIMIT_PER_MIN, 6000 by default, already sits there). The Worker sends a 429 from it to /w/.
The Cache Rule for the default pages (Cloudflare, Caching, Cache Rules). This is the rule that was verified on the Free plan with this server on DigitalOcean App Platform; settings the page does not list are left at their defaults:
| Setting | Value |
|---|---|
| Expression | (http.host eq "qm.weekday100.com" and (http.request.uri.path wildcard r"/full/*" or http.request.uri.path wildcard r"/closed/*")), with your own queue host. Keep the http.host term: the rule is zone-wide, and without it a page of the shop's own site under /full/ or /closed/ would be cached too. |
| Cache eligibility | Eligible for cache |
| Edge TTL | Ignore cache-control header and use this TTL, 30 seconds |
| Status code TTL | 404: No cache |
| Browser TTL | Bypass cache |
| Place at | First |
Two things differ from what you might expect. First, the Edge TTL has to be the override: with "Use cache-control header if present, bypass cache if not" the pages stayed at cf-cache-status: BYPASS here even though they send Cache-Control: public, max-age=60. Second, the override also caches 404 (the server sends no-store, which the override ignores), so the 404: No cache line stops a room created a moment ago from answering 404 at the edge for the whole TTL. The pages never change with the room's state, so 30 seconds loses nothing.
Allow 1 to 3 minutes after saving, then check with two or three GET requests a couple of seconds apart: cf-cache-status should read HIT, with an occasional EXPIRED or MISS (the edge has several cache servers that expire separately), and a 404 should never read HIT. The shop's own /full/... path on its other host must stay DYNAMIC. An old copy cached under a longer TTL can show a large Age until it expires; it does no harm.
If your plan allows a single rule, join the first two expressions with or. Offices and mobile carriers share one address between many people: prefer a challenge to a block where the plan allows it, and watch the blocked count after the first busy hour. If you run the Worker, check its request allowance too (see Workers plan limits above): every refresh that reaches the Worker is a Worker request, which is why the first rule matters (confirm in Cloudflare's documentation that rate limiting rules run before your Worker in your setup).
Watching it
- Metrics.
qm_room_entry_state{room,state}(three series per room, 1 for the current state) andqm_entry_refused_total{room,reason}(line_fullandroom_closed, per instance since start). Alert onstate="full"held for longer than a sale should last, onstate="closed"where nobody meant it (a forgotten close), and on a sustainedrate(qm_entry_refused_total[5m]).qm_room_waitingstays above 0 in a closed room (see above), so it is not a signal there. That counter resets on every restart and is per instance; for the fleet's total over time read the series below. Audit:room.close,room.reopen,room.mark_full,room.unmark_full. - Refusals per 5 s bucket (fleet-wide). Every instance also records the visitors its room turned away (
line_full,room_closed: sent to/full/<room>or/closed/<room>) into the room's 5 s metrics bucket, flushed to the shared store every 3 s in one call.GET /api/admin/metrics?roomId=&range=returns them asrefusedFullandrefusedClosedon each point (0 when none), summed over every instance, and they survive restarts and deploys (not a Valkey rebuild from the journal, which does not carry them); retention is the same 1 h as the other buckets; the hourly reports keep the per-hour totals (refusedFull/refusedClosed). They count answers, not unique visitors: someone polling/api/checkat a closed room is counted once per answer, as inqm_entry_refused_total. Only counts are stored (no IP, fingerprint or ticket). A flush the store refuses is dropped, not retried, so a Valkey outage leaves a hole; the last 3 s of an instance that is killed are lost. - Alerts. A closed room is skipped by
queue_deep,wait_high,queue_frozenandoutflow_stalled: it keeps its old waiting count (above) and admits nobody on purpose, so those rules would page about a room that is working as set.target_downstill applies. To be told a room is closed, alert onqm_room_entry_state{state="closed"}. - Snapshot. With
HOT_SNAPSHOT=roomsorall, a closed room's status polls fall back to the script (one call per poll) instead of the snapshot, so the first poll of every waiting page is answeredclosedand the page leaves; each costs one script call for as long as it keeps polling. - Join cost. The cap and close checks add two hot-field reads to every join and one
ZCARDto a minting join when a cap is set: measured indocs/bench/2026-11-09-entry-cap-join-cost.md. - The health probe is not counted. The server's own probe of a room's target (
queue-manager-healthprobe/) is not counted in the URL targeting counters. Those count door checks, not people: one visitor produces many (each page, each poll), so read a rule's count as "a real check matched", not as a visitor total.
Rolling it out
Roll the deploy to every instance before you set a cap or close a room, as for stock. An old instance's scripts do not read the new fields: it keeps minting tickets in a closed room and ignores the cap (it does not read the room's h:mw). An old instance that edits a room can write the room back without the cap and leave a stale one in Valkey, so do not edit caps while the roll is under way. A rebuild on an older build does not restore closed, and a rollback past this feature does the same: before one, note which rooms are closed and close them again after rolling forward.
The visitor-facing parts ship together, because each needs the other: the waiting page (public/waiting.html, which acts on closed and on the join refused answer) and the server that sends them. A tab opened before the deploy keeps the old page, which ignores closed, until it reloads. The Worker change is optional per customer: an old Worker still redirects through waitingRoomUrl, at the cost of one check call each.
Notification e-mail
With EMAIL_NOTIFY=1 the waiting page offers a visitor an e-mail field. Without SMTP this server only records the address. With SMTP set up (Notion 746) it sends two e-mails per place in line, each at most once:
- Near. When the visitor's place reaches the room's threshold or better (place 1 is the front). The threshold is the room's
notifyNear(1 to 1000; set it with the room API,nullfor the server default) orEMAIL_NOTIFY_AT(default 50). Not sent while the doors of a scheduled room are shut. - Turn. When the pass is minted: the head of the line passes the place and its entry window opens (
passedTtlSec). The e-mail says how long the visitor has. A visitor who already walked in with the tab open is not e-mailed.
Nothing is sent when SMTP_HOST or a valid SMTP_FROM is missing, or EMAIL_NOTIFY is off: the server then records the address, and answers POST /api/notify with delivery: "recorded" and emailDelivery: {enabled: false}. When it does send, the answer is delivery: "email" and emailDelivery: {enabled: true, nearPlace: N, onTurn: true}, and the waiting page promises the e-mail only then (and says at which place). A bad SMTP_* value (an unknown SMTP_SECURE, a SMTP_FROM that is not an address, cleartext without SMTP_ALLOW_PLAINTEXT=1) is a boot warning, shown in /api/admin/health email.problems, and leaves the channel on "recorded".
Configure it
| Variable | Example | |
|---|---|---|
SMTP_HOST | email-smtp.eu-west-1.amazonaws.com | the relay |
SMTP_PORT | 587 | 587 for starttls, 465 for tls (the default follows SMTP_SECURE) |
SMTP_SECURE | starttls | starttls (upgrade on 587; refused if the server does not offer it, never silently clear) or tls (implicit TLS, 465) |
SMTP_USER, SMTP_PASS | AUTH PLAIN (or LOGIN when PLAIN is not offered). Set both, or neither for a relay that trusts this host | |
SMTP_FROM | Queue <[email protected]> | the envelope sender and the From header; must be one your provider lets you send as |
PUBLIC_URL | https://qm.weekday100.com | the link in the e-mail is PUBLIC_URL/w/<room>. Not set: no link (a link is never built from a request's Host header) |
Provider examples. In each, verify the sending domain or address with the provider first, and set SPF and DKIM for it, or the mail goes to spam.
- Amazon SES (SMTP).
SMTP_HOST=email-smtp.<region>.amazonaws.com,SMTP_PORT=587,SMTP_SECURE=starttls,SMTP_USERandSMTP_PASSare the SMTP credentials you create in the SES console (not your AWS access keys),SMTP_FROMa verified identity. A new account is in the sandbox and sends only to verified addresses until you ask for production access. KeepSMTP_RATE_PER_SECat or below your account's send rate. - Google Workspace SMTP relay.
SMTP_HOST=smtp-relay.gmail.com,SMTP_PORT=587,SMTP_SECURE=starttls. In the Admin console (Apps, Google Workspace, Gmail, Routing, SMTP relay service) allow the address this server sends from, or use SMTP auth with a Workspace user and an app password (SMTP_USER,SMTP_PASS).SMTP_FROMmust be an address in your domain. A Workspace account has a daily sending cap: lowerSMTP_RATE_PER_MINto match. - Mailgun (SMTP).
SMTP_HOST=smtp.mailgun.org(smtp.eu.mailgun.orgin the EU region),SMTP_PORT=587,SMTP_SECURE=starttls(or465andtls),SMTP_USER=postmaster@<your-sending-domain>,SMTP_PASSthe domain's SMTP password,SMTP_FROMan address on that domain.
A private CA or a self-signed relay: SMTP_CA_FILE=/path/ca.pem. Certificates are always verified. SMTP_SECURE=none is accepted only for a loopback host (a relay on the same machine) or with SMTP_ALLOW_PLAINTEXT=1; it sends the login in the clear.
How it is kept off the queue's hot path
- One sender. Only the leader scans and sends (
STORE=memoryis always its own leader). EveryNOTIFY_SCAN_MS(5 s) it looks, room by room, at the tickets that hold an address, nearest the front first, and stops at the first place beyond the threshold, so a scan costs a handful of reads however long the line is. Nothing about this runs in a visitor's request. - Sent once, across instances and restarts. The scanner claims a mail in one atomic step in the store (
notify_claim.lua) before it queues it: of any number of instances only one gets the claim, and the near claim stays marked on the record. A failover or a restart cannot send it again. This is at most once: a leader that dies between the claim and the SMTP answer loses that one e-mail rather than repeating it. A visitor who removes the address and files another does not earn a second near e-mail either (the marks are kept, the address is not). - Bounded queue. Messages wait in an in-memory queue of
SMTP_QUEUE_MAX(1000). A full queue refuses; the scanner then claims nothing more until there is room, so nothing is lost but a late e-mail, andqm_email_dropped_totalcounts the refusals. - Paced.
SMTP_RATE_PER_SEC(5) sends per second andSMTP_CONCURRENCY(2) connections per instance, andSMTP_RATE_PER_MIN(300) per minute for the whole fleet (one counter in Valkey; one process onSTORE=memory). One message per connection. - Retries. A temporary failure (a 4xx answer, a network error, a timeout) is tried again after
SMTP_RETRY_BASE_MS(5 s), then 4x that, then 16x, with jitter, up toSMTP_MAX_ATTEMPTS(4) attempts. A permanent failure (5xx) is not retried. A message is counted as failed once, when it is given up on. - Shutdown. A graceful stop gives the queue up to 5 s to empty.
Privacy: what is kept, and for how long
- The address is deleted when the turn e-mail is handed to the sender, and with the ticket on every other end (admitted at the door first, left, ejected, purged, the room deleted), and in any case at most 24 h after it was filed (
LAPSED_TTL_MS). The near e-mail leaves it in place until then. - It is held in memory by the sender only until the attempt ends, and is never logged: log lines,
/api/admin/healthand/metricscarry reasons and SMTP codes, and any address an SMTP server echoes in its answer is replaced by[address].SMTP_PASSis never printed. - The e-mail carries no token, ticket number or reference code, only the room's name and the bare link. What proves a place is the browser's
qms_<room>cookie, so the e-mail says to open the link in the browser the visitor joined from; a forwarded e-mail opens a page that gives its reader a new place at the back, and cannot take the sender's. - The language is the waiting page's at sign-up: Thai for
th, English for anything else. Each e-mail is plain text and HTML in one message. - Anyone holding a place can file any address (there is no confirmation e-mail), so a stranger can be sent at most these two messages per place. The
NOTIFY_LIMIT_PER_MINbudget and one place per visitor bound it. If that matters to you, do not turn the channel on.
Watching it
/api/admin/healthemail:{notify, smtpConfigured, enabled, host, port, secure, authenticated, nearDefault, sender, queued, inflight, sent, failed, retried, dropped, superseded, lastOkAt, lastError, lastScanAt}.lastErroris{at, reason, code?, message}with no address and no secret.senderis true on the one instance that sends.problemslists a setting that stopped it. A share (monitor) link does not seehost,portor the error text./metrics:qm_email_sent_total{kind="near|turn"}(the SMTP server said 250),qm_email_failed_total{reason}(rejectedis a recipient the server refused: a bounce at the door;permanent,auth,tls,network,timeout,temporary,protocol,invalid),qm_email_retried_total,qm_email_queued,qm_email_dropped_total,qm_email_superseded_total(a near e-mail dropped because its place moved on: the turn e-mail was claimed first, the ticket ended or the address changed; a retried near e-mail therefore never arrives after the turn one) andqm_email_claimed_total{kind}. They exist only while the channel is on. Alert on a risingauthortls(the relay changed), onqm_email_queuedstuck above 0 (SMTP is down), and on anydropped.- A bounce that comes back later as a message to the sending mailbox cannot be seen by this server (it is an SMTP client, not a mail server): read that mailbox, or use the provider's bounce webhook. For Mandrill this server has one: Delivery status.
Delivery status: Mandrill's webhook
Mandrill answers 250 on SMTP and may reject or bounce the message afterwards (a recipient on its denylist is rejected with reject_reason: hard-bounce). To this server that mail was sent: qm_email_sent_total counts it and /api/admin/health email.lastError stays empty. Mandrill's webhook is how the server hears what happened next. It is off unless MANDRILL_WEBHOOK_KEY is set.
Set it up (the order matters: Mandrill checks the URL when you add it, and only shows the key after):
- Choose the URL,
https://<your host>/api/hooks/mandrill, and setMANDRILL_WEBHOOK_URLto it. SetMANDRILL_WEBHOOK_KEYto any placeholder of 16 or more characters for now. Deploy. The server then answers Mandrill'sHEADcheck with200(aHEADneeds no signature; only aPOSTdoes). - In Mandrill, Settings, Webhooks, add a webhook: Post to URL is the same URL, character for character. Tick Message is sent, Message is delivered, Message is delayed, Message is bounced, Message is soft-bounced, Message is marked as spam, Message is rejected and Message recipient unsubscribes (the events
send,delivered,deferral,hard_bounce,soft_bounce,spam,rejectandunsub). Leave Message is opened and Message is clicked off: they need Mandrill's open and click tracking, and nothing here uses them (they would only be counted). Leave Rejection Denylist changes and Rejection Allowlist changes off too: the server ignores those events. - Copy the key Mandrill shows for that webhook into
MANDRILL_WEBHOOK_KEY(replacing the placeholder) and deploy again. Until then everyPOSTis401and counted underqm_email_webhook_requests_total{result="unauthorized"}.
The request. POST /api/hooks/mandrill, application/x-www-form-urlencoded, one field mandrill_events holding a JSON array of events. X-Mandrill-Signature is base64(HMAC-SHA1(MANDRILL_WEBHOOK_KEY, MANDRILL_WEBHOOK_URL + each form field's name and value, sorted by name)), compared in constant time. Answers: 200 {ok, counted, ignored}, 401 unauthorized (no or wrong signature), 400 invalid_events (signed, but not a JSON array), 413 payload_too_large (over 1 MiB), 429 too_many_auth_failures, 404 (off), 405. A wrong signature spends the same failed-auth budget as a wrong admin key (ADMIN_AUTH_FAIL_PER_MIN, per client address, fleet-wide on STORE=valkey), and an address that has emptied it is refused until it refills, the right signature included. The bucket is looked at before the body is read and again, fresh, once the signature has verified, so a request held open while the address's bucket was emptied is refused too (429, nothing recorded); on STORE=valkey the second look reads the fleet's bucket, not the 1 s AUTH_NONE_TTL_MS memory of the first. Nothing in the body is read before the signature is proven.
What it keeps. Events are counted by name: send, delivered, deferral, hard_bounce, soft_bounce, open, click, spam, unsub, reject. Any other event, and anything that is not an object, is ignored (counted as ignored); at most 1000 events of one batch are read. The last 50 failures (reject, hard_bounce, soft_bounce, spam) are kept in memory with their time, event, masked address and reason (Mandrill's msg.bounce_description, else the reject reason (reject.reason, msg.reject.reason, msg.reject_reason or reject_reason), else msg.diag; control characters removed, any address inside it masked, at most 200 characters; a reason that still shows an address in a form that cannot be masked, such as a quoted local part, is not shown at all). A recipient that is not a valid address is shown as none. No address is logged or stored, and the list is lost on restart. Counts and the list are per instance: Mandrill posts to whichever instance the load balancer picks, so sum the counters across instances as for qm_email_sent_total. Mandrill retries a batch it got no 200 for, and events can arrive late or twice, so read the counts as a trend, not a ledger.
Watching it.
/api/admin/healthemaildelivery:{counts, ignored, lastEventAt, recent, webhook}:countsby event,recentnewest first ({at, event, address, reason}),webhookthe request results below. A share (monitor) link seescounts,ignored,lastEventAtandwebhook, notrecent. The console's Diagnostics dialog shows the counts and the latest five failures./metrics:qm_email_delivery_total{event}andqm_email_webhook_requests_total{result}(ok,unauthorized,bad_request,too_large,locked). They exist only while the webhook is on. Alert on a risinghard_bounceorreject(mail that never arrived; arejectwith reasonhard-bounceis a recipient on Mandrill's own denylist, which you clear in Mandrill), and onunauthorized(a wrong key, or aMANDRILL_WEBHOOK_URLthat is not exactly the URL in Mandrill).- Behind Cloudflare, let Mandrill reach the path: a WAF, bot or rate-limit rule that challenges it makes Mandrill's
POSTfail. WithEDGE_SECRETset it needs the same Cloudflare header rule as every other request.
Limits and rollback
- A ticket moved by a priority code (it stands in front of tickets with lower numbers) is looked at on every scan whatever its number, so it is e-mailed at its real place; only tickets that follow their number let the scan stop early. A visitor who is already inside, or who has been at the door, is never e-mailed.
- Rolling deploy from a build before Notion 746. The marks of what was already sent live in the address record. An instance still on the old build that saves an address again (a visitor re-saving it from the waiting page) writes the record without them, so that visitor can get a second "near" e-mail, and one that names a different address aims it there. Only the leader of the new build sends, so nothing else doubles. Set
SMTP_HOSTin the last step of the roll, once no old instance is serving visitors. - A room that is sold out (stock at 0) holds its line, so no "near" e-mail is claimed while it is: "your turn is close" would not be true. It goes when stock comes back, if the place is still within the threshold. A pass minted before the stock ran out is still mailed.
- The sender is per leader: a message queued on a leader that dies is lost, not repeated. SES or the relay's own retry applies after the server has said 250.
- Rolling back to a build from before Notion 746 leaves the stored addresses as they were: that build records them and sends nothing, and ignores the marks.
notifyNearis the E-mail "your turn is near" at place field in the console's room editor (1 to 1000; empty uses the server default, which the box shows as its placeholder; it is disabled, with the reason, while this server sends no e-mail, and keeps the room's value). The API takes it too:POST /api/admin/rooms {"id": "...", "notifyNear": 5}.
Threshold activation (the 3 a.m. spike)
A room can switch itself on. Set autoActivate on the room, or use the Threshold activation fields in the room editor:
{"enabled": true, "joinsPerMin": 120, "sustainSec": 60, "releaseAfterSec": 300}
The room moves bypass → active once arrivals hold at or above joinsPerMin for sustainSec, and back to bypass after releaseAfterSec of quiet. releaseAfterSec: 0 means it never stands down by itself.
- It only ever moves
bypass⇄active. A paused room is an operator decision and is never overridden. - It never stands down while anybody is still in the line.
- Both directions are annotated on the room's timeline and written to the audit trail under the
systemactor, with the number that caused the flip. While it is armed the room card carries anAUTO ≥n/MINbadge, and for 15 minutes after it acts on its own that badge turns amber and readsAUTO · SELF, so a queue the machine put up is never mistaken for one a person put up. - With
SIDESTORE=pgtimeline annotations survive a restart: they are kept in Postgres (24 h, saved about a second after each change and on clean shutdown), so the marks are still on the chart during the post-incident review. - The trigger is arrivals per minute and nothing else. A concurrency threshold is not offered because nothing meters sessions while the queue is switched off, so it could never fire; it would be a control that looks armed and is not. The number to compare against is the room card's joins/min, which is the same figure the automation reads.
This is different from AUTOTUNE, which adjusts the outflow rate of a room that is already queueing.
Historical reports
/api/admin/reports serves one row per room per hour (or per day), retained for HISTORY_RETAIN_DAYS:
curl -s "https://qm.weekday100.com/api/admin/reports?bucket=day&from=2026-08-01&format=csv" \
-H "Authorization: Bearer $ADMIN_KEY" -o last-month.csv
Columns: roomId, bucket, start, startIso, joins, passes, netUnserved, peakDepth, avgDepth, peakActive, waitP50Sec, waitP90Sec, waitMaxSec, waitAvgSec, measuredWaits, blocked, warned, samples, partial, coveredSec, missingSec, refusedFull, refusedClosed. The coverage and refusal columns are appended last, so an importer keyed on column position keeps working.
| column | what it counts |
|---|---|
joins | tickets issued |
passes | tickets promoted: permission to enter, not an entry |
netUnserved | joins - passes; null on a partial row |
peakDepth / avgDepth | queue depth, from the depth gauge |
peakActive | sessions on the protected site: the "people who got in" column |
waitP50Sec / waitP90Sec | estimated wait percentiles |
waitMaxSec / waitAvgSec | exact longest and mean wait |
measuredWaits | promotions that carried a measured join→pass duration |
blocked / warned | protection decisions; with several instances, the whole fleet's (each instance's shared counters) |
refusedFull / refusedClosed | visitors turned away at a full / closed state in the hour; null on a row written before they were counted (unknown, not 0). Counted from the 5 s buckets once per sample tick, so a refusal flushed more than ~3 s late can be missed |
samples | sample ticks folded into the row |
Four labels travel with every JSON response:
waitP50Sec/waitP90Secare estimates. Each hour keeps a bounded reservoir of up to 256 waits, uniformly sampled.measuredWaits,waitAvgSecandwaitMaxSecare exact.measuredWaitsis not "people who entered the site". It was formerly calledadmitted, a name that invited that misreading. It is the denominator underwaitAvgSecand the weight under the percentiles: how many people finished waiting in the period. A room at a concurrency ceiling of 5 that minted ten passes reportsmeasuredWaits: 10, because ten people finished queuing; five were then turned away at the door and never got in.peakActiveis the column that counts sessions on the site. See The claim window in Passes vs sessions for why those two populations differ.netUnservedis joins minus passes, not observed abandonment. Inside a single hour it also counts everyone still waiting when the clock ticked, so read it as an abandonment proxy only over a day or more.partial: truemeans the row has a hole in it. The server was not running for part of that period, sojoins,passes,measuredWaits,blockedandwarnedare lower bounds, not totals.coveredSecandmissingSecsay how much was and was not counted, andnetUnservedisnull: it cannot be derived from a partial count, and reporting it as0beside a 45,000 peak depth is how a post-mortem reaches the wrong conclusion. The console marks those rows⚠and suffixes their counters with+.
The open hour is folded in live, so a report run at 10:59 is not missing the last 59 minutes. With STORE=valkey a report Postgres cannot answer is 503 storage_unavailable (retry). It is written to the warehouse on a clean shutdown; see Stopping the server below, because on Windows the obvious way to stop a process is not one.
There is no scheduled or emailed report and no warehouse push. The CSV is the integration point.
Refusals: when the server will not start
Most misconfigurations are warnings. These five are not, because starting would be worse than stopping: the process would come up looking healthy and answer questions wrongly, or lose on the next restart what it had just accepted. Each one exits non-zero and prints the setting and the way out.
| It refuses when | Because | What to do |
|---|---|---|
NODE_ENV=production without both STORE=valkey and SIDESTORE=pg | Memory mode keeps nothing across a restart: every deploy would empty the queue, the rooms and the operators, and several instances would each run a queue of their own. The refusal names each missing setting. There is no override. | Set STORE=valkey and SIDESTORE=pg, with what they need (SECRET, VALKEY_URL, DATABASE_URL). |
SIDESTORE=file | The file side store was removed in step 5: nothing is written to local disk any more. | Use SIDESTORE=pg, or SIDESTORE=memory (the default on STORE=memory) in development. |
STORE=valkey without SIDESTORE=pg, SECRET or VALKEY_URL | The queue is journaled to Postgres, every instance must sign and verify with the same key, and there is no Valkey to connect to. The refusal names each missing setting. | Set what it names. |
SIDESTORE=pg without SECRET or DATABASE_URL | Without SECRET the key is new on every boot, and a new key on every deploy voids every pass (visitor tickets, monitor links, operator keys) that Postgres keeps. | Set SECRET (openssl rand -hex 32) and DATABASE_URL. |
ADMIN_KEY is the default admin-dev and HOST is set to anything but loopback (0.0.0.0, ::, a real address) | The default key is printed in these docs. Listening beyond loopback with it puts the surface that deletes rooms and ejects visitors on the network behind a public password. With HOST unset it does not refuse: it binds 127.0.0.1 only and says so, so node server.js on a laptop works as it always has. | Set ADMIN_KEY to a secret (openssl rand -hex 32). For local use only, HOST=127.0.0.1. |
A few single settings refuse on their own, and their rows in the environment table say so: an unknown STORE or SIDESTORE value, a missing PG_CA_FILE, a malformed QM_INSTANCE_ID. Everything else (a typo in a numeric variable, a short SECRET, thresholds in the wrong order) starts, and appears in warnings on /api/admin/health. A value that could not be applied as written is never silently substituted: the warning names the variable, what you set, and what is actually in effect.
Rolling back across the token-signing change. A release that predates per-purpose keys reads only the legacy token form. While TOKEN_SIGN_V2 is unset (the default), this release writes nothing else, so rolling back is safe. After TOKEN_SIGN_V2=1, rolling back does not refuse to start, but every v2 token is refused: visitors rejoin at the back, share links and console sessions end, and every operator whose key was minted or re-keyed under v2 gets 401 (mint them new keys). Turning TOKEN_SIGN_V2 off again stops new v2 tokens, and after the token lifetimes run out none are left. It does not convert v2 operator verifiers back, so those operators still need new keys. See Signing keys and rotating SECRET.
Signing keys and rotating SECRET
SECRET is the root of every signature the server makes. Tokens have the format base64url(JSON payload) "." base64url(HMAC-SHA256(key, body)), in one of two forms. Both forms are always accepted. TOKEN_SIGN_V2 only chooses which form this server writes.
- Legacy (default, the form every earlier release wrote): the key is
SECRETitself and the payload has nokid. - v2 (
TOKEN_SIGN_V2=1): each purpose has its own 32-byte key,K(purpose) = HKDF-SHA256(ikm = SECRET, salt = empty, info = "qm:<purpose>", 32)
for visitor (queue tickets and pre-queue handles), monitor (share links), session (the console's qm_console cookie) and operator (the stored verifier of an operator key). The payload carries kid: the lowercase hex of HKDF-SHA256(ikm = SECRET, salt = empty, info = "qm:kid", 4), eight characters that name the SECRET without revealing it. The kid picks the key a token is checked against. A kid the server does not hold is refused. Two instances agree on signatures exactly when their v2 tickets show the same kid.
What the per-purpose separation does and does not cover. A v2 token minted for one purpose never verifies as another. A legacy token carries no purpose, so it is accepted for any purpose whose payload checks pass. That is exactly as before per-purpose keys existed, and those checks (scope, room, ticket fields) are what keep a visitor ticket from opening the console. While TOKEN_SIGN_V2 is off, every token this server issues is legacy, so the separation is not yet in force. It takes effect for tokens issued after TOKEN_SIGN_V2=1, and fully once the last legacy token has expired.
Two releases. Ship this release with TOKEN_SIGN_V2 unset. It accepts both forms and writes only the legacy one, so it can be rolled back freely. Once it is settled on every instance, set TOKEN_SIGN_V2=1 everywhere. Legacy tokens already issued keep working for the rest of their life, and legacy operator verifiers are re-keyed to v2 as each operator next authenticates. For what changes if you roll back after that, see Rolling back across the token-signing change above.
Rotating. Tokens live up to TOKEN_MAX_AGE_SEC (24 h) for visitors, MONITOR_TOKEN_TTL_SEC (7 days) for share links and 12 h for console sessions. Rotate with TOKEN_SIGN_V2=1:
- Set
SECRET_PREVIOUSto the current value andSECRETto the new one, on every instance, and restart them. New tokens carry the new kid. Tokens under the old kid keep verifying, so nobody in line loses their place. - Wait out the longest life you care about: 24 h keeps every visitor ticket (the one that matters); 7 days also keeps every share link, which the console can otherwise re-copy under the new key. Operator keys have no expiry. Each operator that authenticates during the window is re-keyed to the new SECRET on that request. An operator key not used during the window stops working when you remove
SECRET_PREVIOUS, so mint that operator a new key. - Remove
SECRET_PREVIOUSand restart. Tokens under the old kid are now refused.
With TOKEN_SIGN_V2 off, the same steps still work, just without a kid. Legacy tokens name no SECRET, so each one is tried against the raw SECRET and then the raw SECRET_PREVIOUS. Nothing in a ticket tells you, or a log, which SECRET signed it, and nothing will refuse an unknown key by name: such a token just fails both tries. Visitors, share links and console sessions survive the rotation all the same. Operator verifiers are moved to the new SECRET in the form they already had (a v2 verifier is never downgraded). Prefer rotating with TOKEN_SIGN_V2=1. The kid is what lets you check every instance agrees (compare the kid in their tickets) and see when old tokens are gone.
Rotating without SECRET_PREVIOUS invalidates every ticket at once: the queue re-joins at the back (the server logs a warning when refused tickets arrive in a burst), every share link and console session ends, and every operator key stops working. A leaked SECRET is the one case where that is what you want.
Several instances (STORE=valkey)
With STORE=valkey and SIDESTORE=pg the server runs as several identical instances behind one load balancer, with no sticky sessions: a visitor or an operator may reach a different instance on every request and gets the answers one instance would give. Every instance needs the same SECRET, VALKEY_URL, VALKEY_PREFIX and DATABASE_URL; none keeps anything on its own disk. The design is in docs/adr/0001-live-state-in-valkey.md in the repository.
With STORE=memory (development only) several instances share nothing but what you give them. A shared SECRET makes a ticket's signature valid everywhere; it does not share the line. Each instance keeps its own rooms, ticket numbers and rate, and a place in line exists only on the instance that issued it, so one room spread across several makes several independent queues, each letting people through at the full rate.
- Shared. The queue (rooms, tickets, the line, admission) is in Valkey and journaled to Postgres. Every instance runs the one-second tick, and each tick credits a room the exact time since the room's shared last tick, claimed atomically, so N instances credit exactly what one ticker would credit at all their tick instants combined: the long-run rate and the one-slot bank are unchanged. A room that holds nothing (no line, session, pass, pending claim, door entry, ejected record, recent join or pass, notify intent, purge in progress, unfinished sweep or open due; lapsed history does not count) skips a tick that comes less than 250 ms after its last full one, after a few cheap reads, so an empty room costs Valkey about four full ticks a second however many instances run; the first visitor ends the skipping at once. Operators, monitor links and timeline notes are written row by row to Postgres and re-read by every instance when another changes them: a hint over Valkey pub/sub (
<prefix>ctl), repaired withinRESYNC_MSif it is lost. The same check rebuilds the room config that gates requests (sentinel protection, the inline host index,onBackendDown). Console logouts, console stream tickets, theADMIN_AUTH_FAIL_PER_MINbudget, target health, the alert state and turn-notification addresses are in Valkey. An operator key, console session or monitor link whose copy this instance cannot confirm is refused with503(seeRESYNC_MS), never let through on a stale copy. Every console reads the rooms from Valkey on its 2 s tick, so a change made through one instance shows on the consoles of all of them within one tick. - One leader. Target probes, autotune, threshold activation, alert delivery and the hourly history rows run only on the instance holding the leader lease, so each happens once for the fleet (see
LEADER_LEASE_MS).leaderon/healthzsays whether this instance holds it. When the leader dies another instance takes over within aboutLEADER_LEASE_MS; a clean stop hands the lease back at once. While Valkey is unreachable no instance leads and those jobs pause, and each instance sends its ownvalkey_unreachablealert (seeVALKEY_ALERT_AFTER_MS). - Per instance. The per-address budgets (
JOIN_LIMIT_PER_MIN,CHECK_LIMIT_PER_MIN,WAITING_LIMIT_PER_MIN,NOTIFY_LIMIT_PER_MINand the rest) and the stream caps (SSE_PER_IP,SSE_MAX_TOTAL) are each instance's own: N instances allow up to N times each. Cloudflare's edge rate limiting is the fleet-wide control./metricsreports this instance's own process, with aninstancelabel (QM_INSTANCE_ID, a display name only): scrape each instance (see Metrics and monitoring). The console's counters are the sum over the live instances. - Deploys. A deploy replaces every instance, and each stop ends every stream on that instance. Nothing about the line is lost (it is in Valkey). A waiting page starts polling
/api/statusafter a random 0-2 s, then every 5 s +-20% (drawn again each poll; a stream that recovers first cancels the poll), so pages that lost their stream together do not poll in step. It reopens its stream: the browser retries it, and once the browser gives up the page retries after 2 s, then longer, up to 20 s. A console reconnects and gets a full frame. During a rolling deploy every instance must serve every waiting-page asset hash still being handed out (see Waiting-page assets and live streams across a deploy). - Stopping one.
POST /api/admin/shutdownstops only the instance that answered it, which behind a load balancer is whichever one the request reached (see Stopping the server).
Readiness (/healthz)
The payload carries two different judgements, and they are not the same question:
status:ok,degradedorshutting_down. "Is anything wrong that an operator should look at?" A target origin that stopped answering, or a clock that stepped, makes thisdegraded, and the same text appears inincidentson/api/admin/healthand on the console badge.ready:trueorfalse. "Should a load balancer send this instance visitors?" This is what the HTTP code follows:200whenready,503when not.
ready goes false for exactly three reasons:
- storage is degraded (on
STORE=valkey, only this instance's: see below); the instance cannot persist a join, so it already answers503 storage_unavailableto every visitor who tries to take a ticket. It must not keep being handed a share of the surge. OnSTORE=valkeya failed events-journal commit to Postgres makesstatusdegraded(withstorage is degraded: events journal commit failed: …inincidents) and pagesstorage_failing, but leavesreadytrue: every instance shares the one Postgres, so taking them out of rotation fails the whole fleet out of the load balancer and moves no join anywhere it could be persisted. Each join still waits for its own commit and answers503 storage_unavailablewhen it fails, so no ticket is acknowledged that is not in Postgres. Storage reads healthy again once a later commit has landed and 3 ×ALERT_EVERY_MShave passed since the newest failure, so a fault that comes and goes stays failing rather than reading ok between failures;storage.writeErrorskeeps counting.storage_failingpages once two alert frames within that window saw new failures: one failed commit (or one refused join, which is its commit and its rollback's) shows as degraded but does not page; an intermittent fault, or a failure still there at the next frame's probe, does. With no traffic to prove it, each alert frame probes the journal while it is failing (the commit's insert, for one row, in a transaction rolled back), so a blip in a quiet hour recovers on its own. The exception is a fault of one instance: when this instance's journal is failing while another instance reported its storage ok in the last 3 ×ALERT_EVERY_MS, moving visitors elsewhere does get their joins persisted, soreadygoes false (storage is degraded on this instance only) and the load balancer takes only this instance out. Readiness follows a hard failure only, not the window above: it goes out when its journal has had no commit or probe land since its newest failure and two alert frames in a row each saw a new failure (a commit, or the frame's probe), and comes back at the first commit or probe that lands (the probe proves it with no traffic). A single statement timeout whose next commit lands does not take it out. An instance whose own commits are failing does not count as ok. When no other instance is ok (the shared Postgres, a fleet of one, Valkey unreachable) it stays in. shutting_down: set the instant a stop begins, before the final snapshot and before any connection is closed, so a load balancer stops sending new work while requests already in flight finish.- at the connection ceiling:
MAX_CONNECTIONSreached, so new requests are already being answered503here instead of proxied (seeCONNECTION_RESERVEin the environment table, and the surge table above). A load balancer still sending this instance its share of a surge is the opposite of what a readiness probe is for. Note thatstatusstaysokthrough this (saturation raises no incident), so "alert onstatus, page onready" below is not two ways of saying the same thing: this is the case onlyreadycatches.
A customer's origin being unreachable deliberately does not clear ready, and neither does a clock step. Both are reported as incidents; neither is a reason to deregister the pod. Wiring readiness to them turns one origin outage into a total waiting-room outage: every instance fails its probe at once and the estate empties out of the load balancer, so the component whose whole job is standing in front of a site that is down is the component that disappears. Restarting a pod does not fix somebody else's origin or this machine's clock.
With STORE=valkey the payload also carries backend: {store, valkey, recoveringRooms, ok}. valkey is up or down (this process's connection; also down for 5 s after a command timed out on a connected socket), recoveringRooms counts the rooms being rebuilt from the Postgres journal (marked here, or answered as fenced by Valkey in the last 30 s); /healthz is public, so it carries the number only and /api/admin/health names the rooms (it also carries instance, the name of the instance that answered, and fleet: {instances, partial}, see Metrics and monitoring; the public /healthz carries neither). Either makes status degraded and adds an incident on /api/admin/health; neither clears ready, because every instance shares the one Valkey and taking this one out of rotation fixes nothing. What visitors get meanwhile is onBackendDown.
leader (true or false) says whether this instance holds the leader lease and runs the fleet-wide jobs: target probes, autotune, threshold activation and alert delivery (see LEADER_LEASE_MS). In a STORE=valkey fleet exactly one instance says true, and none does while Valkey is unreachable, which pauses those jobs. It never changes ready or the HTTP code. With STORE=memory it is always true.
Point k8s readiness, your ALB target group and your uptime monitor at /healthz. Alert on status, page on ready. /api/version returns the same payload but always 200: it answers a question about the build, not about readiness, so a rollout script reading it is not tripped by a degraded instance.
Inline deployments: which address the probe uses decides what it gets. A probe that addresses the process (a pod IP, a container port, localhost) asks for a host no room fronts, so /healthz is the queue's own route and answers normally. A probe that addresses the public hostname is a visitor as far as this server is concerned, and /healthz there is the customer's path: measured on an inline host, GET /healthz answers 503 with {"code":"queued"} for ever, because a monitor never gets admitted. Wire that to an ALB target group and it deregisters every healthy instance you have.
Under the reserved prefix it is the queue's route again. On the public hostname, probe /__qm/healthz:
| Probe addresses | Path to use |
|---|---|
the process (pod IP, container port, localhost) | /healthz |
| the public hostname of an inline room | /__qm/healthz |
| the queue's own hostname (snippet deployments) | /healthz |
The same split applies to /api/version and to /metrics below.
HEAD works everywhere GET does, and answers the same status and the same Content-Length with no body, so a check that defaults to HEAD (many do), or a curl -I on a connector download, gets the truth rather than a 404. It is the same answer, so it makes the same decision: a HEAD /healthz on an inline public hostname is still 503, for the reason above.
When the queue itself is down
ready going false takes one instance out of rotation, which is the normal case and costs nobody anything. This section is about the other one: every instance unready at the same time.
If the queue is deployed inline (Users → Cloudflare → Queue → your app), then "every instance unready" means the site has no path to the app. Somebody has to decide what the visitor gets, and the decision is not the queue's to make at request time; it is a routing rule you write in advance.
The decision taken here: serve a static page, do not fail open. Failing open sends the full surge at an origin with nothing in front of it, the exact outage the queue was bought to prevent, arriving at the worst possible minute. A campaign unreachable for a few minutes is recoverable; a melted origin is not. If your campaign is worth more than that risk, route the failover pool at the app instead and accept what follows. Decide it now, not at 21:04.
public/offline.html is that page. The running server hands it out at /offline.html, and it has to end up somewhere Cloudflare can serve without this server.
It is deliberately built for that job: one self-contained file, no <link>, no <script src>, no image, no webfont: every subresource would be a request to the origin that just stopped answering, and a half-rendered apology looks like a second bug. It carries the same five languages as the waiting page and reads the same qm_lang key, so a visitor who picked Thai on the way in still gets Thai. It retries on its own with jittered backoff (20 s → 60 s, plus up to 80 % random), because everyone landed on it in the same second and a fixed interval would send the whole crowd back in one synchronised wave, hardest exactly as the queue is trying to come up.
It does not show a position, an ETA or a progress bar. The component that holds places is the one that is down, so any number there would be invented.
Wiring it up: the failover Worker (no Load Balancing subscription needed). This server builds and serves it, with its own copy of offline.html already inlined, so the deployed page cannot drift from the shipped one:
curl -fsSL http://localhost:8080/connectors/cloudflare-failover/latest.js -o qm-failover.js
npx wrangler deploy qm-failover.js --name qm-failover \
--compatibility-date 2025-01-01 --route 'YOUR-QUEUE-HOSTNAME/*'
Or take the whole wrangler project (wrangler.toml, a pre-deploy check, the README) from /connectors/cloudflare-failover/latest.tgz and keep it in your own repo. npm run deploy runs the check first. There is no room id and no API key to configure: this Worker never calls the queue's API.
Route it at the hostname the queue answers on (inline, that is your public hostname). It is not the edge gate connector (/connectors/cloudflare), which decides who waits and belongs in front of your origin in a snippet deployment. Cloudflare runs one Worker per route, so give the two different patterns.
What it acts on, and the two exceptions that make it safe:
| The queue answered | Worker does |
|---|---|
| nothing (refused, DNS, TLS, timeout) | offline page, 503 |
521 to 527, 530 (Cloudflare could not use the origin) | offline page, 503 |
503 with X-QM-Queued | passes through |
503 without that header | offline page, 503 |
502 / 504 | passes through |
| anything else | passes through |
503 alone is never enough to act on. A perfectly healthy gate answers 503 to every poll from a visitor who is still waiting, and marks those with X-QM-Queued. Replacing them with the outage page takes a working queue off the air and swaps a live countdown for "we are down".
502/504 are not this rule's business. Those mean the queue is up and your app is down, and this server already answers them itself; see When the site behind the queue is down below. Serving offline.html there would tell the visitor entry is unavailable when in fact they are through and it is the site that is broken.
After deploying, prove it: stop the queue and load a page. The response carries X-QM-Failover: unreachable (or timeout, or http-<status>), so a curl -I tells a working failover from a coincidence. This is the one piece of the product that is never exercised in normal operation: nothing else will tell you it is broken until the night it matters.
Or a Load Balancer, if you have one: primary pool = the queue instances, health check GET /healthz (that is what it is for), failover pool = wherever you put offline.html. With STORE=memory (development only) the instances do not share a line, so the pool must pin each room to one instance: a second instance is a failover target, not extra capacity for the same room. With STORE=valkey they share it, and the primary pool is every instance (see Several instances (STORE=valkey)).
Either way, the Worker above does all five; a Load Balancer's failover pool has to be configured for them:
503, not200. A200tells crawlers and uptime monitors the page they got is the site.Retry-Afterso well-behaved clients back off on their own.Cache-Control: no-store, or Cloudflare will keep serving the apology after the queue is healthy again.- The page also carries
noindex, which is the belt to that braces. - Scope the rule to document requests. A
/favicon.icothat 404s is fine; answering it with a page of HTML is not.
The edge gate fails open, and says so
The rule above is for a queue deployed inline. The edge gate connector (/connectors/cloudflare) sits in front of your origin and asks the queue per request; when the queue is slow or failing it fails open: the visitor goes to origin unqueued, because a queue that is down must never be an outage of the site it protects. That stays. It is not silent (connector 1.1.0, QM-340):
- Every fail-open response carries
X-QM-Failover: <reason>:timeout(no answer within 2 s),unreachable(connect/DNS/TLS failed),http-<status>(any non-2xx except 429:http-503,http-401for a rejected key), orinvalid-response(a200that is neither apassnor a usablequeue). Same header and names as the failover Worker, but here it means forwarded unqueued, not offline page. An answer the queue actually gave (a pass, a redirect to the waiting room) is never marked. A Worker with no configuration or no key forwards unmarked and says so in its log instead; that is a deploy mistake, not the queue failing. - A
429is not a fail-open (connector 1.2.0, QM-379). An exhaustedCHECK_LIMIT_PER_MINis the queue up and shedding load, so the Worker sends the visitor to the waiting room (/w/<room>) instead of the origin: noX-QM-Failover, no Analytics Engine count, one log line per isolate. The Node connector (1.1.0), the WordPress plugin (1.2.0) and the browser tag (1.4.0) do the same. It shows up on the server asqm_rate_limited_checks_total; a sustained increase means visitors the room may have had space for are waiting; raiseCHECK_LIMIT_PER_MIN. - Each one is counted in Workers Analytics Engine when a dataset is bound as
QM_ANALYTICS. Without the binding nothing is counted and nothing breaks.# wrangler.toml of the edge Worker [[analytics_engine_datasets]] binding = "QM_ANALYTICS" dataset = "qm_failover"
Each data point is blob1 = room id, blob2 = reason, double1 = 1, index1 = room id.
Alerting on it. The queue server cannot count checks it never received, so the alert has to read the edge's numbers, not the server's. Run this against the Analytics Engine SQL API from whatever already pages you (a cron, your monitoring system's HTTP check), every few minutes, with an API token that has Account Analytics: Read:
curl -s "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/analytics_engine/sql" \
-H "Authorization: Bearer $CF_API_TOKEN" --data "
SELECT blob1 AS room, blob2 AS reason, SUM(_sample_interval) AS fail_opens
FROM qm_failover
WHERE timestamp > NOW() - INTERVAL '5' MINUTE
GROUP BY room, reason
ORDER BY fail_opens DESC
FORMAT JSON"
Alert when any row comes back: every one is a visitor who reached the origin without being queued. SUM(_sample_interval), not COUNT(), because Analytics Engine samples at high volume and records the rate it kept. timeout/unreachable/http-5xx means the queue is down or drowning; see /healthz above. For a spot check without the dataset: curl -sI https://shop.example.com/checkout | grep -i x-qm-failover.
Why this and not the Worker reporting its counts back to the queue when it recovers: a Worker's memory is per isolate, isolates are evicted freely and there are many per colo, so a replayed count is lossy exactly during a long outage; it could not report a 401 at all (the key is what is failing); and it would add a write endpoint to the server. Analytics Engine is written at the moment of failure, independently of the queue, and aggregated across every colo.
When the backend is down (onBackendDown)
With STORE=valkey, a room's live state is in Valkey. When Valkey cannot be reached (connection lost, command timeout, failover) or a room is being rebuilt from the Postgres journal after Valkey lost or rolled back its state, the API answers 503 storage_unavailable with Retry-After: /api/check, /api/join, /api/status and the rest, snippet and inline alike. A room that is recovering never answers no_room.
Operator changes around a rebuild. A rebuild replays what the Postgres journal held when it read it. A change that ran in Valkey but reached the journal only after that read is not in the rebuilt room. Creating or editing a room, changing its schedule (opensAt) or deleting it waits for its journal entry, so such a change answers 503 storage_unavailable, although it ran, when the rebuild left it out (or the room is fenced when it lands): retry it once the room answers again, and it applies to the rebuilt room. Pausing, resuming or changing a room's rate (by an operator, autotune or threshold activation) is journaled in the background and answers 200 at once, so one made in the seconds before Valkey lost the room can be undone by the rebuild without an error: after a recovery, check the room's state and rate in the console and set them again if they are not what you left.
Valkey must run with maxmemory-policy noeviction (REQUIRED). Under an evicting policy Valkey can drop part of a room (its admissions, the passed set, ticket ownership) while the room's main hash survives. Nothing detects that partial state, and a visitor whose admission was evicted is sent back to the queue or let through wrongly. With noeviction a full Valkey refuses writes instead, which the API answers as 503. At boot each process reads the policy from INFO memory (CONFIG is disabled on DO managed Valkey), logs a loud warning when it is not noeviction, and reports it as backend.maxmemoryPolicy and an incident on /api/admin/health (a share link sees the incident with the policy withheld, and no maxmemoryPolicy).
An inline room also decides what its own site's visitors get, with the room setting onBackendDown:
| Value | Browser navigation | API / XHR / fetch |
|---|---|---|
closed (default) | the room's waiting page in retry mode: 503 + Retry-After: 5, no place in line taken, a "temporarily unavailable" line, and the page reloads itself; the gate decides again on the reload | 503 storage_unavailable JSON, Retry-After: 5 |
open | forwarded to proxyOrigin as if the room were in bypass: no queue check, no cookie | forwarded the same way |
open lets the full surge through to the origin for as long as the backend is down, so choose it only for a site that would rather be slow than closed.
While Valkey is down the gate cannot read the room from it, so it uses the last config this process saw for that host (the inline host index, refreshed on every room change). A host this process has never seen as inline is not gated at all (it is routed as a non-inline request). A process that boots while Valkey is unreachable still starts (it logs valkey: unreachable at boot and keeps reconnecting; /healthz reports valkey: "down") and builds the inline host index from the room configs in Postgres (the rooms table, deleted rooms left out), logging inline host index built from Postgres, so onBackendDown applies to every inline room at once: a closed room's host answers the retry page, never a 404 or the origin. inline.indexFrom on /api/admin/health says postgres meanwhile; once Valkey answers, the rooms check replaces the index with Valkey's copy (valkey). If Postgres cannot be read either, the process logs Valkey and Postgres are both unreachable and gates nothing (its inline hosts answer 404) until one answers: the Postgres read is retried every 1 s, doubling up to 30 s. A WebSocket upgrade on an inline host follows the same setting while the backend is down: closed answers 503 with Retry-After: 5, open forwards the handshake to the origin. Only three kinds of connect error refuse to start, each named without printing the URL: credentials Valkey refuses (WRONGPASS, NOAUTH, NOPERM, ACL errors, an invalid password), a host name that does not resolve (ENOTFOUND), and a TLS certificate that does not verify. Every other connect error boots degraded and keeps reconnecting: refused, timed out or reset, the host or network down, a Valkey that is loading, has lost its master or asks to try again (LOADING, MASTERDOWN, TRYAGAIN), and any error this list does not recognise, such as ERR max number of clients reached or a TLS proxy that is only half up (EPROTO, ERR_SSL_*). An unrecognised one is logged once at boot as a WARNING naming its code or first words. A VALKEY_URL that points at a reachable address with nothing listening therefore boots degraded, so after every deploy alert on backend.valkeyEverConnected on /healthz: it is false until this process has reached Valkey once, and stays true after. It is reported only and never makes the instance unready. Each instance decides from its own last-seen config: a change to onBackendDown (or to the room) made on another instance just before the outage may not have reached this one, so for the length of the outage two instances can answer the same host differently. Before planned Valkey maintenance, make the onBackendDown change at least RESYNC_MS (default 5 s) ahead, so every instance holds the new value. After the first failure that means Valkey is unreachable, each process answers the backend-down reply at once for 5 s (while the connection is not back, or one request at a time probes a Valkey that timed out) instead of waiting for a command timeout per request. Counted per mode in qm_proxy_backend_down_total{mode} and in inline.backendDownOpenTotal / backendDownClosedTotal on /api/admin/health; one log line per room per minute.
Set it like any room field: POST /api/admin/rooms with {"id": "shop", "onBackendDown": "open"}; any other value is 400 invalid_on_backend_down. It is stored with STORE=memory too, where it has no effect: the in-process engine has no backend to lose.
When the site behind the queue is down
The opposite outage, and inline the more likely one: this server is healthy and proxyOrigin is not answering. Nothing needs to be wired up for it (the queue handles it), but you need to recognise it.
| queue down | site down | |
|---|---|---|
| Status | 503 (from your CDN rule) | 502 unreachable, 504 timed out |
| Header | none | X-QM-Origin: origin_unreachable|origin_timeout |
| Page | public/offline.html, served by the CDN | public/origin-down.html, served by this server |
| It says | entry is unavailable, you are not in a queue | you are through, the site is not answering |
| Chip | red: the queue system itself is failing | amber: hold on, your place is safe |
Neither page says paused. That word is the operator's: on the waiting page it means a person chose to hold the line, and a visitor who has seen both surfaces must be able to tell an outage from that choice.
A visitor who navigates gets the page; a background fetch() gets JSON with the same code, because a document handed to an XHR fails as if the app were buggy. Both carry X-QM-Origin, so one header answers "which side is broken" whatever shape the request was.
origin-down.html follows the same rules as the failover page: one file, no subresources, five languages, jittered retry (15 s → 60 s). It differs in one way that matters: it never suggests the visitor has lost their place, because they have not. A retry is a plain reload against a pass they still hold.
Where you will actually see it. The console does not make you go looking:
- The room card carries the line "Site not answering: N visitors got an error page" and its health chip flips to
site · failing. That chip outranks the probe, because a HEAD on/can succeed while every real page 502s. - The header incident badge leads with
⚠ origin down · <room>even when another room has a deeper queue. A snippet room's dead target hurts people who will be let through; a dead inline origin is hurting everyone already through it, and itswaitingcan honestly read 0 while the whole site is down. - Diagnostics adds two rows: Inline rooms (gated vs bypassed, with the ratio) and Origin errors (the total, broken down per room and per failure). Visitor disconnects are listed separately and never added to that total; a closed laptop is not the site failing.
The numbers behind all of it: inline.originErrorsTotal and inline.originErrors in GET /api/admin/health, and in /metrics:
| Series | Alert on |
|---|---|
qm_proxy_origin_errors_total{room,phase} | any sustained increase: the site behind that room is failing. connect = refused/unreachable, timeout = accepted and never answered, body_stall = answered and then died mid-response, upgrade = a WebSocket handshake failed. client_reset is the visitor's own socket and is excluded from the health total on purpose. |
qm_proxy_gated_total / qm_proxy_bypassed_total | a ratio far from ~1:40: the asset rule matches everything or nothing |
qm_proxy_inline_rooms | a drop you did not make |
qm_join_rate_limited_total | increase: visitors are being refused a place in line |
qm_challenge_total{result} | error_open increasing: the Turnstile challenge is admitting visitors it could not verify; error_closed increasing: it is turning them away. See Turnstile challenge |
qm_firewall_blocked_total{reason} | a sudden rise in allowlist or country on a room you did not just change: a rule is turning real visitors away (a wrong range, a country list that grew). See Room firewall |
qm_room_sold_out{room} | 1 while the shop still has units: the stock was set wrong, or units were never returned. See Stock control |
qm_stock_adjust_total{source,result} | unauthorized increasing: a shop with the wrong key; rejected increasing: a shop sending calls the room refuses (a delta with no stock set, a reused key) |
qm_stock_check_total{room,result} | failed increasing on the leader: the shop's stock check is not getting an answer (reason by trying Test the saved settings); stock_check_failing pages on it. See Stock check |
qm_release_total{result} | already or invalid rising with released flat: the shop is sending the wrong token (not the visitor's qm_<room> cookie) or calling for visitors still waiting; unauthorized: the wrong key |
qm_priority_redeem_total{result} | code_invalid or locked increasing fast: someone is guessing codes, or a code was posted somewhere public. See Priority codes |
qm_waiting_page_rate_limited_total | sustained increase: something is pulling the waiting page far faster than a browser would |
qm_open_connections / qm_max_connections | the first approaching the second |
qm_connections_refused_total | any increase: you are at the socket ceiling and shedding |
qm_process_resident_bytes | growth that does not level off |
qm_process_heap_used_bytes / _heap_total_bytes / _external_bytes / _array_buffers_bytes / _heap_size_limit_bytes | where the resident set goes (bytes, per instance): V8 heap in use and reserved, C++ and buffer memory (array_buffers is part of external), and the V8 heap limit V8 chose. RSS far above heap + external is allocator or kernel memory; heap_used near the limit is an out-of-memory risk. The lease holder's checkpoint pass shows as a spike in external and heap |
The card, the badge and the counters all say the same thing on purpose: the queue is up, the site is not, and nothing on the rate dial will help.
Stopping the server
A clean stop marks the process not-ready, stops accepting new connections, folds the open hour into the warehouse, hands the leader lease back (STORE=valkey), makes the events journal's last commit to Postgres (STORE=valkey), saves the timeline annotations and records server.stop in the audit trail. A kill does none of that: the hour in progress is lost, and with STORE=valkey the other instances wait for the lease to expire (LEADER_LEASE_MS) before one of them leads. With STORE=memory a stop of either kind loses the queue, the rooms and the operators: nothing is kept across a restart.
Idle and SSE connections get SHUTDOWN_GRACE_MS to finish, then are cut; SSE streams never end on their own. A socket carrying an inline proxied response is left alone at that point, since unlike SSE it does end on its own; it is only bound by SHUTDOWN_DRAIN_MS, the hard ceiling on the whole stop. An inline deployment with no SHUTDOWN_DRAIN_MS set defaults to a 15s floor instead of the plain 2s default, since 2s was measured truncating a real proxied download mid-transfer on every deploy, but an explicit SHUTDOWN_DRAIN_MS always wins, inline or not: it is never silently raised to the 15s floor.
The audit line says what happened: if the final checkpoint did not land (on STORE=valkey, an events-journal commit to Postgres that failed), it records shutdown … WITH STORAGE FAILING and says the changes since the last good commit are not in the events journal, rather than writing the word "clean" over a checkpoint that never happened.
| Platform | Clean stop |
|---|---|
| Linux / macOS, foreground | Ctrl-C, or kill <pid> (SIGTERM) |
| Linux / macOS, service | systemctl stop, docker stop (both send SIGTERM) |
| Windows | Ctrl-C in the console window, or the admin API below |
Windows has no other clean stop. taskkill /PID <pid> without /F answers This process can only be terminated forcefully (with /F option), and /F is a hard kill the handler never sees. So for anything not running in a console you have your hands on (a service wrapper, a scheduled task, a remote box), use:
curl -sX POST http://localhost:8080/api/admin/shutdown -H "Authorization: Bearer $ADMIN_KEY"
It answers {"ok":true,"stopping":true,"uptimeSec":N} and then exits through the same path SIGTERM takes. It needs the owner role (or ADMIN_KEY), the same bar as deleting a room, and deliberately out of reach of an operator key that runs the queue.
It stops the one process that answered. With several instances behind a load balancer that is whichever instance the request reached; the others keep serving. To stop a particular instance, send it to that instance's own address, or stop it through the platform.
With STORE=valkey a hard kill is still survivable: the line is in Valkey and every acknowledged join is in the Postgres journal, so no visitor loses their place. What is lost is the part of the current hour that had not been written yet.
Deploy, backup and recovery
Production runs STORE=valkey + SIDESTORE=pg (NODE_ENV=production refuses anything else), and no instance keeps anything on its own disk: the line is in Valkey, and everything that has to survive is in Postgres. The design (rolling deploys, Valkey and Postgres backups, RPO 1 s / RTO 5 min, capacity figures and how they were measured) is in docs/adr/0002-deploy-backup-recovery.md in the repository, as amended for step 5.
Deploy. The instances are interchangeable, so replace them one at a time behind the load balancer: start a new one, wait for its /healthz to answer 200, then stop an old one cleanly (see Stopping the server). Nobody loses their place. Each stop ends the streams on that instance, and the waiting pages reconnect to another (see Deploys under Several instances (STORE=valkey)). Two versions run side by side meanwhile, so every instance must serve every waiting-page asset hash still being handed out (see the next section). With SIDESTORE=pg the schema is migrated at boot. Deploy away from a scheduled drop.
Rollback. Deploy the previous version the same way. A rollback past the release that added kid to tokens re-queues every visitor who joined after the upgrade, because the older build cannot verify those tokens (see Rolling back across the token-signing change under Refusals).
Backup set.
| What | Why it matters |
|---|---|
Postgres (the database at DATABASE_URL) | The durable record. The events journal, open_orders and the room_snapshots checkpoints hold every room's queue: it is what a room is rebuilt from. The same database holds operators and monitor links, the audit trail, timeline notes, the 5 s metrics and the hourly history. Back it up with your provider's point-in-time recovery, or pg_dump. |
| Valkey | The live line. When Valkey loses or rolls back a room's state, the room is rebuilt from the Postgres journal (see When the backend is down), so a Valkey backup shortens a recovery but is not what makes one possible. Run it with maxmemory-policy noeviction. |
SECRET (and SECRET_PREVIOUS during a rotation) | Keep it in your secret manager, never in a data backup. Lose it and every ticket, monitor link, console session and operator key stops working at once. |
Restoring Postgres. Restore it together with an empty Valkey (or a new VALKEY_PREFIX): every room is then missing from Valkey, and each is rebuilt from the restored journal as it was at the restore point. Every join since that point is lost. Do not restore Postgres under a Valkey that still holds the newer state: a room that is further along in Valkey than in its journal reads as events not yet committed, and is not rebuilt. To check a backup before you need it, restore it into a new database and start a test instance on it with a VALKEY_PREFIX of its own, then compare waiting per room on /api/admin/rooms.
With STORE=memory there is nothing to back up: the server keeps nothing across a restart, and a deploy empties the queue, the rooms and the operators. That is why production refuses it.
What a backup cannot bring back. Turn-notification e-mail addresses (EMAIL_NOTIFY) are deleted when the ticket ends, or up to LAPSED_TTL_MS (24 h) later if its entry window lapsed. They are never written to Postgres. With STORE=memory every restart or deploy drops them all; with STORE=valkey they are in the shared Valkey until then. Valkey RDB snapshots and provider backups can hold a copy after deletion until they rotate out. Nothing in this build can export them, and it sends mail with them only when SMTP is set up (Notification e-mail). The ADR describes what production does instead.
DigitalOcean App Platform
Measured on 2026-09-29. A request reaches the container as: visitor → your Cloudflare zone → DigitalOcean's own Cloudflare edge → DO ingress → container. The container's socket peer is a DO ingress address in 100.64.0.0/10 (observed 100.127.x.x).
X-Forwarded-For as the container sees it: through your zone <client>, <client>, <your CF edge>; sent straight to the app's *.ondigitalocean.app domain <client>, <DO CF edge>. A value the client sends itself is kept on the left. So TRUST_PROXY=1 keys every visitor on a Cloudflare edge address, and TRUST_PROXY=2 with TRUST_PROXY_IPS=100.64.0.0/10 yields the real client through your zone but is forgeable by anyone calling the default DO domain directly. That domain cannot be turned off. On App Platform set EDGE_SECRET (the client address is then cf-connecting-ip, see Cloudflare edge secret) and leave TRUST_PROXY and TRUST_PROXY_IPS unset: with EDGE_SECRET set they are ignored and only produce a boot warning.
The Cloudflare rule. Rules → Overview → Create rule → Request Header Transform Rule; filter Hostname equals qm.weekday100.com; Set static header X-QM-Edge. Managed Transforms is a different page: do not enable its Remove visitor IP headers, which strips the header the server reads the client address from. /healthz stays answerable on the DO domain (EDGE_EXEMPT), so the platform health check works.
Managed databases. The app must be listed in the Postgres cluster's trusted sources (and Valkey's, if it has any). A missing rule shows as the boot refusal SIDESTORE=pg could not load side state from Postgres: ... connection timeout; the container exits non-zero and App Platform rolls back automatically to the previous deployment. The site keeps serving the old build, so check the deployment list, not only /healthz. A managed Valkey cluster with no trusted sources accepts connections from any address (password only): restrict it to the app(s).
Env drift: a stale settings page overwrites the env
On 2026-10-05, twice, a save from a DigitalOcean settings page that had been open for a while replaced the app's whole env with what that page had loaded: EMAIL_NOTIFY went back to 0, and the HOT_SNAPSHOT* keys were dropped. Nothing failed, so nobody noticed until somebody looked. Reload the settings page before every edit, and run the check after every save:
node tools/env-check.mjs # exit 0 clean, 1 drift, 2 error (doctl failed, manifest unreadable)
node tools/env-check.mjs --json # the same, machine-readable
node tools/env-check.mjs --strict # warnings (below) also exit 1
It reads the live app spec with doctl apps spec get (read-only; the app id is in the manifest, --app <id> overrides it) and compares it with ops/prod-env.json, the manifest of what production must hold:
- Drift (exit 1): a required key that is missing or empty; a non-secret key whose value differs from the manifest (shown as expected and actual, e.g.
EMAIL_NOTIFY: expected "1", actual "0"); a secret shorter than its (apps-s-1vcpu-1gb-fixedx 1, the idle size). Sizes: idleapps-s-1vcpu-1gb-fixedx 1; a sale or a load windowapps-s-2vcpu-4gb(window-env.mjs preparesets it for a window; for a sale runwindow-env.mjs restore --instances <n> --size apps-s-2vcpu-4gb --keep-key --apply, thenrestore --keep-key --applyafter it to go back to the idle size kept inwindow-env-backup.json). Expect this drift while a sale or a window runs. (apps-s-2vcpu-4gbx 1). - Warnings (exit 0): a key that is in neither the manifest nor the load-test list (add it to the manifest or remove it); a load-test key still set (
LOADTEST_KEY,HOT_SNAPSHOT,HOT_SNAPSHOT_ROOMS,HOT_SNAPSHOT_CHECK,SSE_MAX_TOTAL: allowed during a window, reported so they are not forgotten;tools/window-env.mjs restoreremoves them); an env set at service level, which overrides the app-level one.
Secrets are checked for presence only: the manifest holds no secret value (it refuses to load if one has a value), and the tool prints a secret key by name, never its value. Doctl error text is scrubbed of every value in the spec. When you add, rename or remove an env key on purpose, edit ops/prod-env.json in the same change.
The boot alert. Under NODE_ENV=production every instance compares its own environment with the manifest at boot (ops/prod-env.json ships with the code). On a missing required key, a changed non-secret value or a short SECRET it logs [server] warning: the app env differs from ops/prod-env.json: ... and the leader posts one env_drift alert (warning) to ALERT_WEBHOOK_URL, in the same payload as every other alert, at most once per boot. The message names keys and, for non-secret keys, expected and actual values; never a secret. It never blocks the boot: a save from a stale page therefore shows up at the deploy it triggers. Switches: ENV_CHECK=0 turns it off (for a staging app that is meant to differ), ENV_CHECK=1 turns it on outside production, ENV_MANIFEST=<path> names another manifest file. An unreadable manifest is a boot warning, not an alert.
Connection pool (pgbouncer)
The app works behind a DigitalOcean connection pool in Transaction mode. That is safe here because every lock is a transaction-scoped advisory lock (pg_advisory_xact_lock), the only session setting is SET LOCAL, and the app uses no LISTEN/NOTIFY and no named prepared statements.
The role's statement timeout is required. Direct connections send statement_timeout (10 s) when they connect. pgbouncer rejects that as an unknown startup parameter, so with PG_POOLER=1 the app leaves it out, and the database role must carry it instead. Without it a write the app gave up on after 12 s keeps running in Postgres and can still commit later, and blocked backends pile up toward the cluster's connection limit. So with PG_POOLER=1 the app checks SHOW statement_timeout at boot and refuses to start (SIDESTORE=pg could not load side state from Postgres: PG_POOLER=1 needs a server-side statement_timeout ...) unless it is greater than 0 and less than 12 s.
Set it up in this order:
- Create the pool. Databases → your cluster → Connection Pools → mode Transaction, database = the app database, user = the app user. Its size counts against the cluster's backend connection limit and is shared by every instance.
- Set the role timeout, once, as the admin user:
ALTER ROLE app_user SET statement_timeout = '10s';. It applies to new sessions only. - Reset the pool in the DigitalOcean panel so it opens new server connections. Restarting the app does not: the pool keeps its existing server connections, which still have the old value.
- Switch the app: set
PG_POOLER=1, and pointDATABASE_URLat the pool: port25061(the pool) instead of25060(direct), path = the pool name (for exampleqm-pool), keep theprivate-host, keepPG_CA_FILE.
Keep the schema public. Do not use ALTER ROLE ... SET search_path: the app takes the schema only from options=-c search_path=... in the URL (that is what it migrates), so migrations and queries would disagree. That URL option is itself a startup parameter, which pgbouncer rejects, so behind the pool the schema is public.
Connections per instance: each instance's pool holds up to 10 direct (N instances = 10×N against the cluster limit), or shares the pgbouncer pool.
Before a real drop
A checklist to run before a real sale or drop. Every line can be checked against the console, the API or the sections linked.
- Create the room. Set
id,tagOrigins(the pages that run the tag),returnOrigins,urlPatterns, and aratePerMinutethe protected site can absorb: an active room at 0 makesverifywarn "Outflow rate is zero" and nobody is promoted. SetqueueMaxPerIpon purpose: the default is 16 places per address, so raise it for an audience behind carrier NAT or an office (see Places per address). - Run
verifyfrom the connector, withQM_PUBLIC_API_KEYin the environment:queue-manager verify --server https://qm.weekday100.com --room <id> --url https://shop.example/checkout --strict. The Public API key travels only asAuthorization: Bearer;?key=is refused. Never give a connector theADMIN_KEY. A wrong--origin(or--url) is a FAIL, because that page's browser tag would fail open. - Confirm the edge. The Cloudflare Request Header Transform Rule sets
X-QM-Edgefor the queue hostname. The default*.ondigitalocean.appdomain answers403 edge_required(except/healthz)./healthzshows theversionyou expect.warningson/api/admin/healthis empty. - Confirm alerts reach the channel.
ALERT_WEBHOOK_URLis set (the boot log printsalert webhook enabled -> <host>). Runtools/alert-test.mjs(setup, wait,resume,cleanup; it needsADMIN_KEYand makes its own room): a paused room with people waiting pages asqueue_frozenafterALERT_FROZEN_SEC(default 300 s). No CPU or memory alert is configured on the app, so watch App Platform Insights and the database dashboards during the drop. - Capacity, as measured on 2026-09-29 (one run, not a guarantee). From one address: 869 waiting plus about 220 pollers (about 55 status requests per second) on one 0.5 GB instance took rss from 170 to 178 MB (about 9 KB per waiting visitor, polling rather than SSE), with p95 under 100 ms and no errors.
MAX_CONNECTIONSdefaults to 50000, far more sockets than 512 MB can hold with SSE, so measure SSE before trusting it. The tool istools/load-test.mjs: single address, joins stay underJOIN_LIMIT_PER_MIN. Many addresses and SSE at scale were not measured. - During the drop, do not deploy or restart. A push to
mainauto-deploys, and a deploy ends every open stream (pages reconnect by themselves; see live streams across a deploy). WithSTORE=memorya restart also drops every place. Watch the console and the alert channel. - If a room is left paused with people waiting, resume it or set a rate:
queue_frozenis the alert for it. If storage fails, writes answer503 storage_unavailablewithRetry-After; checkreadyon/healthzand/api/admin/health(see When the queue itself is down). - After the drop, delete the test rooms (deleting a room discards its line; it needs
ownerorADMIN_KEY) and record the numbers.
Waiting-page assets and live streams across a deploy
Waiting-page assets. The waiting page's style and main script are not inline. They are served at a content-hashed address, /assets/waiting-<hash>.css and /assets/waiting-<hash>.js, where <hash> is the first 22 characters of the base64url SHA-256 of the file. On an inline host they are under /__qm/assets/…. They are sent with Cache-Control: public, max-age=31536000, immutable, so a browser or CDN keeps each one for a year. A new build that changes public/waiting.html gets new hashes. A process serves only the hashes of its own build. An old hash is a 404, and a page that asked for it renders with no style and no script.
So the rule for more than one instance behind one address, and for a rolling deploy: every instance must serve every asset hash that any instance is still handing out. A page rendered by an old instance asks for old hashes, and the load balancer may send that request to a new instance. Ways to meet it:
- Deploy all instances at once (this build's stop-then-start deploy does this).
- Pin a visitor to one instance for the length of a page load (not possible behind a load balancer with no sticky sessions, such as DO App Platform's).
- Keep the previous build's asset files reachable, for example at a CDN or object store in front of
/assets/, until no old instance is left.
A CDN that already cached an old hash covers most requests, but a cold edge does not, so do not rely on it.
Visitor streams. An open waiting-page stream (/events) is ended by the server when the token it stands for is due to be re-signed (see TOKEN_MAX_AGE_SEC). The server first sends event: refresh with data {}, and the page reopens the stream itself. The new stream's response re-signs the place and re-sets the cookies. The due time is TOKEN_REFRESH_AFTER_MS after the token was issued: half the shorter of TOKEN_MAX_AGE_SEC and QUEUE_COOKIE_MAX_AGE_SEC. Each stream is ended up to 10% of that window later than the due time. The extra delay is fixed per place (a hash of the place), so a burst of joins that share one issue time does not reconnect all at once. A port must send the same frame and use the same rule. A deploy ends every stream, and pages reconnect by themselves.
The server also ends a visitor stream by itself in two cases (Notion 843). Right after a final frame: a status frame with expired, ejected, passed: true (a pass, a bypass, or a deleted room) or closed: true (the room closed under a waiting visitor). And at SSE_MAX_AGE_MS, after an event: refresh with data {}. A client, the shipped page or an integrator's EventSource on /api/v1/events, must stop on a final frame (close() the EventSource and act on the answer) and not reconnect: a browser EventSource reconnects on its own after any end, and the new stream would be answered with the same final frame at once. On refresh it reopens the stream. qm_sse_streams_ended_total{reason} counts both (and reason="far", below), and reason="peer" counts streams that closed under the server (the client, Cloudflare or the platform ingress) while still subscribed; a jump in peer with no matching server-side cause is a lead for the edge, not proof: it also counts our own destroys of a stream (a write error, a buffer over 1 MiB, a failed comment write) (Notion 849).
A visitor stream that has no frame yet (its first store read is slow or failed) is sent a : hb comment every 4 s and its first push is retried, at most 32 retries at once per instance (Notion 849). The page cannot see comments, and after 11-15 s without a status frame it polls /api/status; those polls now back off (after three, each gap is x1.5 up to 10 s, and a failed poll doubles it up to 15 s; never longer, because a poll is also what keeps the visitor present for presenceSec) until a stream frame arrives, so a silent stream does not become a synchronized polling load.
Far-back visitors poll instead of holding a stream (Notion 850). Three load windows (2026-11-13) showed an edge ceiling on concurrent visitor streams, about 285-300k fleet-wide whatever the instance count. Above it the edge closed the origin side of streams (qm_sse_streams_ended_total{reason="peer"} near 3k/s) while the pages stayed open and silent, then 120k pages polled at once and tripped Cloudflare's rate limit. A ticket is near, and streams as before, when its position is at most SSE_NEAR_POSITION, or its ETA is at most SSE_NEAR_SEC and its position at most SSE_NEAR_MAX_POSITION. The position ceiling matters: the ETA test alone grows with the drain rate (5 minutes at about 950 admissions/s is 285k places), so a room holds at most SSE_NEAR_MAX_POSITION streams. A plain waiting answer for any other ticket (/api/status, the join answer, an SSE frame) carries transport: "poll" and pollMs, the ETA / 10 clamped to SSE_FAR_POLL_MIN_SEC-SSE_FAR_POLL_MAX_SEC (20-120 s; the maximum with no ETA); every other answer carries neither, and an absent transport means stream. The page then opens no stream and asks /api/status every pollMs +-20% (twice that after a failed poll, at most 120 s; the page itself keeps the hint between 5 and 120 s). The first answer without poll makes it open the stream, so a far ticket that becomes near flips within one poll. A frame of a stream that is already open is judged with a wider test (2x SSE_NEAR_SEC, 1.25x both position limits), so a page hovering at the threshold is not ended and reopened. A page that opens /events?tr=1 (the shipped page does) has the stream ended by the server right after the far frame, with an SSE retry: as long as pollMs, counted as qm_sse_streams_ended_total{reason="far"}. A stream opened without tr=1 (a page cached from before this, an integrator's EventSource) is not ended: it sees the hint and keeps streaming, so it cannot loop on reconnects. Presence does not change the hint. In a room that judges presence (presenceSec and maxConcurrent) a holder unseen for presenceSec is promoted as a ghost (its pass owns no slot, and the door gives it one), but that is judged only at promotion, and a far ticket reaches the head through the near zone, where it streams. Only skipping the zone (an operator flush, a large rate or maxConcurrent raise) can promote a polling holder unseen, and the cost is a slotless pass, not the place. Far polls are the cheapest status path there is: with HOT_SNAPSHOT on they are answered from the room snapshot (the ticket's own record and its eject mark, no script), else by the status script as any poll. Budget: 350k far pollers at 60-120 s is 2.9k-5.8k requests/s fleet-wide (at 400k waiting and 64 load-generator IPs, about 45-90 requests/s per source IP; the DO edge blocked /api/status at about 90/s per IP in windows 26-27, Notion 854). SSE_FAR_POLL=0 turns the hint off.
Console stream. /api/admin/events sends a full stats frame on connect and again on the next 2 s tick. After that, a tick sends only a delta: {"delta":true,"rooms":[changed rooms],"removed":[ids],…} plus the same totals as a full frame. If rooms changed order (a room deleted and created again under the same id), that tick sends a full frame instead. A console that holds a delta with no full frame under it reconnects, and that is the resync. A deploy ends the stream, so the console gets a full frame again.
The stream also carries event: alive with {"ts":<ms>} every ADMIN_ALIVE_MS, written without reading the store. A stats frame needs a store read, and under load that read can take longer than the console's 10 s; the console then shows "not live" but keeps the stream while alive arrives. Only one read is in flight at a time. A console stream is held to 16 MiB of unsent data, not the 1 MiB a visitor stream is, before the server drops it.
How a pass is bound to a visitor
The pass token travels in the URL (?qm_token=), so it is written into every origin and CDN access log. Anything that treats "possession of the token" as "is the visitor" hands your queue to whoever reads those logs. Three layers stop that:
- Ticket ownership. A ticket is recorded against the client that queued for it. Presenting somebody else's token gets you a fresh ticket at the back of the line, never their place and never their pass.
- A browser-bound session cookie (
qms_<roomId>,HttpOnly,SameSite=Lax, first-party to this server, only its hash is stored). This is the ownership proof, in the same spirit as Queue-it's session cookie: it never appears in a URL or a log, it survives the visitor changing network, and the holder can use it to take their pass back from anyone who managed to claim it. - Client fingerprints for browsers that block cookies: a strict one (socket peer + forwarded identity +
User-Agent) and a second tier without the socket peer, so a CDN answering from a different edge node does not lock a visitor out of their own pass.
The second tier is built entirely out of request headers, and those headers (client address, User-Agent) sit on the same access-log line as the token. So it is only computed for a request that arrived from a proxy you named in TRUST_PROXY_IPS. Without that allowlist there is no way to tell a CDN edge node from an attacker replaying a log line, and the strict tier (which pins the socket peer, the one thing a sender cannot choose) is the only identity.
Consequences:
- A visitor who blocks cookies and changes network address mid-queue is treated as a new visitor and starts at the back, the same as a visitor who cleared their storage.
- On a deployment behind a CDN with
TRUST_PROXY_IPSunset, a cookie-blocking visitor whose requests move between edge nodes will have to rejoin. SetTRUST_PROXY_IPS(/api/admin/healthwarns you if you have not).
Why a visitor was refused: the [door] log line
A door check that answers bound_to_other_client says only that the request is not the client that holds the ticket. To see why (a visitor looping between a site and the waiting room), the server writes one line to stderr:
[door] bound_to_other_client {"room":"drop","ticket":17,"channel":"v1","ipFamily":"v4","netHash":"3f9a1c07be","uaHash":"a41d90e2c5","vouched":false,"sessionCookie":true,"doorKey":false,"claim":"absent","fp2":false,"viaProxy":true,"ownerRead":"ok","gate":"holder","owner":{"fp":true,"fp2":false,"sid":true,"sfp":false,"ip":"v4","net":"diff","ipEq":false,"fpEq":false,"fp2Eq":null},"adm":null}
channel:v1(/api/v1/check),api(/api/check) orinline(a proxied host).ipFamilyandnetHash:v4orv6, and a keyed hash of the request's /24 (IPv4) or /64 (IPv6). The address is never written, and the hash is keyed withSECRET, so it changes on a restart whenSECRETis unset. Two lines with the samenetHashcame from one network;uaHashdoes the same for theUser-Agent.sessionCookie/doorKey: whether the request presented theqms_<room>cookie, or a door key (?sess=,X-QM-Session,qm_dk_<room>). A refused request with neither is a client that dropped them (third-party cookie rules, a cross-site fetch); one with both is a different browser using the ticket.claim(QM-796): what the request'sX-QM-Claimheader amounted to, for the ticket being checked:absent(none sent),valid(signed by this server for this room and ticket and not yet 60 s old) orinvalid(anything else: wrong ticket or room, expired, tampered, too long, or sent by a vouched or inline caller, which never honours it). Avalidclaim skips the address test, so a refused request is normallyabsentorinvalid. The claim itself is never written.vouched,fp2,viaProxy: the request came from a connector's?ip=, a forwarded-identity fingerprint was computed, and a forwarded client address differed from the socket peer. If the same visitor showsfp2:trueon one channel andfp2:falseon the other, the two doors disagree about the proxy.
The second half of the line is the owner side (QM-794): what the ticket's owner record and admission record hold, compared with this request. It is read after the door has decided, without the answer waiting for it, so the line is written a moment after the response. Nothing about it changes what the door answers. Only booleans and the words below are written: a fingerprint, cookie hash, door key hash or address is compared and then dropped.
ownerRead:ok,none(no owner or admission record is left for the ticket, for example after a purge, an eject or a reset),errorortimeout(the store could not answer in 2 s; the line then has no owner half), orskipped(the request carried no ticket number).gate: which check refused, re-run on the records as they are now.holder: the ticket's owner is someone else (a differentqms_<room>cookie, a different fingerprint, or no fingerprint to compare against an owner that has a cookie).door: the door's own check (for a vouched caller, a different network or door fingerprint).session: the owner matches but the live admission was opened by another client.none: nothing refuses now, so the records changed since the refusal (the owner came back, or the session ended).owner.fp,owner.fp2,owner.sid: whether the owner record holds a fingerprint, a second-tier fingerprint, and a session cookie. An owner with nofpand nofp2is a ticket nobody can be compared with by fingerprint.owner.sfp: the first vouched (server-side) claim is on record.owner.fpEq,owner.fp2Eq: whether the request's fingerprint, and its second-tier one, equal the owner's.nullwhen either side has none. A refusal withfpEq:falseandfp2Eq:truecannot come from the fingerprint test (either tier matching is enough), so look atsidandgate.owner.ip: which address families the owner record holds:v4,v6,bothornone.owner.net: the owner's network against the request's, in the request's own family (/24 for IPv4, /64 for IPv6):same,diff, ornonewhen the owner has no address of that family (a v6 request to a v4-only owner).owner.ipEq: whether the whole address is the same (nullwhen either is missing); the door's last-resort check compares whole addresses.adm: the same for the live session's admission record, ornullwhen there is none:fp,fp2,sid,dk(opened with a door key),v(opened by a vouched caller), andfpEq,fp2Eq,ipEqagainst the request.
Reading it: sessionCookie:false with owner.sid:true and gate:holder is a client that lost its cookie but also fails the fingerprint (fpEq:false), for example IPv4 to IPv6 or a different proxy path; net:diff with fpEq:false is a different person; net:same and fpEq:false is a neighbour on the same NAT or a browser whose build or headers changed. adm showing dk:true and gate:session means the session is held by a browser with the door key.
At most one line per ticket per minute, and 30 a minute per instance (so at most 30 owner reads a minute). The token, door key, cookies and the full address are never logged.
The waiting-room claim (POST /api/claim, X-QM-Claim)
A visitor whose public address changes between the waiting page and the door (multi-WAN, VPN, hotspot) fails the address test at the door, because the queue cookie is not sent cross-origin. The waiting page therefore asks for a claim just before it returns the visitor, and the snippet presents it on the first check only.
POST /api/claimwith{"roomId":"…","token":"…"}, same origin only (no CORS headers on any answer, rate limited per address like/api/join).200 {"claim":"…"}only when the ticket has passed and the request'sqms_<room>cookie is the ticket's recorded holder (the same test that re-signs a token).400malformed body,401token not valid,403 not_holder,404unknown room or ticket (or a token for another room),409 not_passed,429.- The claim is stateless: nothing is stored. It is bound to the room and ticket and expires 60 seconds after it is issued. It travels in the return URL's fragment (
#qm_claim=), which is never sent to a server, and then as theX-QM-Claimheader on the first/api/checkor/api/v1/check(the header is in the CORS allow-headers list). The server never logs or echoes it. - A valid claim skips the address test for that check only. A session that is already open still needs its door key, so a replayed claim after the first admission is refused as
session_elsewhere. A token on its own (from a log or a Referer) behaves as before. - Server-side gates (QM-802). A gate that checks with the Public API key and
ip=&agent=(vouched) never sees the fragment. SetCLAIM_COOKIE_DOMAINto the parent domain the waiting room shares with the site andPOST /api/claimalso setsqm_claim_<room>(60 s,HttpOnly,Secure,SameSite=Lax,Domain=that value). The gate forwards its value asX-QM-Claimon the first/api/v1/checkand may delete the cookie after. A valid claim on a vouched check waives only the address tests (first use from another network, the reclaim window, the address recorded by the vouched session) and only while the ticket has no admission: once admitted, a claim, even a freshly minted one, opens nothing on the vouched channel (a holder can re-mint every 60 s, so honouring it would seat any number of riders on one admission, pastmaxConcurrent). Never the vouched-session rule (a direct caller with the claim is stillsession_elsewhere) or a contradicting queue cookie. On an inline (proxy) check it is stillinvalid. It does not follow an egress that moves after admission. The stock connectors (connectors/node/index.js,connectors/cloudflare/src/worker.js, the WordPress plugin'sincludes/class-qm-client.php) do not forward the cookie yet; only a custom gate does. The waiting page still appends#qm_claim=to the return URL, also for a server-side site, so the fragment is in the visitor's browser; the server-side check has used the cookie on the first request and, after admission, the fragment value is useless. The cookie adds that the claim reaches the server-side check at all, and it is never in a query string, log orReferer. Residual risk: theDomain=<parent>cookie is sent to every subdomain of that parent for 60 s, including ones hosted by a third party. Whoever presents a stolen claim together with a leaked?qm_token=before the owner's first check takes the first vouched admission, and the owner is thenbound_to_other_clientuntil the join reclaim. Bounded by the 60 s of the claim; it needs both credentials, and the cookie isHttpOnly. SetCLAIM_COOKIE_DOMAINonly if every host under that parent is yours. - To see whether it is working, look at the
claimfield of the[door]line above: a visitor who still loops withclaim:"absent"never got to send one (an older snippet, or the claim request failed);invalidpoints at an expired, mismatched or tampered claim.
What this stores, and what belongs in your privacy notice
Per ticket the server keeps a truncated SHA-256 digest of the client address, the socket peer, the forwarded chain and the User-Agent. The events journal in Postgres (STORE=valkey) additionally records the client address in the clear, on every join. That is all of it: no third-party cookie, no cross-site identifier, no profile, and nothing leaves your server.
It is still personal data under GDPR, because an IP address is, so it needs naming in your privacy notice, with your own counsel deciding the lawful basis and the retention period (which is however long you keep the Postgres events journal and its backups: the leader prunes a room's events below its oldest checkpoint once they are older than EVENTS_RETENTION_HOURS, but the rest of the journal stays, and so do backups). The purpose is narrow: the pass token travels in a URL and therefore lands in access logs, and this binding is the only thing stopping whoever reads one of those lines from taking the visitor's place. The customer-facing FAQ in the Integration guide links here.
Passes vs sessions
Two different clocks, per room:
| Field | Default | Meaning |
|---|---|---|
passedTtlSec | 600 | How long a promoted visitor has to walk through the door. Unused after that, the pass expires and they rejoin. |
sessionTtlSec | 1800 | How long they stay inside once admitted. Idle timeout: every /api/check slides it forward (Queue-it's extendCookieValidity). |
sessionMaxSec | null (4 h) | Hard ceiling on a single visit, however active, counted from walking in. null means 14400 s, or sessionTtlSec if that is longer; set a number to change it. |
All three are fields of the console's room Edit form (empty sessionMaxSec sends null) and of POST /api/admin/rooms.
A session holds exactly one maxConcurrent slot no matter how many times its token is replayed, and releases it when the visitor goes quiet for sessionTtlSec (or is ejected).
The claim window: a third clock, and the one that surprises people.
An unclaimed pass holds a maxConcurrent slot for 120 s (or passedTtlSec if that is shorter), not for the pass's whole life. Otherwise one visitor who was promoted and closed the tab would wedge a slot for the full ten minutes. Past the window the pass is still valid (its holder can still walk in) but it no longer counts against the ceiling, and its holder has to acquire a slot at the door like anybody else.
The clocks in order. Promotion issues the pass, an entry grant valid for passedTtlSec (600 s). For at most its first 120 s (the claim window: shorter if passedTtlSec is, and sooner still when the holder is absent, see presenceSec below) the unused pass holds a maxConcurrent slot. Walking in starts the session: every check slides it forward, and it ends after sessionTtlSec (1800 s) without one, or sessionMaxSec after walking in, whichever comes first. A pass still unused when the grant ends expires, and its holder rejoins; a session already running is not cut short by the grant ending.
The consequence looks alarming and is not:
A room with maxConcurrent: 5 can have ten people holding valid, unexpired passes. Five own slots; five gave theirs back. If all ten arrive, exactly five get in and five are turned away, and the ceiling is never breached. Bounced pass-holders are admitted strictly oldest-ticket-first as slots free, and keep their place while they keep polling.
Those five are real people and they are not in waiting: they already have a pass. The room card shows them under CAPACITY as +5 holding passes, and the API reports them per room:
| Field | Meaning |
|---|---|
occupancy | Slots in use: active sessions + passes still inside their claim window. |
passesOutstanding | Valid passes past the claim window, owning no slot. These people will be turned away if they arrive now. |
atDoor | The subset of them being turned away right now (knocking within the last 30 s). |
claimWindowSec | The window this room is actually using. |
occupancy is also what the waiting page tells every waiting visitor as "People inside now" (Notion 882; wire field peopleInside on the visitor status, the join answer and the SSE frames). It stands alone: the page never shows it against a capacity and maxConcurrent is never sent to a visitor. It is exact below 100 and rounded down to a ten from 100 up, so the churn of sessions ending does not make a new frame for every waiting stream. The console and /api/admin/rooms keep the exact occupancy.
passesOutstanding climbing while occupancy sits at the ceiling is the normal shape of a capacity-bound drop. passesOutstanding climbing while occupancy is below the ceiling means passes are being minted faster than they are being walked, usually promotion outpacing a slow target page. It also climbs when the line is full of ghosts, below.
Absent holders do not hold slots (presenceSec)
Without this rule, one client could freeze a room without ever looking at it. Measured on a room at 600/min with maxConcurrent: 5: one address sent 200 joins with no cookies and never polled. All 200 got a place; the next real visitor got position 201 and 15 seconds later was still at 196, with occupancy 5, active 0, every slot held by an unclaimed ghost pass for its 120 s claim window, five at a time. Sixty ghosts froze that room for about 24 minutes.
A pass reserves a slot only for a holder who is demonstrably there:
| Field | Default | Meaning |
|---|---|---|
presenceSec | 30 | How long a visitor may go unseen and still have a slot held for them. null switches the rule off for the room. With STORE=valkey, a room with maxConcurrent and presenceSec of 60 or more is judged against presenceSec + presenceSec / 3 instead (Notion 836: the last-seen stamp is written at most every presenceSec / 3), so an absent holder's slot is held up to a third longer than with STORE=memory, never shorter. Under 60 nothing changes. |
"Seen" means the visitor joined, polled /api/status, or is holding the /events stream (the waiting page does one of these every 5 s, so an open page is never judged absent). Two consequences:
- At their turn, a ticket whose holder has been unseen for
presenceSecis still promoted, in order (nobody loses their place), but its pass owns no slot and costs the room's rate nothing. It is exactly a pass past its claim window: if the holder comes back insidepassedTtlSecthey are through, and take a slot at the door, oldest ticket first, like any other bounced pass-holder. A phone that was locked while the line moved loses nothing but the reservation. - After promotion, a pass whose holder was never told they are through (no status call since) gives its slot back once they have been unseen for
presenceSec, instead of holding it for the whole claim window. A visitor who was told keeps the slot for the full window, because they are now on their way to your page and there is nothing left to watch.
The same 200-ghost room lets the real visitor through about presenceSec after the burst; the ghosts' passes show up in passesOutstanding, not in occupancy. A restart treats every ticket as seen at boot (presence is not persisted), so a crash can cost nobody a slot and can give a ghost at most one more presenceSec. Shortening the claim window for everybody was the rejected alternative: it bounces real visitors on every slow target page and still lets a burst of fresh ghosts hold every slot for the shorter window.
Two origin lists, and why they are not one (returnOrigins, tagOrigins)
They are two fields because one list would let a single edit decide two things that fail in opposite directions:
| Field | Answers | Getting it wrong |
|---|---|---|
returnOrigins | Where a promoted visitor may be sent | An open redirect on your own domain that hands out pass tokens. Loud, security-owned, kept tight. |
tagOrigins | Which pages may read a door check (the browser CORS allowlist) | That page is served completely unqueued, silently: the browser discards an answer with no Access-Control-Allow-Origin, the snippet fails open, and the room still looks healthy here. |
The room's own targetUrl origin is always on both. tagOrigins defaults to null, which means "use returnOrigins". Every room configured before the split behaves exactly as it did, and you only set it when the two genuinely differ (a tag on a marketing domain that visitors are never returned to, or a narrow return policy that must not widen just to unblock an install).
Set them independently:
curl -X POST http://localhost:8080/api/v1/admin/rooms \
-H "Authorization: Bearer $ADMIN_KEY" -H 'Content-Type: application/json' \
-d '{"id":"checkout",
"returnOrigins":["https://www.shop.example"],
"tagOrigins":["https://www.shop.example","https://landing.brand.example"]}'
Refusals of the second kind are counted per (room, origin) and shown in Diagnostics and in qm_refused_origin_checks_total. Non-zero means a page carrying your tag is live and unprotected right now. The console's install verifier asks about the origin as well as the URL, and its one-click fix writes tagOrigins only; unblocking a tag is not a decision to widen where visitors may be redirected.
Where a visitor is allowed to land (returnOrigins)
A promoted visitor is sent back to the page they came from, which reaches the waiting room as a qm_return URL, an attacker-supplied string. The server refuses every return URL not covered by the room's policy:
- the origin of the room's own
targetUrl, always; plus - any origin listed in the room's
returnOrigins:https://shop.example, orhttps://*.shop.exampleto cover subdomains. The dot in the wildcard is required, so the pattern never matchesevilshop.example, and the scheme and port must match too.
Relative URLs, non-http(s) schemes and URLs carrying embedded credentials (https://user:pass@…) are refused outright. A refused return is not an error for the visitor; they simply land on the room's target instead, so this fails quietly by design. It is counted, and Diagnostics shows the tally as blocked return URLs.
Watch that counter. A missing return origin looks exactly like an attack: if checkout lives on https://shop.example but the room's target is https://www.shop.example, every real visitor is silently dropped on the wrong page. Non-zero means either you have a domain to add, or somebody is trying to use your waiting room as an open redirect.
Scheduled drops
A room can be given a doors-open instant. Before it there is no line at all: arrivals go into a pre-queue and get an opaque handle instead of a ticket number, and at the open instant the whole pre-queue is shuffled with a crypto-grade random draw and becomes the FIFO line.
curl -X POST http://localhost:8080/api/v1/admin/rooms/drop/schedule \
-H "Authorization: Bearer $ADMIN_KEY" -H 'Content-Type: application/json' \
-d '{"opensAt":"2026-09-01T09:00:00Z","preQueueMaxPerIp":16}'
| Field | Meaning |
|---|---|
opensAt | null (no schedule: doors are open), epoch milliseconds, or an ISO datetime. |
preQueueMaxPerIp | Entries one identity may hold in the pre-queue. Default 16; null for unlimited. |
Each field is applied only if you send it. Adjusting the cap mid-drop (-d '{"preQueueMaxPerIp":4}') changes the cap and leaves the drop scheduled. Cancelling a drop takes an explicit {"opensAt": null}, so a routine tweak can never silently throw the doors open on a queue that was waiting for a draw. Cancelling does not discard anyone: every visitor holding a pre-queue entry is drawn in random order at once and queued ahead of anyone who joins later. The console's room form clears the time through POST /api/admin/rooms (opensAt: null), and that, removing a branding.opensAt that was the only schedule, or saving a time already past (the instant the room last opened for counts only when a pre-queue has collected since, after a re-arm), does exactly the same. A save that leaves a future schedule in place draws nothing. A body with neither field is refused (400 nothing_to_change) rather than accepted as a no-op.
Why it works this way:
- Arriving early buys nothing. Clicking the moment the link is published and clicking a minute before the drop draw from the same hat. That is the entire point: a FIFO line that opens hours early just moves the stampede to whenever you published the link.
- The draw is round-robin across identities. The second entry one identity holds is drawn strictly behind the first entry of every other identity, so extra entries can never crowd out first-time arrivals.
preQueueMaxPerIpis a fairness floor, not an anti-fraud control. A whole office or a CGNAT block shares one address, which is why the default is generous. Raise it if your audience sits behind carrier-grade NAT; lowering it punishes shared addresses long before it inconveniences a determined attacker.- The permutation is recorded, not recomputed. A restart across the open instant replays the order that was drawn instead of drawing a second one.
While the doors are shut, POST /api/join answers state:"scheduled", preQueued:true, a preCount, and opensAt/now so the page can count down against the server's clock. position and ahead are null, because neither exists yet.
Note the two views of a scheduled room. GET /api/admin/rooms reports the room's configured state (active, paused, bypass) alongside opensAt and a preQueue count; the visitor wire reports the effective state, scheduled, until the doors open. The dashboard composes the two into a SCHEDULED badge, an "opens …" time, and an in pre-queue counter in place of waiting.
The operator console
The dashboard at / is where an operator lives during an incident. Everything on it is live (a stats frame arrives every 2 s over SSE) and every control applies immediately. There is no save step.
Per room
| Control | What it does |
|---|---|
Active / Paused / Bypass | active queues normally; paused freezes automatic outflow and holds everyone's place; bypass switches the queue off and lets everyone through. Pausing states its consequence before you confirm. |
| Rate slider / number | ratePerMinute, the smooth per-second outflow. Applies on the next slice, not the next minute. |
Let through n | Promote n visitors now, on top of the rate, including on a paused room, which is the one way anybody gets in while paused. Deliberate: releasing a few people during a pause is a normal operator action. It releases the front of the line in ticket order; there is no way to pick a particular visitor. The confirm says which of the two applies. |
Autotune | Drives the rate from the target site's measured response time instead of your guess; the gear opens its bounds. |
Install | The script tag for this room, ready to paste. For a room with a proxyOrigin it shows the inline deployment checklist instead: where DNS points, the internal address, the reserved /__qm prefix and the failover rule. An inline room is never shown a snippet; there is no page to paste one into. Rooms deployed inline also carry an inline chip on the card. |
Waiting page | Opens /w/<room>: exactly what a visitor sees. |
Empty queue | Discards the entire waiting backlog without admitting anybody, for a room that has outlived its event. Nobody is promoted, so the chart gains no spike that never happened; purged tickets read as expired and have to join again. A scheduled room's pre-queue is part of the backlog and is emptied too: those visitors are told their pre-queue entry closed and join again. The room, its settings and its history are kept. Irreversible, and the confirm says so. |
Edit / Delete | Room settings (target URL, TTLs, branding, tagOrigins, returnOrigins, schedule) and removal. |
Reading a room card
CAPACITYalways has a denominator.12/25is twelve of twenty-five slots in use;0/∞is a room with no concurrency ceiling at all. (A bare0under the word CAPACITY, beside a neighbour reading25/25, says the opposite of what it means.) The number counts live sessions on the protected site plus passes issued inside the claim window and not yet used; see Passes vs sessions.EST. WAITis compact and never truncated:40s,3m,1h20m, and past ten hours just109h, because at that point the minutes are not information. A leading≥means the figure is a lower bound, not an estimate: the room is at its ceiling and nothing has come out for a minute, so raising the rate will not help. Hover it for which case you are in.∞under EST. WAIT is a room letting nobody through (paused, or active at 0/min) with people still in it. It is waiting ÷ 0 at the room's current setting, not a forecast: it goes finite the moment you resume or raise the rate, and the tooltip says which of the two it is waiting on. The visitor's own page words the same gap as "no estimate", because a visitor cannot act on the rate and "unbounded" would be a promise about their future; you can, so the card shows you the arithmetic. The state itself is on the badge, once.- The header's WORST EST. WAIT leaves those
∞rooms out, and says so. The top-line number is the worst wait across the rooms that are moving, so one paused room cannot pin the whole estate at∞. Whenever a room with people in it is letting nobody through, the line under the number readsexcludes 3 at ∞: the header and a card reading∞are then both right, and the header is telling you which rooms it is not counting. When every room with a queue is stopped the number itself is∞and the line reads3 not admitting. - A scheduled room counts down. Under the room name,
Doors open in 4m 12s · 12:13 PM, amber inside the last five minutes. The line forms before then: visitors can join and hold a place, it just does not move.
Across rooms
- Chart: queue depth, joins/min and passes/min, plus two wait lines that are deliberately not the same number: est. wait is computed (depth ÷ measured outflow) while actual wait p50/p90 are measured server-side from real join→pass durations. When they disagree, believe the measured one.
- The rate scale can split. Normally joins/min and passes/min share one amber
/minscale inside the left axis, because the gap between the two lines is the rate the queue is growing at. When one is several times the other (a surge at 1,000 joins/min against 20 passes/min) the smaller line would be pressed flat onto the axis, and passes/min is the line you steer by: nudging the dial from 20 to 30 would move it a fraction of a pixel. Past a 4× ratio each line gets its own scale, its ticks printed inside the left axis in its own colour (amber for joins, green for passes), and both legend entries change from(rate scale)to(own scale). While it says own scale, the lines crossing does not mean the numbers crossed; hover for both figures. It reverts on its own once the two are comparable again. - Events: vertical marks for everything that changed the room: rate moves, state flips, threshold activation, autotune, flushes, purges, ejects and protection blocks. Hover one for the note and its clock time; marks landing on the same pixel are collapsed and the tooltip lists all of them. Toggle the series off in the legend when a busy timeline gets in the way.
- Export CSV: the full retained history (1 h), percentiles included.
- URL targeting: the rules deciding which pages this room protects, each with how many door checks it has matched (checks, not people: one visitor makes many, and the server's own health probe is not counted) and when it last matched. Change them in
Edit; they take effect on the next check, with no deploy. A rule reading never matched during a live sale is the visible symptom of a room pointed at the wrong pages. The box below it is a dry run: paste a URL, see which rule would win, before you save anything. Warnings appear here when a rule names an origin the room will not return visitors to, and when checks are arriving with no page URL at all (an integration older than qm.js 1.2.0, which cannot be scoped and is therefore queued as if unscoped). - Visitor drill-down: look up either a ticket number or the
Refcode the visitor is reading off their own waiting page: state, position, time waited, which clock is running (pass expires in before they enter the site, session expires in once they are on it), whether they are on the site right now, and whether the ticket is bound to a client. The waiting page shows both the ref and the raw ticket number, so whichever one the caller reads out is one you can paste. (A ref is a short digest, so a very large room can produce a collision; the lookup then lists the candidate tickets instead of guessing.)Ejectrevokes the pass, drops any live session and sends them to the back of the line. It is a two-step confirm; the arming survives the 2 s refresh, and is dropped if you look up somebody else.
state is one of:
| State | Meaning |
|---|---|
waiting | In the line. position and est. wait are theirs. |
passed | Holds a pass that would get them in right now, or is already on the site (on site, with the session clock). |
holding | Shown as holding pass. A valid pass that gave its slot back (claim window lapsed) while the room is full: turned away at the door until a slot frees, oldest ticket first. These are the room card's holding passes. pass expires in is still running; door position appears while they are actually knocking. Not expired, and Eject voids the pass. |
expired | The engine is finished with the ticket: the pass has expired and no session is live (or the line was emptied before their turn). They have to join again. |
ejected | An operator ejected them. |
prequeued | A PQ- ref: in a scheduled room's pre-queue, before the draw. After the draw the same PQ- ref opens the ticket it was drawn into, marked drawn from pre-queue (same room generation only). |
unknown | That ticket number was never issued in this room. There is no position or wait to report. |
A ref also names the room generation it was issued in. Deleting a room and creating it again under the same id restarts ticket numbers at 1, so a ref read out by a caller from before the reset is not resolved to whoever holds that number today: the lookup says which ticket of which earlier generation it was (previous_generation), and that the caller has to join again. The last 3 generations are checked, over their first 50,000 tickets.
The wait field is labelled by tense. waiting is a number still climbing: time since they joined the line. waited is the finished journey, frozen at the instant they were promoted; it does not grow while you read it, so a ticket you look up an hour after the incident still answers how long did this caller wait? with the wait, not the hour. For a room with opensAt, the clock starts when the visitor joined the pre-queue, not when the doors opened; the hour they spent holding is real waiting and every number here says so, including the Actual wait series on the chart and the percentiles in Reports. joined is that instant. passed is when they were let through; it stays after the pass itself expires. A session admitted by an older version has no record of it once the pass expires, and shows passed: unknown rather than a guess.
After a reclaim (the holder takes their session back from a second tab or device), passed and waited still read the original promotion, not the re-grant the reclaim issues.
When the engine has finished with the ticket (the pass has expired and no session is live), state becomes expired, and joined, passed and waited are kept. That covers a visitor who was promoted and never came in, too. The last 50,000 finished tickets per room are kept, oldest dropped first. An eject forgets them straight away.
- Share monitor: a read-only link for stakeholders. It carries a scoped viewer token, not
ADMIN_KEY, so it can observe but never change. The console asks the server what the signed-in credential may do and hides every mutating control accordingly, so the read-only view survives the#monitorfragment being lost in a paste, and a namedviewerkey gets the same treatment. The header names which credential you are signed in with.
Share monitor shows a live read-only link, never minting on open (Mint a new link creates one), in a selectable field: copy it from there, or with the button beside it. Minting a second link never revokes the first, so the dialog says so and offers the existing link first. Copy on a row in the list below puts an existing link back in front of you rather than creating another, so the number of live links stays the number of people who are meant to have one. It is audited as monitor_token.reveal, separately from monitor_token.mint, because who else was sent this is a different question from who made it. A revoked or expired link cannot be re-copied: that would be a way to resurrect exactly the credential somebody just took back. Links expire on their own after MONITOR_TOKEN_TTL_SEC (seven days by default); revoking one is separate and takes effect immediately. Revoking an operator closes every link that operator shared (see Operators, roles and the audit trail).
- Alerts: desktop notifications for surge start, target-URL failure and stalled outflow.
- Diagnostics: the health report described above.
Where the controls live. The header bar holds only what you reach for while a queue is moving: Alerts, Share monitor, Security, Diagnostics, and + New room. Everything you set up between incidents is one click away under Console: Reports, Access, Docs and Sign out. The menu is drawn over the page rather than in it, so opening it never moves a button you were aiming at. On a read-only credential the bar and the menu both shrink to what that credential can actually read, which for a shared monitor link is Security and Reports.
The console never stores ADMIN_KEY: signing in trades it once for an HttpOnly qm_console session cookie (POST /api/admin/session, see the QM-349 note above), and Sign out (under Console) sends DELETE /api/admin/session, which clears the cookie and revokes the session server-side.
Running it from the keyboard
A busy console is well over a hundred tab stops, and a room card is about eighteen of them, so reaching the sixth room by tabbing is not a real option.
- Skip links. The first
Tabon the page offers Skip to rooms and Skip to chart. They are off-screen until focused. - Skip past a room. The first stop inside every room card is Skip past name to the next room, so moving down the list costs one
Enterper room instead of eighteen tabs. The last card's skip goes to the chart. The target is worked out when you press it, so it follows the live card order. - The rate dial.
←/→move it by 10/min,PageUp/PageDownby 50/min, andShift+←/→by 1/min. The number box beside it is still the way to type an exact figure. (The underlying step is 1, so a rate the server sends is always shown exactly; only the keys move in jumps.) - The Console menu.
Enteror↓opens it,↑/↓move through it and wrap,Home/Endjump to the ends,Escapecloses it and puts focus back on the button.Tableaves and closes it rather than cycling inside. - Dialogs return you where you were. Closing a dialog (by
Escape,Close, or clicking outside) puts focus back on the control that opened it, including a confirm opened from inside a panel: the firstEscapereturns to the control in the panel, the second to the button that opened the panel. If the room a dialog belonged to has been deleted meanwhile, focus lands on that room's card heading, or on the room list, never on nothing.
Campaign theme
A room can carry its campaign's look on the pages visitors see: a logo, a colour set, and campaign copy and links in Thai and English. One room is one campaign. The theme lives in the room's branding object, next to message, so it needs no migration, and a room without it renders exactly as before.
Edit it in the room's Edit dialog, under Campaign theme (below the visitor message), or with POST /api/admin/rooms (also /api/v1/admin/rooms). Both need the operator role or above, and both are recorded in the audit log. Viewers and monitor links cannot change it. The console sends branding only when something in it changed. A POST replaces the whole branding object, so an API caller sends every branding key it wants to keep, message included.
| Field | What it is | Rule |
|---|---|---|
branding.logoUrl | The logo, centred above the card on the waiting page | An https:// URL, or a path on this server starting with a single /. http://, //host and /\host are refused. A logo that fails to load leaves the initial-letter mark in the card. A logo address saved before this rule existed is kept stored while it is unchanged, but the page shows it only if it is an https: address or a path starting with a single /; an http://, //host, javascript: or credential-bearing (https://user:pass@host) logo is not shown. |
branding.homeUrl | Where the Back to home button on the room's default full page goes (the default full page only; the default closed page has no button) | An https:// URL with no username or password; a path, http:// and javascript: are refused. Empty or absent: the full page has no button. A value saved before this rule that is not https: is kept stored but the page does not show the button. |
branding.myOrderUrl | Where the My order button goes: on the waiting page while the room is sold out (stock 0; it opens in a new tab so the visitor keeps their place) and on the default full and closed pages (same tab) | An https:// URL with no username or password; a path, http:// and javascript: are refused. Empty or absent: no button. A value saved before this rule that is not https: is kept stored but the page does not show the button. |
branding.color | Primary: buttons, the position number, progress | #RRGGBB when bg is set. |
branding.bg | Page background. Setting it turns the theme on. | #RRGGBB |
branding.card | Card surface. Optional: derived from bg when absent. | #RRGGBB. Needs bg. |
branding.copy.th, branding.copy.en | headline, description, passMessage (shown at the visitor's turn), footer, inside (the whole sentence of the "people inside now" line) | At most 80, 300, 200, 200 and 80 characters. Strings only. th and en are the only language keys. |
branding.links | Up to 4 links under the card | Each { "th": "…", "en": "…", "url": "https://…" }. Labels are at most 30 characters, with at least one of th/en. url must be https: with no username or password; javascript:, data:, http: and relative URLs are refused. |
A value that breaks a rule answers 400 invalid_branding with a message naming the field, for example branding.links[0].url must be an https:// URL. The whole branding object stays within 8 KiB; full bilingual copy is about 3 KiB. Copy is plain text: <b> is stored and shown as the three characters <b>.
inside (Notion 884) words the "people inside now" line of the waiting page (see occupancy above) as a full sentence, for example {n} people are on the buying page right now. {n} is replaced by the number the page shows (rounded as described there); a text without {n} gets the number added after a space. Empty or absent keeps the built-in line. Thai and English visitors use their language's text, else the other one (the rule of the other copy fields); Spanish, German and French visitors always see their built-in line.
{
"id": "weekday-100",
"branding": {
"name": "Weekday 100",
"logoUrl": "https://cdn.example.com/weekday-100/logo.png",
"color": "#E4002B",
"bg": "#FFF4E0",
"copy": {
"th": { "headline": "ลด 100 บาท ทุกวันธรรมดา", "footer": "เงื่อนไขเป็นไปตามที่บริษัทกำหนด" },
"en": { "headline": "100 baht off every weekday", "footer": "Terms and conditions apply." }
},
"links": [{ "th": "กติกา", "en": "Terms", "url": "https://www.example.com/weekday-100/terms" }]
}
}
What visitors see.
- The queue status stays the page's main content. The headline (plain text, not a heading) and the description sit under the brand row; the status headline stays the
h1and is the first heading on the page. At the turn,passMessageappears under "You're in!", above the continue button. Under the card come the links, then the footer text, then the language picker. - Every state uses the theme: queued, at the turn, the scheduled countdown, paused and closed. The no-JavaScript page is unchanged.
- Language follows the page's usual order:
?lang=, the visitor's saved choice, the room'slang, the browser. A field left empty in that language shows the other one. Spanish, German and French readers get the English copy, then the Thai. - A themed room has one fixed colour scheme, so the Light/Dark/System picker is hidden.
- Colours: you set two or three, and the page derives the rest. Text is black or white, whichever reads better. Secondary text is mixed toward its surface only as far as 4.5:1 allows. If the primary colour does not reach 4.5:1 as text on the card, the page darkens it (light card) or lightens it (dark card) in small steps until it does. The console shows the colour it will use.
- Links open in a new tab with
rel="noopener noreferrer"and no Referer, and onlyhttps:links are drawn: the page checks again. The logo is also loaded with no Referer, because the waiting page's address can carry a visitor's token. - The theme travels in the page's inline config. A change reaches a visitor on their next page load, not live. The visitor message stays live.
Privacy. The logo's host sees the IP address of every visitor who loads the page. Use a host you trust. Uploading the logo into the queue, which removes this, is a separate task.
The origin-down page. For inline rooms, this is the page a visitor who is already through the queue sees when the site behind it does not answer. It uses the room's colours, logo, footer and links. It does not use the headline, description or turn message: that page has to say plainly that the site is failing. It shows the logo only from an https:// host other than the site's own, because a request to the site's own host would go through the gate to the site that is down. offline.html is served by the CDN with no room data and is not themed.
Preview. The group's preview is the real waiting page at /w-preview in a frame, fed the unsaved form by the console. Pick the state (queued, at turn, countdown, paused) and the language above it. It shows made-up numbers, joins no queue and makes no API call. /w-preview is a console surface: it answers only where the console does (ADMIN_HOST), only the console's own origin may frame it (frame-ancestors 'self'), and it accepts messages only from that origin.
Copy theme from room fills the group from another room's theme. Nothing is saved until Save.
Hiding waiting-page elements
An operator can switch four elements of the waiting page off for one room. All four are shown by default, in every existing room and every new one: a room with nothing stored is read and written exactly as before.
| Name | What it hides |
|---|---|
opensHint | The line under the headline while a scheduled drop's countdown runs ("Doors open at 12:00. Your place is drawn at random…", and the count of people already waiting). The countdown stays. |
message | The staff message box. The stored branding.message text and its time are kept, so switching it back on shows it again. While hidden the text is not sent to visitors at all (not in the page, not in the status frame). |
notify | The "Notify me when it is my turn" button (and its explanation line). |
email | The e-mail notify button and its form. |
- Where. The room's
branding.hide: an array holding any of those four names, no duplicates. Absent or[]shows all four. Anything else (an unknown name, a repeat, a non-array) is400 invalid_branding. Set it withPOST /api/admin/roomslike the rest ofbranding, or in the room's Edit dialog, in the four Show … boxes under the visitor message (an unticked box is a name inhide; leaving them alone sends nobrandingat all).branding: nullclears it with the rest of the branding. - Live. A change reaches visitors who are already waiting inside one heartbeat, on the same status frame as the message: no reload.
- Hide only.
emailcan hide the e-mail button; it never shows it. Whether the button can appear at all is still the server'sEMAIL_NOTIFY. This hides the interface only: the e-mail endpoint is untouched and still accepts an address from anyone who posts one, and a visitor's address already stored stays stored. Likewisenotifyhides the button, not the browser notification code behind it. - Spoken text. The pre-queue announcement a screen reader hears when it is first shown follows
opensHint: shown, it says when the doors open, that the place is drawn at random and how many are waiting; hidden, it says only when the doors open ("The doors open at …").
Metrics and monitoring
| Endpoint | Format | Auth |
|---|---|---|
GET /metrics | Prometheus text exposition | ADMIN_KEY |
GET /api/v1/admin/metrics?roomId=&range= | JSON time series for charts | ADMIN_KEY |
GET /api/admin/health | JSON health, config and warnings (incl. absolute startedAt) | ADMIN_KEY |
POST /api/admin/shutdown | Clean stop of the instance that answers; the only one Windows has off-console | owner / ADMIN_KEY |
GET /healthz | Readiness: 200 while ready, 503 when storage is failing (STORE=memory; on STORE=valkey only when this instance fails while another is ok), the process is draining, or this instance is at MAX_CONNECTIONS | none |
GET /api/version | The same payload, always 200 | none |
/metrics is not public: it answers 401 without the key, because room ids and live queue depths are commercially sensitive. Give Prometheus a bearer token:
scrape_configs:
- job_name: queue-manager
metrics_path: /metrics # inline, on the public hostname: /__qm/metrics
authorization: { type: Bearer, credentials: "<ADMIN_KEY>" }
static_configs: [{ targets: ["qm.weekday100.com"] }]
metrics_path is spelled out because Prometheus defaults it to /metrics, and on the public hostname of an inline room that path belongs to the customer's site: the visitor gate answers the scrape 503 and the job goes up=0 while the server is perfectly healthy. A scrape target is a host and port with no room for a prefix, so the path is the only place to say it; see the probe table under Readiness. Scraping the process directly (pod IP, container port) needs no change.
Per-room series are labelled {room="…"}: qm_room_waiting, qm_room_active_sessions, qm_room_pending_entry, qm_room_at_door, qm_room_occupancy, qm_room_max_concurrent, qm_room_rate_per_minute, qm_room_passed_last_minute, qm_room_oldest_wait_seconds, qm_room_state, qm_room_stock_remaining (-1 with no stock) and qm_room_sold_out (Notion 745; qm_stock_adjust_total{source,result} counts the stock calls); qm_stock_check_enabled{room} and qm_stock_check_total{room,result} (Notion 878, per instance, counted on the leader only; see Stock check). The visitor fan-out (Notion 747): qm_sse_status_calls_total (store reads made to push a frame; divide its rate by qm_sse_subscribers{kind="visitor"} for reads per stream per second), qm_sse_frames_total{kind=changed|keepalive|resend}, qm_sse_heartbeats_total and qm_sse_swept_total (Notion 849, 771), qm_sse_streams_ended_total{reason=terminal|age|peer}, qm_sse_frames_skipped_total{reason=governed|unchanged|duplicate|held}, qm_sse_fanout_passes_total and qm_sse_fanout_requests_total{result=...}. Streams below the room head (Notion 826): qm_sse_below_head_frames_total{outcome} (frames computed for a stream whose ticket is below the head) and the gauge qm_sse_below_head_streams{outcome} (open streams whose last computed frame was below it); outcome is passed, at_door (bounced at the door), expired, bound (bound_to_other_client) or other. Needs the frame governor on (its room view gives the head). The room snapshot (Notion 748, only with HOT_SNAPSHOT on): qm_snapshot_requests_total{kind=status|sse,path=fast|fallback,reason=…} (the hit ratio is fast ÷ (fast + fallback); near_front and below_head are normal, stale, cold, fence, invalid and breaker mean the snapshot was not usable), qm_snapshot_age_ms (a histogram of the snapshot's age when it answered) with qm_snapshot_age_max_ms and qm_snapshot_age_max_seen_ms, qm_snapshot_refresh_total{result=ok|error|stale_drop|invalid}, qm_snapshot_fresh_total{result=current|refreshed|null} (what the SSE pass got when it asked for a snapshot: current was already there, refreshed was taken for the call, which includes a call that only waited on another refresh already in flight, and null means the pass view was read directly from Valkey, three reads; in a room whose changes arrive faster than a refresh takes this should be near zero), qm_snapshot_valkey_calls_total{kind=status|sse|refresh} (Valkey commands made for those answers; divide by the requests of the same kind for commands per status or frame), qm_snapshot_hot_rooms, qm_presence_flush_entries_total, qm_presence_skipped_total and qm_presence_flush_calls_total{result=ok|error}. The waiting page's re-join (Notion 773) adds kind="join" to both qm_snapshot_requests_total (reasons as for status, plus holder, ejected, gen and the bind_* reasons: the script had something to write or decide) and qm_snapshot_valkey_calls_total. The bind_* reasons (Notion 774) name the first field the join script would have rewritten for the stored holder, in this order: bind_sid (the record has no sid and no fingerprint, so it would take the caller's sid), bind_fp (the strict fingerprint differs and the second tier does not: the socket peer, the forwarded chain or a forwarded-identity header changed between the page's two requests, the user-agent and client address did not), bind_fp2 (only the second tier differs, or one side has none), bind_fp_fp2 (both differ: another user-agent or client address), bind_ip (the recorded address differs), bind_net (same address, but the stored family or network key differs) and bind_live (the ticket's live-per-address entry is not this address's). Earlier releases counted all of these as bind. Only the first applicable field is counted, so bind_fp also hides an address change that came with it. A re-join whose strict fingerprint is the only difference is answered from the snapshot (path="fast") without rewriting it, and counted in qm_snapshot_join_fp_refresh_total as well (a subset of the fast answers), when the session cookie proves the caller, the stored and the request's second tier are both set and equal, and nothing else would change (sid, address, family, network key, live-per-address entry). The stored fp then keeps its old value until the next join script run for that ticket; a status poll does not write it. No later answer changes: the strict fingerprint is made of the client address, the user-agent and the peer and forwarded headers, and the second tier of the first two, so a request that matches the stale value matches the second tier too. bind_fp therefore counts only the fp-only joins that stayed with the script: no second tier on either side, no sid on the stored record, or the address or a stored key differing as well. The door fast case (Notion 718, HOT_SNAPSHOT_CHECK=1) adds kind="check" to qm_snapshot_requests_total (reasons: no_session is every new admission and normal, token, gen, not_passed and bound are the visitor's own state; rules is one retry after a rules change; short_session is a room whose idle limit is under the bound above; fence, drawing, open_due, cfg, breaker, error and missing mean the room or Valkey was not in a state to prove anything; ejected, session_over, rekey and fill are the script's cases) and to qm_snapshot_valkey_calls_total (the atomic read plus one script per fallback: commands per check), and the buffers' own series qm_check_touch_flush_entries_total, qm_check_touch_flush_applied_total, qm_check_touch_flush_calls_total{result=ok|error}, qm_check_targeting_flush_entries_total and qm_check_targeting_flush_calls_total{result=ok|error|dropped}. Valkey cost per check is INFO commandstats usec ÷ checks (tools/bench/analyze.mjs); the local bench measured the fast case at 4.4× cheaper than the script (docs/bench/2026-10-05-phase2b-check.md). HTTP requests (Notion 755), per instance, every pair always present (zero until used): qm_http_requests_total{route,class}. route is one of a fixed set, never a raw path, room id or query: w (the waiting page, /w/…), join, status, check, events (the visitor stream; /events and /api/events), notify, redeem, admin (/api/admin/*, the admin stream included), metrics (/metrics), health (/healthz, /api/health, /api/version), static (snippet, connectors, assets, docs, console pages), proxy (traffic for a customer's host on an inline room), misc_api (/api/targeting, /api/verify, /api/verify.gif, /api/connectors, /api/stock/…, the Mandrill webhook) and other (anything else, 404s included). /api/v1/* and the /__qm prefix are the same routes as without. class is 2xx, 3xx, 4xx or 5xx of the final status, counted once when the response completes; aborted is a request whose connection ended before its response did (no status exists to class it). An event stream is counted once, when it opens (2xx), and not again when it closes. Not counted: requests Node itself refuses as malformed, and WebSocket upgrades. A path the router normalises (dot segments, % escapes) counts as other. 5xx per second = sum(rate(qm_http_requests_total{class="5xx"}[1m])) across instances. qm_event_loop_lag_ms{quantile="0.5|0.99|max"} is the event-loop delay in ms (10 ms sampling, an idle loop reads about 0) over the last completed 10 s window; it is rolled on a timer, not on scrape, so any number of scrapers see the same window. Alert on max or 0.99 staying high (the process is not keeping up). Valkey scripts (Notion 770), per instance, STORE=valkey only: qm_valkey_script_calls_total{script}, qm_valkey_script_seconds_total{script} and qm_valkey_script_errors_total{script}. script is the name of a file in lib/valkey/ (a fixed list, one series per script from boot, zero until used); every script call the server makes goes through one function, so the sum over script is the server's EVALSHA count (FCALL with Valkey Functions, Notion 848). Seconds are measured on the server's side of the wire, from the call to the reply, so they include the time a command waited behind others at a busy Valkey and the network, not only the script's own run time (which INFO commandstats gives, for all scripts together); calls that failed are in calls and seconds as well as errors. Average ms per call = rate(seconds_total) / rate(calls_total) * 1000; calls per join = rate(qm_valkey_script_calls_total{script="join"}) / rate(joins). Only scripts are counted: the plain commands (SET, HGET, PUBLISH, pipelines) are issued from many call sites with no single place to count them, and INFO commandstats already gives them by kind. Valkey main-thread time per script (Notion 844), STORE=valkey, off with QM_LUA_COST=0: qm_valkey_lua_server_seconds_total{script} and qm_valkey_lua_server_calls_total{script}. INFO commandstats lumps every script into evalsha (fcall with Valkey Functions, Notion 848), and qm_valkey_script_seconds_total above includes the network and the wait behind other commands; these are the time the script itself held Valkey's one thread, read inside Valkey (Lua os.clock(), the process's CPU time, read at the start and end of the script body on a random 1 call in QM_LUA_COST, scaled up: an estimate, close for scripts called more than a few times a second, noisy for a rare one). They come from the hash <VALKEY_PREFIX>stat:luacost (fields <script>:us and <script>:n), which every instance's scripts add to: the series are fleet-wide and every instance exports the same values, so take one instance's, never sum() across instances. Share of the Valkey's script time = max by (script) (rate(qm_valkey_lua_server_seconds_total{script="join"}[5m])) / scalar(sum(max by (script) (rate(qm_valkey_lua_server_seconds_total[5m])))) (max by (script) keeps one copy of the fleet-wide series); INFO commandstats evalsha usec is the total to compare with (it also holds the few microseconds each script spends on the measurement). Because the clock is the process's CPU time, a Valkey running more than one busy thread (io-threads above 1) adds the other threads' CPU to the scripts running at that moment: if the scripts' total share in summary.txt comes out well above 100%, that is why, and the per-script ratios are then only a rough guide. On a shared vCPU, CPU steal works the other way: CPU time reads below the wall-clock evalsha usec, so a total share under 100% is not by itself missing scripts. The counters only grow; they start again from zero when the hash is lost (a Valkey restart without persistence, eviction) or someone deletes <prefix>stat:luacost (rate() handles that; DEL is also how to reset them by hand). A script that fails with a Lua error is not timed. tools/capture-window.mjs reads the hash each sample (valkey.lua in samples.jsonl: us/s, calls/s, us per call and share_pct of the evalsha us/s of the same sample, top 8) and prints the biggest scripts with their share in summary.txt. Not for a Valkey Cluster: the key is not in the script's declared keys (nor are other keys the scripts derive). Checkpoints (Notion 810), STORE=valkey with recovery on only: qm_checkpoint_state_bytes{room} (gauge: the size in bytes of the last checkpoint row this instance wrote for the room) and qm_checkpoint_passes_total{room} (counter: rows this instance wrote since it started) and qm_checkpoint_last_duration_seconds{room} (gauge: the wall time of the last pass for the room, journal reads + fold + Postgres write, not CPU). Only the instance that holds the ckpt:lease exports them; an instance that lost the lease stops exporting at its next pass. A room whose bytes keep growing: see A checkpoint that is too big. qm_checkpoint_skipped_total{room,reason="heap"} (Notion 853, counter: passes not started because the room's last checkpoint would not fit the free heap, counted since this instance took the lease) is exported by the lease holder like the others; rising means that room's checkpoint is no longer refreshed, see the same section. Process-wide: qm_rooms, qm_sse_subscribers, qm_uptime_seconds, qm_shutting_down, and the counters to alert on: qm_storage_write_errors_total, qm_unknown_room_checks_total, qm_blocked_return_urls_total, qm_refused_key_checks_all_total, qm_rate_limited_checks_all_total and qm_rejected_tokens_all_total.
Several instances (STORE=valkey). Every series also carries instance="<QM_INSTANCE_ID>", and each instance reports only its own process: its own counters, connections and SSE streams (the room gauges read the shared Valkey, so every instance reports the same queue). Scrape each instance and sum in Prometheus. Prometheus sets an instance target label of its own, so with the default honor_labels: false this one arrives as exported_instance; set honor_labels: true on the job to keep the server's name. With honor_labels: true the name must be unique per scrape target: give each instance its own QM_INSTANCE_ID, or leave it unset (i:<random> is new on each boot). Two targets that report the same name write the same series, and Prometheus drops or mixes their samples. Where the platform exposes one address for the whole fleet (DO App Platform), a scrape reaches whichever instance the load balancer picks. The console is the fleet view there: each instance writes its origin-error, protection and diagnostic counters to Valkey every 5 s (<prefix>ctr:<id>, expiring after 15 s), and the console's room cards and GET /api/admin/health show the sum over the live instances. A stopped instance's share drops out of that sum within 15 s. Health's fleet: {instances, partial} says how many instances the sum covers, and partial: true when the other instances' counters could not be read from Valkey (the sum is then this instance's own, plus what it last read within 15 s). Connection and SSE counts in health stay this instance's own, beside its own limits.
Alert on the rate of qm_rejected_tokens_all_total. A trickle of refused tickets is stale bookmarks; a step change means everyone in a room was ejected at once, which is what a regenerated signing key or a moved clock does. It is the one failure with no other symptom anywhere. Those visitors are not shown an error; they are quietly put at the back of the line.
The one alert you should not skip is storage: a server that cannot append to its event log must stop handing out tickets, and it does (503 storage_unavailable), but you want to hear about it before your visitors do.
Observing a fleet behind one address
/metrics also carries qm_instance_info, always 1, naming the process that answered:
qm_instance_info{instance_id="web:3f9c0a1b2c3d4e5f",version="0.1.7",leader="true",instance="web"} 1
instance_id is the per-boot id (<QM_INSTANCE_ID or i>:<random>, also on STORE=memory), so it tells instances apart even when they share a QM_INSTANCE_ID; a new value means that instance restarted. leader is whether it runs the fleet-wide jobs: exactly one instance should say true. qm_process_start_time_seconds is beside it. The id is a name you chose plus random hex: it names no host, address or secret, and /metrics still needs the same credential as before.
Where the platform gives the fleet one address (DO App Platform), a single scrape cannot see all of it. tools/fleet-metrics.mjs asks /metrics over and over, on a new connection each time so the load balancer picks again, until it has seen every instance, then prints one row per instance and the fleet totals.
Point it at the app's ingress URL (https://<app>.ondigitalocean.app), not the public hostname. Through Cloudflare the tool cannot choose the instance: Cloudflare keeps its own pooled connections to the origin, so a new connection from the tool often reaches the same instance again, and the count comes out low. With EDGE_SECRET set on the app, the ingress URL answers 403 unless the request carries X-QM-Edge. The tool sends the first entry of EDGE_SECRET, taken from the environment or from the app spec.
QM_DO_APP=<app id> node tools/fleet-metrics.mjs https://<app>.ondigitalocean.app
ADMIN_KEY=… EDGE_SECRET=… node tools/fleet-metrics.mjs https://<app>.ondigitalocean.app --expect 3 --watch 10
3 instance(s) seen in 3 request(s)
instance version leader rssMB conns sse sat shed refused jErr joinRL checkRL badTok gated edgeRef
i:d964a63e4a376f49 0.1.7 yes 93 2 0 0 0 0 0 0 0 1 0 0
…
FLEET 1 279 6 0 0 0 0 0 0 0 7 0 0
- How many to expect.
--expect Nkeeps asking until N instances are seen. WithQM_DO_APPset and no--expect, N is the count fromdoctl apps list-instances. If--samples N(default 60) requests run out first, aWARNING: saw X of N expected instancesline says so. With neither, the tool stops after--stableanswers in a row (default 10) bring no new instance, and printscount unverified. A failed request (an error, a timeout, a connection cut mid-answer, or a200with noqm_instance_info) counts as failed and is never taken as "nothing new". - Credentials.
ADMIN_KEYandEDGE_SECRETcome from the environment, or from the app spec viadoctlwhenQM_DO_APPis set. Neither is ever printed. A base path is kept:https://host/qmaskshttps://host/qm/metrics. - Columns.
sseis every open stream: visitors and console (admin) streams.sat/shed/refusedare the connection ceiling,jErrthe journal write errors,joinRL/checkRLthe rate limiters,badTokrefused tickets,gatedinline requests checked, andedgeRefrequests without the edge header. Room gauges are left out: every instance reports the same shared rooms. A secondWARNINGmeans the instances seen did not report exactly one leader. --watch <secs>repeats, and shows each counter's change and rate since that instance was last seen (--rounds Nstops after N rounds). During a load test or a drop, run it besidetools/load-test.mjsto see whether one instance saturates (sat,shed) while the others idle.
Alerting (paging someone who is not looking at the dashboard)
The console's Alerts button raises desktop notifications in that tab. That is useful while somebody is watching and worthless at 3 a.m.: it dies with the tab and exists once per operator laptop.
Everything below runs inside the queue process. When the process is down, wedged or unreachable, nothing here fires: no webhook, no resolved, nothing in the panel. The only thing that pages you then is an external monitor on /healthz (see Readiness); set one up, because it is the only alert that survives the failure it reports.
The conditions below are evaluated on the server's own clock every ALERT_EVERY_MS whether or not a webhook is configured, and whatever is firing is listed under Diagnostics → Alerting → Firing now either way. With nothing configured that panel is the alerting: the conditions are real and nobody is being paged for them, which the panel says in as many words. Several of them (queue_frozen, outflow_stalled) depend on hold times no dashboard replicates, so this is the only place they appear. With several instances the leader reads the rooms each frame and leaves the figures in Valkey (<prefix>alerts:stats); the other instances' frames take that copy, so what a non-leader lists under Firing now can be older than the leader's by up to twice ALERT_EVERY_MS (the copy's lifetime), and longer while no instance leads, until a frame finds the copy gone and reads the rooms itself. The leader's own frame, which pages, always reads the rooms.
Set ALERT_WEBHOOK_URL and the server also POSTs JSON:
{
"source": "queue-manager",
"event": "outflow_stalled",
"status": "firing",
"severity": "critical",
"roomId": "shop",
"message": "Shop: 412 waiting and nobody let through in the last minute",
"ts": 1730000000000,
"since": 1729999880000,
"text": "[queue-manager] CRITICAL: Shop: 412 waiting and nobody let through in the last minute"
}
text is there so a Slack incoming webhook renders something readable with no transform; the structured fields are for PagerDuty Events v2, Opsgenie and anything else that parses. Events:
event | Severity | Fires when |
|---|---|---|
storage_failing | critical | The event log cannot be written, so joins are being refused. On STORE=valkey this is events-journal commits to Postgres failing in two alert frames within 3 × ALERT_EVERY_MS (one failed commit does not page), until a later commit has landed and that window has passed since the newest failure. With several instances the message names the instance(s) whose storage is failing. |
valkey_unreachable | critical | With STORE=valkey: this instance has not reached Valkey for VALKEY_ALERT_AFTER_MS. Sent by each such instance itself, not by the leader. |
target_down | critical | The server's own probe stops reaching a room's target site. |
outflow_stalled | critical | People are waiting and nobody has been let through for ALERT_STALL_SEC. The room is trying and failing. |
queue_frozen | critical | People are waiting and the room is paused or set to 0/min for ALERT_FROZEN_SEC (the forgotten paused room). The room is not trying, because a human said so and may not have come back. |
stock_check_failing | warning | A room's stock check has failed continuously for STOCK_CHECK_FAIL_SEC (and then ALERT_HOLD_SEC). The line keeps its last state (held or released) until the shop answers again; resolves on the next accepted answer. The message names the room, never the URL. |
queue_deep | warning | Depth at or above ALERT_DEPTH (off by default). |
wait_high | warning | Estimated wait at or above ALERT_WAIT_SEC. |
Every condition must hold for ALERT_HOLD_SEC before it fires, re-pages every ALERT_REPEAT_SEC while it is still true, and sends a "status": "resolved" event when it clears. An alert channel that never says "it is over" is one operators learn to ignore.
With STORE=valkey and several instances, every instance evaluates the conditions, so Firing now and GET /api/admin/alerts are the same on any of them, and only the leader (see LEADER_LEASE_MS) POSTs to the webhook. The state that decides a delivery (when a condition started, when it was paged, when it was last re-paged) is kept in Valkey (<prefix>alerts:state), so when the leader dies mid-incident the next one neither pages the open incident again nor forgets to send its resolved. Do not delete <prefix>leader:epoch by hand: the stored state is fenced on it, so if <prefix>alerts:state survives, the epoch restarts below the one saved with that state and every later save of the alert state is refused until the epoch passes the stored one again (or <prefix>alerts:state is deleted too). If you must reset the epoch, delete both keys together (an alert that is still firing is then paged again). Storage is each instance's own: every instance reports its storage status to Valkey (<prefix>alerts:storage) each frame, the leader pages storage_failing when any instance reported failing within the last 3 × ALERT_EVERY_MS and names it (instance on /api/admin/health is each instance's name), and resolves it only once every instance reports healthy. While Valkey is unreachable nothing is delivered except valkey_unreachable, which each instance that cannot reach Valkey sends itself after VALKEY_ALERT_AFTER_MS (so expect one page per instance); an external monitor on /healthz is still the alert that survives the queue itself failing. The delivery log, sent and failed are the answering instance's own: the leader's list is the one with the deliveries in it.
ts is when this page was decided and since when the condition began, which a firing and its resolved share. A resolve can reach the webhook before its firing while the firing is still in flight (ALERT_EVERY_MS below the 5 s webhook timeout, or a receiver that accepts late), so order pages by ts and pair them by event, roomId and since.
GET /api/admin/alerts reports the configuration, what is firing and the last 20 deliveries with their HTTP results. POST /api/admin/alerts (write grant) fires a test event; the console does this from Diagnostics → Alerting → Send test alert, which is the only way to know the path works before you need it. The button is always in that panel: with no ALERT_WEBHOOK_URL set it is there but inert, and says so, rather than not existing at all for the one reader who is following these instructions because nothing is configured yet. It is disabled, saying why, for a credential without the write grant (a share link or a named viewer key), which the server would answer with 403.
Durability
With STORE=valkey the durable record is the events journal in Postgres. Valkey holds the live line, and a room whose Valkey state is lost or rolled back is rebuilt from the journal (see When the backend is down). With STORE=memory nothing is written anywhere: every wait below is met at once, a restart starts empty, and the 503 answers below cannot happen.
- Joins are acknowledged only after the join event is committed to the journal. A failed commit makes
/api/joinanswer503 storage_unavailablerather than hand out a signed ticket nothing recorded, and the ticket (or pre-queue entry) it minted is taken back: it does not stay in the line, does not count againstqueueMaxPerIp/preQueueMaxPerIp, and does not come back in a rebuild. - The same holds for everything else a restart must not take back (QM-390): the pre-queue draw, an eject, a purge and a room's definition.
/api/statusand/eventsanswer only once the draw they reveal is committed, and eject, purge, room create/update/delete, schedule and flush answer200only once their event is. If the commit fails they answer503 storage_unavailable(/eventsholds the frame instead). Retrying an eject or purge is safe. When nothing is pending the check costs one map lookup. - Admissions at the door are held to the same rule (QM-431).
/api/check(direct and vouched) answers apassthat admits somebody only once the room's admissions are committed, and the inline gate forwards the page or the WebSocket upgrade only then. If the commit fails the answer is503 storage_unavailable(a refused upgrade inline), and the admission is taken back: the pass is pending again with the slot and claim window it had, so the retry is admitted on a fresh door key instead of being toldsession_elsewhere. The snippet and the connectors fail open on that503, as on any 5xx. The wait is per room and separate from the one/api/statusand/eventsuse, so they never wait on the door. - A refused join or admission can still come back as an orphan if the process dies before its compensating event is committed, or that commit fails too. An orphaned ticket lapses like a closed tab: it counts against
queueMaxPerIpuntil it reaches the head of the line, is promoted without a capacity slot once its holder has been unseen forpresenceSec, and expires with its pass. An orphaned pre-queue entry counts againstpreQueueMaxPerIpuntil the open and is then drawn into such a ticket. An orphaned admission holds a slot until the session idles out, and its visitor, whose door key it does not know, is toldsession_elsewhereand rejoins unless their queue cookie reclaims it. - Ticket ownership, admissions and ejections are all in the journal, so a
kill -9cannot turn a leaked token into a free ride. GET /api/admin/healthexposesstorage.ok,storage.writeErrors(onSTORE=valkey, the journal commits that failed) and the last error; alert on it, or on thestorage_failingalert.- Checkpoints keep a rebuild short. One instance at a time folds each busy room's journal into a
room_snapshotsrow, so a rebuild replays the latest checkpoint and the events after it instead of the room's whole life. A checkpoint is read from Postgres only, never from Valkey, so it always agrees with the journal. - The journal is bounded. The leader deletes each room's events below its oldest kept checkpoint once older than
EVENTS_RETENTION_HOURS, and a deleted room's events below its delete, in batches (EVENTS_PRUNE_*). The oldest kept checkpoint, not the newest: a rebuild that read Postgres before the newest one was written can still make it unusable, and recovery then falls back to the older one. Deleted rows free space for reuse inside Postgres (autovacuum); the table file does not shrink on disk. Each batch looks at the first rows of a room's journal only and stops at the first young one, so a run never rescans what the retention still keeps. The prune records how far it cut a room (rooms.pruned_below), and a rebuild refuses to write itsrebuiltmarker when that would leave a pruned room with no usable checkpoint (the rebuild is retried from the newer checkpoint). - A room fenced with
pruned_no_checkpoint. The prune cut that room's journal and the room has no usable checkpoint (itsroom_snapshotsrows were lost or truncated, for example by a restore of the table from an old backup), so it cannot be rebuilt: it stays fenced, and the log saysrecovery pruned_no_checkpoint <room>: ...once a minute (retrying with a backoff up to 5 minutes). The checkpoint job cannot repair it, as it folds from the same journal. Restore the room'sroom_snapshotsrows, or itseventsrows below the prune point (rooms.pruned_below), from a backup of the same database; the next retry then rebuilds it. - Before deploying the build that adds migration
006_events_rebuilt_idxto a largeeventstable, create its index by hand, so the migration finds it and does nothing. The migration runs in one transaction at boot and cannot useCONCURRENTLY; without the index, the boot would hold a lock that blocks the journal's writes for as long as the build takes (minutes at tens of millions of rows). As the admin user, on the same database and schema (SET search_pathfirst, if it is notpublic):CREATE INDEX CONCURRENTLY IF NOT EXISTS events_rebuilt ON events (room, seq) WHERE type = 'rebuilt';
The index holds only the rare rebuilt markers, so it is tiny, but every usable-checkpoint lookup (the prune, the checkpoint job, a rebuild) needs it: without it each lookup scans the room's whole journal and the prune cannot finish inside the 10 s statement timeout. Migration 007_rooms_pruned_below adds a column with a constant default: instant.
- The journal is guarded per event against a rollback: a rebuild that meets an event type this build does not know, or an event stamped with a newer format (
lv, absent means 1), fails instead of skipping it, and the room stays fenced until a build that can read it runs the rebuild. For whoever changes the format: a new kind of event gets a new type; changing what an existing type means stamps those events with the nextlv(EVENT_LOG_VERSIONinlib/engine.js). - The hourly history is one row per room and hour in Postgres. The leader rewrites the open hour on every sample, and rows older than
HISTORY_RETAIN_DAYSare deleted. A warehouse that cannot be read at boot is logged ([history]) and refuses the boot rather than start on empty state and overwrite it.
Valkey Functions (Notion 848)
With STORE=valkey every script in lib/valkey/ is loaded at boot as one Valkey Function library and called with FCALL; the shared helpers (_lib.lua) are built once at load instead of on every call. The loader is lib/valkey.js (buildLibrary); EVALSHA stays as the fallback.
- Version. The library is named
qm_<16 hex>, the first 16 hex of a SHA-256 over the whole library source (every script, the helpers they reach, theQM_LUA_COSTwrapper); each function isqm_<16 hex>_<script>. Function names are server-wide in Valkey, so the hash is also what keeps two builds apart. The same sources always give the same name. - Rolling deploy. Each instance uses its own library name only, so an old and a new instance work side by side, each with the code it was built with, and never call a mismatched function. At boot an instance first asks
FUNCTION LIST LIBRARYNAME <its name>; the library of the same build is already there once any instance has loaded it, so a rolling deploy of 50 instances compiles the 220 KB (7 to 11 ms of Valkey main-thread time) once, not 50 times. Only a missing library is loaded, withFUNCTION LOAD REPLACEof that name (instances of one build that load at the same moment replace each other's identical copy: harmless). The server never deletes any other library: instances still draining need theirs. - Fallback, per instance. Valkey unreachable at boot: the load is tried again on the first call (path
pendingin/metricsuntil it is resolved).FUNCTION LOADrefused for any other reason (an ACL without theFUNCTIONcommand, a managed Valkey that blocks it, a server older than 7.0, a library that does not compile): one log linevalkey: FUNCTION LOAD not usable (<why>); scripts run through EVALSHAand that instance usesEVALSHAuntil it restarts. So is anFCALLthat is refused after a good load (an ACL withoutFCALL, a renamed command:NOPERM/unknown command): a probeFCALLright after the load finds it at boot, and the same reply to a real call (nothing ran) switches toEVALSHAand answers that call. A load that times out is tried again on the next call, 3 attempts in all, thenEVALSHAuntil restart. A library that has gone missing (FUNCTION FLUSH, a Valkey that lost its data; functions normally survive a restart in the RDB/AOF) is loaded again once, however many calls meet it, and the call that found it missing is repeated (nothing ran). If it is gone again straight after, or the reload is refused, the instance falls back as above. - Memory. One library is about 220 KB of source (the Lua compiled in Valkey is a few times that). Each deploy that changes a script or
_lib.lualeaves its library behind; nothing prunes them. Clean up by hand after a deploy has fully rolled over (below). - Refused up front (OOM, MISCONF, NOREPLICAS). A function without flags is refused before it runs when Valkey is over
maxmemorywithnoeviction(OOM), when a background save is failing withstop-writes-on-bgsave-error(MISCONF), or with fewer replicas thanmin-replicas-to-write(NOREPLICAS);EVALrefuses only at its first write, so a pure read still answered. Such a reply fromFCALLis repeated throughEVALSHAfor that call: nothing ran, andEVALSHAdecides as before. The path staysfcall. - The switch.
VALKEY_FUNCTIONS=0(alsooff,false,no) goes back toEVALSHAfor the whole instance without a code change. Use it to compare costs or if a Valkey misbehaves with functions. - Observing.
qm_valkey_script_path{path="fcall"|"evalsha"|"pending"}(1 on the active path).qm_valkey_function_librariesandqm_valkey_function_memory_bytesare the libraries on the Valkey (every build's, from oneINFO memoryper scrape) and the memory they hold: a count that keeps rising is old builds nobody deleted. InINFO commandstatsthe calls arecmdstat_fcallinstead ofcmdstat_evalsha;tools/capture-window.mjs,tools/bench/vkcost.mjs,tools/bench/lua-micro.mjsandtools/bench/join-open-loop.mjsadd them together and still call the sumevalsha.qm_valkey_lua_server_seconds_total{script}and the other per-script series (844, 770) are unchanged: the script names are the same. TheQM_LUA_COSTsample goes to the same hash<VALKEY_PREFIX>stat:luacost; with functions the key is sent as one extra trailingKEYthat the function removes before the script runs (so the script sees exactly its ownKEYS, andFCALLdeclares the key it writes). - Inspect.
qm_valkey_script_library_info{library="qm_<hex>"} 1names the library an instance uses (only while the path isfcall). On the Valkey:FUNCTION LIST(LIBRARYNAME qm_<hex>for one,WITHCODEfor the source),FUNCTION STATS,INFO memory(used_memory_vm_functions,used_memory_functions). - Clean up (ops step, by hand). Only after every instance of the old builds is gone (a deploy finished, no instance of the previous version left): list them with
FUNCTION LIST, andFUNCTION DELETE qm_<hex>each one that no running instance reports inqm_valkey_script_library_info. An instance whose library was deleted under it reloads it on the next call (above), so a mistake costs one reload, not an outage, but do not delete the current one on purpose.FUNCTION FLUSHdeletes every library on the server, other deployments' included: do not use it on a shared Valkey. The qm848 tests delete the libraries they load; other suites leave the library of the build under test on the test Valkey (about 1 MB), whichFUNCTION DELETEclears.
A checkpoint that is too big
Each written checkpoint logs one line: checkpoint <room> seq <n> <bytes> bytes, <events> events, retired <passes> passes + <pending> pending, <ms> ms, rss <n> MB before, <n> MB after, process peak <n> MB. The last three are the process RSS at the start and the end of that room's pass and the process's peak RSS since start (not the pass's own peak). A due room whose oldest un-checkpointed event is younger than the settle time (60 s) is skipped, not read: it could not be written yet. A state over 24 MB also logs checkpoint: room <room> state is N.N MB; a pass costs about 4x that in heap and ~9x in RSS. Alert on that warning, or on qm_checkpoint_state_bytes for the room. Only the instance that holds the ckpt:lease exports it (one that lost the lease stops at its next pass), and it reflects the rows that instance has written since it started, so after the compaction tool or a restart it is stale or absent for a quiet room; the SQL listing below is the source of truth.
What a pass costs (Notion 853). A pass parses the room's latest checkpoint, builds the engine from it, folds the new events, then writes the text. Measured on a synthetic 400k-ticket room (the 2026-11-14 loadtest shape: 400k joins, all passed, empty queue; 76.0 MB of JSON, 82 MB as Postgres prints it, against 75.4 MB in the incident): the V8 heap needed is about 3.5x the state as Postgres prints it (it was 5.6x before 853, and a 76 MB state died on a --max-old-space-size=512 heap that held the app's own ~50 MB; with the fix it survives up to ~200 MB of other heap), and the process RSS peaks near 9x (the pg driver's copies of the text sit outside the heap): 700 to 800 MB for that room. Not the old "3x". On a 1 GB instance (default heap about 512 MB) a state much over 60 MB is therefore out of reach. The 76 MB is owner 64% (48.7 MB: one record per ticket, 122 bytes: fp, fp2, ip, sid), passed, joinedAt and pending 12% each (9.1 MB, 23 bytes a ticket), and under 0.1 MB for everything else; lapsed (up to 50 000 marks, ~3.5 MB) adds to that. These are the passed tickets: a ticket is retired from the checkpoint only when it is older than the room's last journal event minus 10 minutes (and its pass TTL). A room whose traffic just stopped writes no later event, so the row written at the end of a window keeps every ticket of it for as long as the room stays quiet, empty queue or not.
Skipped, not killed. Before it reads a room's checkpoint a pass compares octet_length(state::text) x 4 with the old-generation heap still free (heap_size_limit - 192 MB - used_heap_size). The 4 is fixed in the server (a CheckpointJob option, not an env var); the stored size (pg_column_size) is no substitute, since compression took test rows to anywhere from 3.5% to 65% of their text. The 192 MB is the young generation, measured on Node 24 (--max-old-space-size=512 reports a 704 MB limit); on a build where it is smaller the guard only skips sooner than it has to. If the state does not fit, nothing is read or folded: the room is skipped, qm_checkpoint_skipped_total{room,reason="heap"} goes up (only the instance that holds the lease exports it; a lost lease or a deleted room drops it), and one line per room and checkpoint is logged: checkpoint: room <room> skipped (heap): base checkpoint is N.N MB, a pass needs about N MB of heap, N MB is free. Before 853 the same room made V8 abort (FATAL ERROR: Ineffective mark-compacts near heap limit, exit 134, no catch stops it): the instance restarted every ~7 minutes, about 75 s after boot, with no traffic.
What a room that is skipped on every pass costs, while it stays skipped:
- It keeps its oldest checkpoint, and the events prune deletes only events below the oldest kept usable checkpoint (
lib/roomstore/prune.js), so the room'seventsjournal grows without bound: disk, not memory. - A recovery replays a longer tail from that checkpoint (correct, slower).
- Recovery itself is not guarded. It loads the same big checkpoint through
recovery.jswith no heap check, so a Valkey loss on a heap too small for that row can still end in the same out-of-memory abort. Skipping the pass does not make that row smaller.
What to do: alert on increase(qm_checkpoint_skipped_total[1h]) > 0, then give the process more heap (NODE_OPTIONS=--max-old-space-size=<MB>) or a bigger instance until one pass has written a smaller row, or shrink the row with tools/compact-checkpoints.mjs (below) from a workstation. A room with no checkpoint yet is not guarded (there is no size to read): its first pass folds the whole journal and is the one case this check does not cover.
To list every room's latest rows by size, as the admin user:
SELECT room, octet_length(state::text) FROM room_snapshots ORDER BY 2 DESC;
A row shrinks by itself only when its room gets new events: the next checkpoint of that room writes a smaller row. A quiet room keeps its big row. tools/compact-checkpoints.mjs shrinks rows already written, without waiting:
DATABASE_URL=<direct url> PG_CA_FILE=<ca.crt> node tools/compact-checkpoints.mjs # dry run
DATABASE_URL=<direct url> PG_CA_FILE=<ca.crt> node tools/compact-checkpoints.mjs --write # act
- Run the dry run first. It lists every room's latest checkpoint; rooms over
--min-mb(default 16) show what they would shrink to, the others show as skipped (below minBytes). It changes nothing.--writeupdates those rows in place under the room's checkpoint lock. A room that fails is reported asskipped (error: ...), the others go on, and the tool exits1at the end. DATABASE_URLmust be the direct connection (the database port), not the pooler: the per-room lock needs a session.- On prod run
SHOW statement_timeoutfirst. The tool lifts the timeout for its own connections (SET statement_timeout = 0), which overrides a role-levelALTER ROLE ... SET statement_timeout = '10s'; if that statement fails, the tool says so and exits1. - Run it before a load window, not during one: it reads rows of tens of MB.
- It connects from the machine you run it on, so that machine's IP must be a trusted source of the managed database (its firewall); add it first.
- A compacted row cannot go below the lapse marks it keeps (up to 50,000, about 2.6 MB).
- The tool compacts only a room's latest row. With
keep= 2 a quiet room such asloadteststill holds its older big row as the recovery fallback, and the SQL listing above shows it until that room's next checkpoint. The tool is for quiet rooms whose row was written before this change; a room whose bytes keep growing has a big live line, which the tool does not shrink.
Clocks
Outflow pacing uses a monotonic clock, so an NTP correction cannot stall or burst promotions; recorded timestamps use the wall clock but never move backwards, which is what keeps the log and the prune order consistent.
What a clock step does cost is tickets. Every ticket carries the instant it was issued and is refused if it was issued more than one minute in the future or is older than TOKEN_MAX_AGE_SEC (24 hours by default). That check is what stops a ticket from last week being replayed, and it is not negotiable. So a host whose clock moves (a VM booting with a bad RTC before NTP steps it, a machine resumed from a snapshot, a container inheriting a wrong clock) refuses every ticket in the queue at once, and each of those visitors silently rejoins at the back of the line.
The server cannot prevent that, so it names it: a step of more than five seconds is logged, listed in incidents for the following hour, and sets status to degraded on /healthz. The probe still answers 200: taking the pod out of rotation does not fix the host's clock (see Readiness). Watch qm_rejected_tokens_all_total for the size of it. Keep NTP running on the host, and prefer a slew to a step.
No public-internet dependency
Every surface this server hands out (the console, the waiting page and /docs) renders completely with no request to any origin but this one. There is no CDN, no analytics, no external stylesheet and no external script. You can run the whole product on an airgapped network, behind a corporate proxy that blocks everything unlisted, or during the DNS outage that is the reason somebody opened the console in the first place, and it will look exactly the same.
There is one opt-in exception. A room that turns on the Turnstile challenge loads Cloudflare's widget script into its waiting page, and only that page, and only once the room has asked for it. Rooms that do not use it, and every other surface, are unchanged.
The typeface is not loaded from Google Fonts. Geist and Geist Mono are checked into public/fonts/ and served by this process at /fonts/<file>.woff2:
| File | Face | Subset |
|---|---|---|
geist-latin.woff2 | Geist, variable 400 to 700 | latin |
geist-latin-ext.woff2 | Geist, variable 400 to 700 | latin-ext |
geist-mono-latin.woff2 | Geist Mono, variable 400 to 600 | latin |
geist-mono-latin-ext.woff2 | Geist Mono, variable 400 to 600 | latin-ext |
- About 82 KB total, and a page only fetches the subsets it actually shows: an English waiting page pulls two files, not four.
- Served
Cache-Control: public, max-age=604800, so reloading a dashboard mid-incident does not refetch them. They are the one asset here that is pure content: identical in every deployment and carrying nothing about yours. - Sent uncompressed on purpose. woff2 is Brotli internally; gzipping it again costs CPU and adds bytes.
- Latin only. Thai, and every other non-Latin script, falls through to the system face, as it did on the CDN, whose subsets did not cover Thai either. The waiting page in Thai renders correctly; it just renders in the visitor's system font.
- Licensed SIL OFL 1.1 (Vercel / basement.studio). The licence ships beside the files in
public/fonts/LICENSE.txt; keep it there, redistribution requires it.
To update them, replace the four files, keep the names, and re-run the tests: test/surfaces.test.js fetches each one over HTTP and checks the wOF2 magic and the byte count, so a truncated or mistyped file fails the suite instead of silently falling back to Arial in production.
Running the HTTP tests
Every HTTP suite starts its server through startServer() in test/_harness.js, which runs node server.js with PORT, HOST=127.0.0.1, ADMIN_KEY, SECRET, the limit knobs set to 0 (off), plus whatever the suite adds (see the environment table above). Each server gets a temporary directory of its own (dataDir). Nothing is written there since step 5; it names the server's Valkey run below, so a restart on the same one sees the same state.
On the Valkey store. With STORE=valkey in the test process's environment (and TEST_VALKEY_URL, TEST_DATABASE_URL set), startServer() runs every server on STORE=valkey + SIDESTORE=pg: the test Valkey under a key prefix of its own and a Postgres schema of its own per dataDir, both deleted after the file. It never uses VALKEY_URL or DATABASE_URL from the environment, and refuses Valkey db 0 and a database whose name does not end in _test:
STORE=valkey npx vitest run test/conformance-http.test.js
Which suites pass on Valkey today, and why the others do not yet, is in docs/superpowers/plans/2026-09-25-valkey-step3a-http.md. The tests whose point is state surviving a restart (test/_valkey-only.js) run only on Valkey, since memory mode keeps nothing across a restart. Without TEST_VALKEY_URL and TEST_DATABASE_URL they are skipped, with one warning per file that names each skipped test; with QM_REQUIRE_VALKEY=1 (CI) they fail instead.
Local test databases. compose.test.yaml runs Postgres 18 (with TLS) and Valkey 8 in Docker on 127.0.0.1, so the tests need neither the network nor the production clusters. sh scripts/test-db.sh up makes a throwaway CA and a localhost certificate in .test-db/ (git-ignored), starts both containers, waits until they are healthy and prints the three variables the tests need: TEST_DATABASE_URL, TEST_VALKEY_URL and PG_CA_FILE (the TLS connection is verified against that CA, as in production). Data lives in memory; sh scripts/test-db.sh down or a container restart wipes it.
Against another server command. QM_SERVER_CMD (test-only, read by test/_harness.js) replaces node server.js with another command, to run the same HTTP suites against another implementation or build. It is split on whitespace (double quotes group a token) and spawned with no shell, with the same environment as above. It must be the server process itself, not a wrapper, because suites kill it and read its exit code, and it must print a line containing listening to stdout once it accepts connections. Unset, the harness runs node server.js from this repo.
test:conformance runs only the files that talk to the server over HTTP and nothing else: no require('../lib/...'), no assertions on its stderr, no decoding of ticket numbers out of a token. These files are: abuse, admin-host-gate, conformance-http, contract, edge-connector, failover, forwarded-proto-trust, forwarded-trust, identity, origin-down, prequeue-forwarded, proxy, snippet, stream-generation, surfaces, timeline and visitor-support. A file with even one white-box block stays out, so a white-box test goes in a sibling <name>.internal.test.js (as the ones split out of proxy, abuse, visitor-support, failover, identity and edge-connector did). The list is the test:conformance script in package.json; a new file that meets the bar goes there.