Skip to content

Cap in-flight realtime permission checks per worker - #15094

Closed
ArnabChatterjee20k wants to merge 4 commits into
fix/realtime-permission-ingest-fail-closedfrom
fix/realtime-permission-check-cap
Closed

ArnabChatterjee20k wants to merge 4 commits into
fix/realtime-permission-ingest-fail-closedfrom
fix/realtime-permission-check-cap

Conversation

@ArnabChatterjee20k

Copy link
Copy Markdown
Member

Issue / Description

Tracking: appwrite-labs/cloud#7108

Stacked on #15086 (base: fix/realtime-permission-ingest-fail-closed). It lands there when the stack is merged.

#15086 bounds how long the realtime pub/sub subscriber waits for a permission check: after the timeout it fails closed and moves on. The timed-out check itself is never reaped, though. Its child coroutine keeps waiting on the database read, holding the database pool connection it took, until that read returns. Under a slow or partly dead database, every timed-out check keeps a connection. Nothing in the process capped that below Swoole's coroutine limit, so stuck checks could drain the worker's pool and starve connection handshakes and everything else on that worker.

Solution

Appwrite\Realtime\Event\Handler::verify() now counts the permission checks running on its worker. The count goes up before the child coroutine starts and down in the child's finally, so a stuck check keeps its slot for as long as it is stuck. When the count is at the cap, no new child is started. The check fails closed immediately, like the timeout and coroutine-limit paths: the span records realtime.verification = check_limit with a GENERAL_SERVER_ERROR ("Permission verification skipped: check limit reached") attached, and the affected connections receive the 401 and close.

The cap is derived from the worker's real database pool, with no new setting: max(1, intdiv(console pool size, 2)). size is a public property of Utopia\Pools\Pool, and every database pool in app/init/registers.php uses the same size. Stuck checks can therefore hold at most half the pool and always leave connections for everything else. This matches the MQTT broker's version in #15093.

Limits

  • With default settings the per-worker pool is 1 (151 / 15 connections, split across CPU × 6 workers in app/init/registers.php). The cap is then 1, and one stuck check already holds the whole pool. The cap prevents a second check from adding to it, but it cannot keep a connection free on a pool of one. Deployments with larger pools get the headroom described above.
  • The cap only applies after a timeout. The subscriber processes events one at a time, so a new check can only start once the previous one has finished or timed out.
  • This bounds the leak; it does not reap it. A stuck child still holds its slot and its connection until its read returns. Freeing them needs the database read timeout, appwrite-labs/cloud#7100.

Tests

Verified locally against a real Swoole realtime server and Redis, using the same process harness as #15086 with a temporary test that is not committed. The pool-sizing settings (_APP_CPU_NUM=1, _APP_WORKER_PER_CORE=1, _APP_POOL_CLIENTS=1, _APP_CONNECTIONS_MAX=2) give a console pool of 2, so the derived cap is 1. Scenario: one user's permission check gets stuck on a database read that never returns. Then a permission change arrives for a second user, followed by a normal event, then a new connection.

Before (5015e9ede0, no cap) After (d9ec7f7db7)
Second user's check while the first is stuck Starts a second child and waits the full timeout (span timed_out, 2s), leaving two stuck checks Refused at once (span check_limit, 0s), connection closed with 401
Normal event after both Delivered Delivered
New connection's handshake Succeeds Succeeds

The fake database in the harness holds no real pool connection, so this run cannot show the pool draining and handshakes stalling. It shows that, without the cap, every stuck check starts another child. In production each of those children holds a pool connection.

After (green), d9ec7f7
PHPUnit 12.5.35 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.5.11
Configuration: /usr/src/code/phpunit.xml


first check: realtime.verification=timed_out span.duration=2.002s
second check: realtime.verification=check_limit span.duration=0s, closed after 0s
follow-up delivered; new handshake succeeded
testCheckLimitFailsClosedWhileACheckIsStuck ended in 7261 milliseconds
D                                                                   1 / 1 (100%)

Time: 00:07.263, Memory: 20.00 MB

Check Limit Local (Tests\Unit\Realtime\CheckLimitLocal)
 ⚠ Check limit fails closed while a check is stuck

OK, but there were issues!
Tests: 1, Assertions: 14, Deprecations: 2.
Before (red), 5015e9e

ANSI colour codes stripped. Nothing else edited.

PHPUnit 12.5.35 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.5.11
Configuration: /usr/src/code/phpunit.xml


first check: realtime.verification=timed_out span.duration=2.001s
second check: realtime.verification=timed_out span.duration=2s, closed after 2s
follow-up delivered; new handshake succeeded
testCheckLimitFailsClosedWhileACheckIsStuck ended in 9267 milliseconds
F                                                                   1 / 1 (100%)

Time: 00:09.270, Memory: 20.00 MB

Check Limit Local (Tests\Unit\Realtime\CheckLimitLocal)
 ✘ Check limit fails closed while a check is stuck
   │
   │ Second check was not refused by the check limit
   │ Failed asserting that two strings are identical.
   │ --- Expected
   │ +++ Actual
   │ @@ @@
   │ -'check_limit'
   │ +'timed_out'
   │
   │ /usr/src/code/tests/unit/Realtime/CheckLimitLocalTest.php:359
   │

FAILURES!
Tests: 1, Assertions: 13, Failures: 1, Deprecations: 2.

composer lint and composer analyze are clean on the changed files, and tests/unit/Realtime passes (50 tests).

🤖 Generated with Claude Code

A timed-out check is never reaped: it keeps its coroutine and database
connection until the read returns, so under a slow database stuck checks
could drain the worker's pool and starve everything else. The handler
now counts running checks and, at the cap, fails closed immediately with
realtime.verification = check_limit instead of starting another. The cap
is half the worker's database pool (at least one), derived from the
console pool's size, so stuck checks always leave connections free.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Hung checks permanently consume slots with no reaping · Handler.php:478–503 · unchanged line

// src/Appwrite/Realtime/Event/Handler.php
478	            $started = \go(function () use ($check, $done): void {
479	                try {
480	                    $done->push(['closing' => $check()]);
481	                } catch (\Throwable $th) {
482	                    $done->push(['error' => $th]);
483	                } finally {
484	                    $this->checks--;
485	                }
486	            });
487	
488	            // Never inline: that brings back the unbounded wait.
489	            if ($started === false) {

A check coroutine that never completes holds its slot forever: $this->checks is only decremented when the child coroutine finishes (src/Appwrite/Realtime/Event/Handler.php line 484), and the timeout path at lines 497-503 merely stops waiting — the hung coroutine keeps running, holding its slot and its database connections indefinitely, with no watchdog or hard kill. Once checkLimit checks hang (e.g. a database lock wait or wedged connection), every subsequent verify() call takes the check_limit branch and fails closed. A transient database hang then converts into a sustained realtime permission-verification outage on that worker, closing connections for every arriving event until the process is restarted.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Limit-driven closures are indistinguishable from denials (Handler.php:469) — When checks >= checkLimit or the coroutine spawn fails, verification is skipped and every affected connection receives the standard unauthorizedPayload and close code (src/Appwrite/Realtime/Event/Handler.php lines 69-72), identical to a genuine permission revocation.

This PR caps concurrent permission checks in the realtime worker at half the console database pool size, failing closed (closing the client connection) when the cap is reached instead of queueing an unbounded number of checks.

Files Change
app/realtime.php Passes checkLimit to the realtime Handler, derived as half the console connection pool size with a floor of 1.
src/Appwrite/Realtime/Event/Handler.php Adds a checks counter incremented when a verification coroutine spawns and decremented in a finally block; the verify() path fails closed via onFailure() when the limit is reached or coroutine spawn fails.

Reviewed commit: d9ec7f7

@ghost

ghost commented Oct 29, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

Limited by an open major finding: Avoid exporting a span for every realtime event

The realtime worker now caps concurrent permission checks based on half of the console database pool, with a minimum of one, and fails closed when the cap is reached. It also records event counts, exposes the current processing-stage duration, and emits event spans; new unit coverage checks these telemetry behaviors.

Latest changes: The newest commits add event counters, a stage-duration gauge, per-event spans, and unit tests with recording helpers.

Verdict New comments Fixed Still open
🛑 Changes requested 1 0 0
Finding Where
🟠 Avoid exporting a span for every realtime event src/Appwrite/Realtime/Event/Handler.php:119
Fix with agent prompt
### Issue 1
src/Appwrite/Realtime/Event/Handler.php:119
**Avoid exporting a span for every realtime event**

With the default self-hosted exporter in `app/init/span.php`, every successful pub/sub message now synchronously writes a `realtime.event` span to stdout; under normal firehose traffic this can create unbounded log volume and slow the worker. The previous handler deliberately emitted spans only for failures, so routine spans need sampling or opt-in export.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 5
File Change
app/realtime.php Registers the event telemetry instruments and passes them, alongside the pool-derived permission-check limit, to the handler.
src/Appwrite/Realtime/Event/Handler.php Tracks the permission-check cap and event processing stages, records event telemetry, and creates event spans.
tests/unit/Realtime/Event/HandlerTest.php Covers event spans, counters, invalid payloads, timestamp failures, and the idle stage gauge.
tests/unit/Realtime/Event/RecordingAdapter.php Adds a recording WebSocket adapter for handler tests.
tests/unit/Realtime/Event/RecordingExporter.php Adds a span exporter that retains finished spans for assertions.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Validate span attribute values before creating the span Verifier: The scalar-only Span::set() signature would reject the proposed malformed values, but no production path supplying them was found. The realtime Redis publisher is Messaging/Adapter/Realtime::send(), which requires a string projectId and constructs the event envelope itself. Its production caller supplies events from Event::generateEvents(), which produces string event names. User payload data remains nested under data.payload, not these attributes. In addition, a malformed project already escaped in the base handler because its catch block passed that same project value to Span::set(). The claimed regression therefore depends on an unsupported malformed Redis publication rather than a reachable application input.

Reviewed the commits since d9ec7f7 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix/realtime-permission-ingest-fail-closed (before) → fix/realtime-permission-check-cap (after).

Metric Before After Change
🚀 Requests/sec 158.31 163.46 ⚪ +3.3%
⏱️ Latency P50 107.38 ms 107.2 ms ⚪ -0.2%
⏱️ Latency P95 268.01 ms 253.33 ms 🟢 -5.5%
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 107.2 253.33 10,260 163.46 -14.68
Account 183.2 366.18 540 9.22 -39.24
TablesDB 105.05 202.49 5,580 91.33 -5.03
Storage 97.18 244.89 2,700 46.21 -8.14
Functions 140.39 287.35 1,440 25.35 -44.24

Top API waits (after)

API request Max wait (ms)
account.name.update 653.54
account.prefs.update 591.5
storage.buckets.create 557.42
functions.create 484.17
functions.delete 411.67

ArnabChatterjee20k and others added 2 commits October 30, 2026 09:32

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

}

$span->set('realtime.resolved_at', \microtime(true));
$span->finish(error: $error);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid exporting a span for every realtime event

With the default self-hosted exporter in app/init/span.php, every successful pub/sub message now synchronously writes a realtime.event span to stdout; under normal firehose traffic this can create unbounded log volume and slow the worker. The previous handler deliberately emitted spans only for failures, so routine spans need sampling or opt-in export.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Event/Handler.php
Line: 119

Comment:
**Avoid exporting a span for every realtime event**

With the default self-hosted exporter in `app/init/span.php`, every successful pub/sub message now synchronously writes a `realtime.event` span to stdout; under normal firehose traffic this can create unbounded log volume and slow the worker. The previous handler deliberately emitted spans only for failures, so routine spans need sampling or opt-in export.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟠 Major · performance · Reply if this doesn't apply.

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