Skip to content

Fix realtime concurrency: close connections on worker exit, fold over a trailing window - #13520

Merged
lohanidamodar merged 10 commits into
mainfrom
fix/realtime-concurrency-window
Sep 10, 2026
Merged

lohanidamodar merged 10 commits into
mainfrom
fix/realtime-concurrency-window

Conversation

@lohanidamodar

@lohanidamodar lohanidamodar commented Sep 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Two changes that together stop the realtime.connections concurrency gauge from ratcheting upward — the cause of the realtime peak rising 3.7× in five days on Cloud billing.

  1. Close a worker's connections when it exits (app/realtime.php, new Appwrite\Utopia\WebSocket\Adapter\Swoole) — the root cause.
  2. Fold the level over a trailing window instead of carrying it (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, onClose runs in a worker that never registered them, the array_key_exists gate fails, and the -1 is 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 (unlike onWorkerStop), and closes every registered connection with 1001 Going Away. The -1, the connectionsTotal decrement, telemetry, presence cleanup and unsubscribe all take the existing onClose path — 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 enables reload_async with max_wait_time 15s, 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_time exceeded) still loses closes, and a carried level keeps every such error forever. Each bucket is now

level = max(0, Σ deltas in (bucket end − window, bucket end])

with 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:

region live 3h 6h 12h 24h carried (gauge today)
fra1 1,415 461 1,142 2,519 3,957 29,521
nyc3 1,263 1,482 2,499 5,617 11,298 35,238
sgp1 300 188 314 662 828 4,180
sfo3 / tor1 / syd1 161 / 73 / 63 — 52 / 28 / 33 144 / 77 / 51 — 2,692 / 758 / 207
total 3,275 72,596

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

  • Same gauge, metric name and 5-minute cadence; resume-from-last-sample unchanged, so no bucket is emitted twice.
  • Cloud's getRealtimePeakConnections (max over the cycle's samples) and /v1/usage/gauges?aggregate=max read exactly as before.
  • Gauge write volume: a tenant is sampled only for buckets it had deltas in, as before.

Tests and gaps

tests/unit/Usage/ConcurrencyTest.php — each case seen red against the carried fold, green after:

  • the level is the windowed sum, not the carried gauge
  • an open exactly one window old has aged out
  • each catch-up bucket gets its own window
  • a bucket without deltas is not sampled
  • a capped read samples only the buckets it completed
  • the event read starts one window before the first emitted bucket

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:

realtime.php under test opens closes net
origin/main 8 0 8 stranded
this branch 10 10 0
adapter only (reload_async, no exit hook) 8 0 8 stranded
exit hook registered but empty 8 0 8 stranded

The last two rows matter: neither enabling reload_async nor merely registering a workerExit handler is sufficient. The closes come from the hook's own sweep, which drives them through the normal onClose path.

Running it also turned up a defect that no unit test would have: Swoole re-invokes onWorkerExit until the worker's loop is empty, so the sweep ran on every call — a few hundred warnings per shutdown and repeated close() 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)

  • Bump REALTIME_CONCURRENCY_BASELINE to the deploy time so this cycle's peak is taken only over windowed samples.
  • Refresh the getRealtimePeakConnections docblock, which still describes the carried fold.
  • Raise WINDOW_SECONDS once the flush is confirmed in production.

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
lohanidamodar force-pushed the fix/realtime-concurrency-window branch from 135af93 to 223f218 Compare September 8, 2026 02:38
@greptile-apps

greptile-apps Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding correctness, security, or repository-rule violation remains.

Summary

  • Adds a Swoole worker-exit hook that closes locally registered connections through the existing close lifecycle.
  • Enables asynchronous worker draining and extends its maximum wait period.
  • Computes concurrency from event deltas within a six-hour window rather than carrying the previous gauge indefinitely.
  • Pages dense usage reads without committing samples from a potentially split bucket.
  • Adds output-level tests for windowing, catch-up, sparse buckets, and pagination behavior.

Reviews (9) · Last reviewed commit: "fix(realtime): give the exit drain the w..."

Comment thread src/Appwrite/Usage/Concurrency.php Resolved
Comment thread src/Appwrite/Usage/Concurrency.php Resolved
Comment thread src/Appwrite/Usage/Concurrency.php Resolved
@github-actions

github-actions Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/realtime-concurrency-window (after).

Metric Before After Change
🚀 Requests/sec 238.36 247.81 ⚪ +4%
⏱️ Latency P50 73.98 ms 70.07 ms 🟢 -5.3%
⏱️ Latency P95 168.14 ms 164.36 ms ⚪ -2.3%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 70.07 164.36 15,618 247.81 -3.78
Account 142.74 244.23 822 13.6 -7.03
TablesDB 67.4 119.7 8,494 137.83 -7.41
Storage 65.32 132.16 4,110 68.34 -18.86
Functions 107 194.71 2,192 37.13 -10.12

Top API waits (after)

API request Max wait (ms)
account.name.update 470.37
storage.files.create 341.56
functions.variables.update 337.55
functions.create 335.92
storage.files.preview 331.61

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.
@lohanidamodar lohanidamodar changed the title Fold realtime concurrency over a trailing window Fix realtime concurrency: close connections on worker exit, fold over a trailing window Sep 8, 2026
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.
Comment thread src/Appwrite/Usage/Concurrency.php Resolved
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.
Comment thread tests/unit/Usage/ConcurrencyTest.php Resolved
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.
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.
@lohanidamodar
lohanidamodar merged commit 422f14e into main Sep 10, 2026
45 checks passed
@lohanidamodar
lohanidamodar deleted the fix/realtime-concurrency-window branch September 10, 2026 04:35
@ChiragAgg5k ChiragAgg5k mentioned this pull request Sep 10, 2026
2 of 4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant