Skip to content

fix(realtime): cap channels and queries across a connection - #14948

Merged
ArnabChatterjee20k merged 3 commits into
fix-realtime-subscription-limitsfrom
fix-realtime-connection-budget
Oct 27, 2026
Merged

ArnabChatterjee20k merged 3 commits into
fix-realtime-subscription-limitsfrom
fix-realtime-connection-budget

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Stacked on #14945. Merge that first.

What does this PR do?

#14945 limits each subscription, but the limits multiply: 100 subscriptions × 100 channels × 100 queries lets one connection hold tens of MB, and one user with 32 connections several GB. This PR adds a budget for the whole connection and bounds the size of a single query.

Constraints

Constraint #14945 This PR When exceeded
Channels across a connection's subscriptions 100 × 100 = 10,000 100 (APP_LIMIT_REALTIME_CHANNELS) message: 1003, stays connected; URL: 1008 close
Queries across a connection's subscriptions 100 × 100 = 10,000 100 (APP_LIMIT_REALTIME_QUERIES) same
Queries nested in and/or counted as 1 each one counts same
Queries in one subscription, nested ones included 100 top-level, any depth 100 same
Values in one query (e.g. equal('id', [...])) any, up to the 64 KB message 100 (APP_LIMIT_ARRAY_PARAMS_SIZE) same
Length of one query any, up to the 64 KB message 4,096 characters (APP_LIMIT_ARRAY_ELEMENT_SIZE), the same as the REST API same
Subscribing again with an existing id adds channels; new queries only on the named channels adds channels; replaces queries on all of its channels —

Unchanged from #14945: 100 subscriptions per connection, 100 channels per subscription, 32 open connections per user per worker.

Subscribing again with an id was meant as an upsert, but older channels kept their old queries, so one subscription could hold several query sets and its queries couldn't be counted. Each subscription now has one set, which is also what in-band authentication already rebuilds it with.

Worst-case memory

The most one worker can be made to hold when every level is maxed out: 100 projects × 100 users × 32 connections. Measured on PHP 8.5 with the real adapter; each connection uses the spread of the budget that costs the most (50 subscriptions × 2 channels × 2 queries of 100 values each, every query near the 4,096-character limit). Subscriptions are stored once per role, so the 20-role column is a user in several teams.

Level #14945, 5 roles #14945, 20 roles This PR, 5 roles This PR, 20 roles
1 connection 38 MB 132 MB 1.8 MB 2.8 MB
1 user (32 connections) 1.2 GB 4.1 GB 59 MB 90 MB
1 project (100 users) 118 GB 412 GB 5.8 GB 8.8 GB
100 projects (320,000 connections) 11.5 TB 40 TB 575 GB 875 GB
1 guest connection (2 roles) 18.9 MB — 1.7 MB —

A general shape for comparison: 30 projects × 100 users × 5 connections, users with 10 roles, each connection with 30 subscriptions of 3 distinct channels and 30 queries in total. It is within the limits, so it costs the same before and after.

Level Count Memory
1 connection 30 subscriptions, 90 channels, 30 queries 435 KB
1 user 5 connections 2.1 MB
1 project 100 users, 500 connections 213 MB
30 projects 15,000 connections 6.2 GB

The fleet-wide totals still grow with the number of connections; a cap on connections per worker and on guest connections per IP are follow-ups.

Test Plan

  • Unit: MessagingTest::testConstructSubscriptionsLimitsTotals, testConvertQueriesLimitsQuerySize, testCountQueriesIncludesNested, testSubscribeAgainReplacesQueriesOnEveryChannel
  • E2E: RealtimeCustomClientQueryTestWithMessage::testSubscribeTotals

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

🤖 Generated with Claude Code

Limits per subscription multiplied: 100 subscriptions x 100 channels
x 100 queries let one connection hold tens of MB.

- At most 200 channels and 100 queries across all subscriptions of a
  connection, on both the message and URL paths
- Queries nested in and/or count, and a query takes at most 100
  values, so one large query cannot stand in for many
- Subscribing again with an id replaces its queries on all of its
  channels, so each subscription holds one set of queries

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

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

Copy link
Copy Markdown

Review complete. No blocking issues — 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Select-all subscriptions count as 0 queries on websocket path (Realtime.php:177) — A subscription sent with an empty queries array is stored with 'count' => self::countQueries([]) = 0 even though it is represented by a select-all filter (src/Appwrite/Messaging/Adapter/Realtime.php:177), so it contributes nothing to the connection-wide APP_LIMIT_REALTIME_QUERIES sum checked in src/Appwrite/Realtime/Message/Handlers/Subscribe.php:170.

The change introduces new APP_LIMIT_REALTIME_* constants and enforces per-connection limits on realtime subscriptions: a connection cap, a per-connection channel cap, and a per-connection query cap, validated both when a websocket client sends a subscribe message and when subscriptions are built from URL parameters. Unit tests lock the countQueries helper's nesting semantics and an e2e suite covers the client-visible error behavior. | Files | Change | |-------|--------| | app/init/constants.php | Adds the new realtime limit environment constants. | | src/Appwrite/Messaging/Adapter/Realtime.php | Adds countQueries/query-value validation and enforces channel and query limits in subscribe() and constructSubscriptions(). | | src/Appwrite/Realtime/Message/Handlers/Subscribe.php | Aggregates per-connection query counts and rejects subscribe messages exceeding the new limits. | | tests/unit/Messaging/MessagingTest.php, tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php | Unit locks for countQueries and e2e coverage of limit rejection. |

Reviewed commit: 981b93a

@ghost

ghost commented Oct 26, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The query replacement leaves stale filters on existing console-tail entries, a minor correctness issue in that feature.

This change adds connection-wide realtime channel and query budgets, including counting nested queries and limiting query/value sizes. Reusing a subscription ID now replaces its query set across the subscription’s existing channels. Unit and E2E tests cover the new limits and replacement behavior.

Verdict New comments Fixed Still open
💬 Commented 1 0 0

Note

Not approving while a bug finding is open: Keep console-tail filters in sync with query replacement

Finding Where
🟡 Keep console-tail filters in sync with query replacement src/Appwrite/Messaging/Adapter/Realtime.php:184
Fix with agent prompt
### Issue 1
src/Appwrite/Messaging/Adapter/Realtime.php:184
**Keep console-tail filters in sync with query replacement**

Console-tail delivery uses `EventTailRegistry`'s separate filters, which are only updated for tail channels present in the current subscribe payload. Reusing this ID with `channels: []` (or adding a new channel) therefore leaves previously attached tail channels filtering with the old query, so they can deliver events that no longer match the subscription or suppress new matches.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 5
File Change
app/init/constants.php Defines connection-wide channel and query limits.
src/Appwrite/Messaging/Adapter/Realtime.php Tracks query counts, enforces URL-side limits and query sizes, and replaces queries on existing subscription channels.
src/Appwrite/Realtime/Message/Handlers/Subscribe.php Enforces connection-wide totals for in-band subscriptions.
tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Covers in-band connection limits, query size limits, and replacement behavior.
tests/unit/Messaging/MessagingTest.php Covers URL-side totals, nested query counting, query-size limits, and subscription replacement.

Reviewed de40891 · 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 B · See the inline comments. Summary

@github-actions

github-actions Bot commented Oct 26, 2026 •

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 26, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix-realtime-subscription-limits (before) → fix-realtime-connection-budget (after).

Metric Before After Change
🚀 Requests/sec 201.78 208.48 ⚪ +3.3%
⏱️ Latency P50 85.48 ms 82.38 ms ⚪ -3.6%
⏱️ Latency P95 198.25 ms 197.46 ms ⚪ -0.4%
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 82.38 197.46 12,996 208.48 -0.79
Account 156.53 304.29 684 11.33 +24.31
TablesDB 79.77 145.94 7,068 115.53 -10.46
Storage 75.65 177.18 3,420 57.65 -26.63
Functions 119.76 241.14 1,824 31.32 +14.37

Top API waits (after)

API request Max wait (ms)
functions.create 503.14
account.prefs.update 483.15
account.name.update 451.73
tablesdb.rows.create 450.68
functions.variables.create 408.7

A value count alone did not bound how long a value could be, so one
query could carry a ~50 KB string. Query strings are now limited to
APP_LIMIT_ARRAY_ELEMENT_SIZE characters, the same as the REST API,
checked before parsing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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

@abnegate

Copy link
Copy Markdown
Member

@hansi-codes review

@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 A · See the inline comments. Summary

foreach ($this->connections[$identifier]['roles'] ?? [] as $role) {
foreach ($this->connections[$identifier]['channels'] ?? [] as $channel) {
if (isset($this->subscriptions[$projectId][$role][$channel][$identifier][$subscriptionId])) {
$this->subscriptions[$projectId][$role][$channel][$identifier][$subscriptionId] = $data;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Keep console-tail filters in sync with query replacement

Console-tail delivery uses EventTailRegistry's separate filters, which are only updated for tail channels present in the current subscribe payload. Reusing this ID with channels: [] (or adding a new channel) therefore leaves previously attached tail channels filtering with the old query, so they can deliver events that no longer match the subscription or suppress new matches.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Messaging/Adapter/Realtime.php
Line: 184

Comment:
**Keep console-tail filters in sync with query replacement**

Console-tail delivery uses `EventTailRegistry`'s separate filters, which are only updated for tail channels present in the current subscribe payload. Reusing this ID with `channels: []` (or adding a new channel) therefore leaves previously attached tail channels filtering with the old query, so they can deliver events that no longer match the subscription or suppress new matches.

---

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

🟡 Minor · bug · Reply if this doesn't apply.

@ArnabChatterjee20k
ArnabChatterjee20k merged commit bd837dd into fix-realtime-subscription-limits Oct 27, 2026
72 checks passed
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.

2 participants