Repository navigation
Fix realtime concurrency: close connections on worker exit, fold over a trailing window - #13520
Merged
Merged
Conversation
A realtime worker that stops never emits the closes for its open connections, so the carried level only ever ratcheted upward: fleet-wide the gauge read 72,596 against 3,275 live connections, and the peak that billing takes from it rose 3.7x in five days. Each bucket is now the net of the deltas inside the trailing _APP_REALTIME_CONCURRENCY_WINDOW (default 6h). That needs no carried state and forgets an orphaned open within one window, at the price of not seeing connections older than the window. 6h was calibrated against live connection counts per region (fra1 0.86x, nyc3 1.98x, sgp1 1.05x); shorter hid long-lived connections, longer carried a stopped worker's opens for the rest of the cycle.
lohanidamodar
force-pushed
the
fix/realtime-concurrency-window
branch
from
September 8, 2026 02:38
135af93 to
223f218
Compare
Contributor
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
In process mode the connections belong to the reactor and the registry that maps them to projects is per worker, so a worker that exits leaves its connections open; whenever they finally close, onClose runs in a worker that never registered them and the -1 is skipped. Every rollout, scale-down and reload therefore added that worker's open count to the concurrency level for good. The base adapter exposes no worker-exit hook, so a subclass adds one and turns on reload_async, which is what makes the hook fire while the loop is still alive. realtime.php closes every registered connection there, so the -1, the stats decrement and the presence cleanup all take the existing onClose path and clients reconnect to a live worker.
The event read now spans the window as well as the catch-up range, so it can hit the 50,000-row cap on a long catch-up. The rows come back time-ascending, so a capped result is still complete for every bucket before the last one it returned: sample up to there and let the next run resume, instead of writing levels that are missing deltas and advancing past them for good. Sampling every catch-up bucket for any tenant active in the window multiplied gauge writes for sparse tenants; a tenant is again written only for the buckets it had deltas in. The window changes the value, not how often it is sampled. Wire _APP_REALTIME_CONCURRENCY_WINDOW through variables.php, .env and the compose services that carry _APP_STATS_RESOURCES_INTERVAL.
Only the fold reads it, so it does not need to be an environment variable or the configuration surfaces that come with one. Like the interval and the lag, it is a constant; raising it is a code change.
Stopping at the last bucket a capped read completed made no progress when the cap fell at or before the first bucket awaiting a sample: the resume point comes from the newest gauge sample, which was never written, so every later run repeated the same capped read. A window dense enough to fill a page with its own history stalled sampling for good. The read is now paged. Each page drops its newest bucket, which the limit may have split, and the next page re-reads that bucket whole, so the cursor advances by at least one interval per page. Only a bucket that fills a page on its own is unsamplable, and that is reported rather than silently truncated. Page size is a constructor argument so a test can reach the cap without 50,000 rows.
… into fix/realtime-concurrency-window
Swoole re-runs the exit hook until the worker's loop is empty, so the sweep ran on every call: one shutdown wrote a few hundred warnings and re-closed connections that were already closing. It now runs once and the later calls let the closes it started drain. Found running the fix locally against a real stack.
One test inspected the read's query methods and time bounds, and another counted event reads, both of which pin how the fold fetches rather than what it samples. The window boundary they guarded is already observable: an open exactly one window back ages out of the level, and one inside it still counts. Coverage is unchanged -- with the clock pinned, the carried fold still fails six of the seven tests, and the pre-paging read still fails the dense-paging one.
max_wait_time was 5s, which would have been the tighter limit on a worker holding thousands of connections: whoever stops the process caps the drain anyway -- a Cloud pod leaves ~10s after its 20s preStop, out of a 30s grace period -- so a lower value only cuts the drain short and strands the rest.
This was referenced Sep 10, 2026
2 of 4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Two changes that together stop the
realtime.connectionsconcurrency gauge from ratcheting upward — the cause of the realtime peak rising 3.7× in five days on Cloud billing.app/realtime.php, newAppwrite\Utopia\WebSocket\Adapter\Swoole) — the root cause.Appwrite\Usage\Concurrency) — bounds any residual error and removes the manual re-anchor.1. Why closes were lost
In Swoole process mode the connections belong to the reactor, while the registry that maps a connection to its project (
$realtime->connections) lives in the worker that accepted it. When that worker exits — rollout, HPA scale-down, reload — its connections stay open. Whenever they finally close,onCloseruns in a worker that never registered them, thearray_key_existsgate fails, and the-1is never emitted. Every worker exit therefore added its open count to the level permanently.The fix hooks
WorkerExit, which fires in the exiting worker while its event loop is still alive (unlikeonWorkerStop), and closes every registered connection with1001 Going Away. The-1, theconnectionsTotaldecrement, telemetry, presence cleanup andunsubscribeall take the existingonClosepath — no second bookkeeping, no double count — and clients reconnect to a live worker instead of holding a socket the worker has abandoned. The base Utopia adapter exposes no such hook, so a small subclass adds it and enablesreload_asyncwithmax_wait_time15s, which is what lets the loop drain. Whoever stops the process caps that anyway -- a Cloud pod leaves ~10s after its 20s preStop, out of a 30s grace period -- so the value is set high enough not to be the tighter limit.2. Why the fold also changes
Even with the flush, a killed worker (OOM,
max_wait_timeexceeded) still loses closes, and a carried level keeps every such error forever. Each bucket is nowwith a 6h window (
Concurrency::WINDOW_SECONDS, a constant like the interval and the lag). No carried state, so an orphaned open is forgotten one window later, at the price of not seeing connections older than the window.A tenant is still written only for the buckets it had deltas in — the window changes the value, not how often it is sampled — so gauge write volume is unchanged. The event read now spans the window as well as the catch-up range; because it is time-ascending, a result that hits the 50,000-row cap is still complete for every bucket before the last one returned, so the fold samples up to there and the next run resumes, rather than writing levels missing deltas and advancing past them.
Calibration (production, read-only, 2026-09-08 02:20 UTC)
Live inbound connections counted on the realtime pods against each estimator for the same instant, ~3h after a fleet-wide rollout:
Shorter windows hide long-lived connections (fra1 at 3h: 0.33×); longer ones carry a stopped worker's opens (nyc3 at 12h: 4.4×). 6h is the balance with the leak still present. Once (1) is confirmed in production the leak term disappears and a longer window (24h+) becomes the better default — deliberately not changed here until that is verified.
Behaviour that does not change
getRealtimePeakConnections(max over the cycle's samples) and/v1/usage/gauges?aggregate=maxread exactly as before.Tests and gaps
tests/unit/Usage/ConcurrencyTest.php— each case seen red against the carried fold, green after:No automated test covers the worker-exit path — it is the Swoole server lifecycle. It was instead verified against a real stack (compose, ClickHouse, the stats-usage worker), opening websocket connections and restarting the realtime container with SIGTERM, which is the pod-termination path:
origin/mainreload_async, no exit hook)The last two rows matter: neither enabling
reload_asyncnor merely registering aworkerExithandler is sufficient. The closes come from the hook's own sweep, which drives them through the normalonClosepath.Running it also turned up a defect that no unit test would have: Swoole re-invokes
onWorkerExituntil the worker's loop is empty, so the sweep ran on every call — a few hundred warnings per shutdown and repeatedclose()on connections already closing. It now sweeps once; a shutdown writes exactly one line,Worker 0 exiting, closing 10 open connections.Still worth watching on the first production rollout: whether a worker holding ~470 connections drains inside the ~10s a pod has after its preStop. Each close does database and queue work, and the local run drained only a dozen. The log line gives the count to compare against the closes that land that hour; if it falls short the remainder is stranded, though the 6h window now caps how long that costs anything.
Follow-ups (Cloud)
REALTIME_CONCURRENCY_BASELINEto the deploy time so this cycle's peak is taken only over windowed samples.getRealtimePeakConnectionsdocblock, which still describes the carried fold.WINDOW_SECONDSonce the flush is confirmed in production.