Skip to content

fix(realtime): cap subscriptions, channels and connections per user - #14945

Merged
ArnabChatterjee20k merged 26 commits into
mainfrom
fix-realtime-subscription-limits
Oct 27, 2026
Merged

ArnabChatterjee20k merged 26 commits into
mainfrom
fix-realtime-subscription-limits

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds limits to realtime connections. Nothing capped how many subscriptions, channels or queries a connection could register, or how many connections one user could keep open, so a single client could make a shared realtime worker do unbounded work.

Limits

Limit Value When exceeded
Channels per subscription 100 (APP_LIMIT_ARRAY_PARAMS_SIZE) message: 1003 error, connection stays open; URL: 1008 close
Queries per subscription 100 (APP_LIMIT_ARRAY_PARAMS_SIZE) same
Subscriptions per connection 100 (APP_LIMIT_REALTIME_SUBSCRIPTIONS) same
Ids per unsubscribe batch 100 1003 error
Open connections per project user, per worker 32 (APP_LIMIT_REALTIME_CONNECTIONS) 1008 close

Worst-case memory

The most one worker can be made to hold when every level is maxed out: 100 projects × 100 users × 32 connections, each connection with the most subscriptions and channels allowed. Measured on PHP 8.5 with the real adapter and normal-size queries; subscriptions are stored once per role, so the 20-role column is a user in several teams.

Level Before (main) After (this PR), 5 roles After (this PR), 20 roles
1 connection unbounded, grows ~664 MB/min (5 roles) to ~2.6 GB/min (20 roles) 38 MB 132 MB
1 user unbounded (no connection limit) 32 connections × 38 MB = 1.2 GB 4.1 GB
1 project (100 users) unbounded 118 GB 412 GB
100 projects (320,000 connections) unbounded 11.5 TB 40 TB
1 guest connection (2 roles) unbounded 18.9 MB, no limit on how many —

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

Level Count Memory
1 connection 30 subscriptions, 150 channels, 30 queries 690 KB
1 user 5 connections 3.4 MB
1 project 100 users, 500 connections 337 MB
30 projects 15,000 connections 9.9 GB

Before, a single 64 KB message could add ~21 MB, so one connection could exhaust a worker in minutes. After, one connection has a ceiling, but the per-user and fleet-level totals are still large.

Design notes

  • Counted per worker. Each worker only holds its own connections, so a local count bounds every worker with no shared state on the connect path.
  • Keyed by projectId:userId, with no per-project cap, so one user can't lock out a project's other users. Guests aren't counted; the existing per-IP abuse limit covers them.
  • Counted per connection. The adapter records which user each connection is counted under, and onClose releases it by connection id. In-band authentication moves the count to the new user, and a rejected switch leaves the connection as it was.
  • Re-subscribing an existing subscription id replaces it in place, so it doesn't count towards the subscription limit.

Test Plan

  • Unit: SubscribePayloadTest, UnsubscribePayloadTest, MessagingTest::testAddConnection*
  • E2E: RealtimeCustomClientTest::testConnectionLimitPerUser, testConnectionChannelLimit, RealtimeCustomClientQueryTestWithMessage::testSubscribeLimits

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

A connection could register any number of subscriptions, channels and
queries, and a user could hold any number of open connections, so one
client could grow worker memory and stall the event loop for every
project on that worker.

- At most 100 channels and 100 queries per subscription, on both the
  message and URL paths
- At most 100 subscriptions per connection; re-subscribing an existing
  id does not count, and the connection stays open when the limit is hit
- At most 100 ids per unsubscribe batch
- At most 64 open connections per project user on one worker, also
  enforced when in-band authentication switches the user; guests stay
  under the per-IP abuse limit

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. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Auth-vs-close race permanently leaks a connection slot — Realtime.php:452

This PR introduces APP_LIMIT_REALTIME_CONNECTIONS and APP_LIMIT_REALTIME_SUBSCRIPTIONS (plus the existing array-size cap) to bound per-user realtime usage. The Swoole realtime entrypoint now tracks connection counts per user via addConnection/removeConnection on the Realtime messaging adapter, rejects connections over the per-user cap with a policy close code, and validates subscribe/unsubscribe payloads for channel and query batch sizes. The authentication handler re-checks limits after re-auth and moves the connection between user counters. Validators enforce the limits with close codes 1003/1008 consistent with app/config/errors.php. Coverage is added at both layers: e2e tests exercising the connection limit over real WebSockets and unit tests for the payload validators and counter accounting.

Files Change
app/init/constants.php Adds APP_LIMIT_REALTIME_CONNECTIONS and APP_LIMIT_REALTIME_SUBSCRIPTIONS constants.
app/realtime.php Enforces the per-user connection limit at connect time and removes counts on close.
src/Appwrite/Messaging/Adapter/Realtime.php Adds per-user connection counter accounting (addConnection/removeConnection) with guest exemption.
src/Appwrite/Realtime/Message/Handlers/*.php Subscribe handler enforces the subscription limit; Authentication handler re-checks limits and moves counters on re-auth.
src/Appwrite/Realtime/Message/Validators/*.php New subscribe/unsubscribe payload validators capping channels and queries batch sizes.
tests/e2e/Services/Realtime/*.php E2E coverage of the per-user connection limit over real WebSocket connections.
tests/unit/**/*.php Unit tests for the payload validators and connection counter accounting.

Reviewed commit: 468758b

@ghost

ghost commented Oct 26, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

No unresolved issues were found in the incremental changes; the earlier aggregate-query concern is addressed by replacing query groups across channels for a reused subscription ID.

Caps realtime subscriptions, channels, queries, and open connections, with per-connection limits configurable through environment variables. Adds per-project guest connection quotas keyed by client IP and a project policy to deny guest subscriptions while allowing guests to authenticate on an existing connection. Adds response models, API documentation metadata, compose configuration, and unit and end-to-end coverage for these behaviors.

Latest changes: The newest commits make subscription, channel, and query limits configurable, add guest connection quotas and the deny-realtime-guests project policy, and update related API models and tests.

Verdict New comments Fixed Still open
✅ Approved 0 1 0
📂 Walkthrough · 20
File Change
app/init/constants.php, app/config/variables.php, docker-compose.yml, apps/console/src/lib/docs/compose-generator/composeData.ts Defines configurable realtime subscription, channel, and query limits and exposes them through deployment configuration.
app/realtime.php, src/Appwrite/Messaging/Adapter/Realtime.php Enforces connection and subscription limits, tracks user and guest connection ownership, and carries limits through connection rebuilds.
src/Appwrite/Realtime/Message/Handlers/Authentication.php, src/Appwrite/Realtime/Message/Handlers/Subscribe.php, src/Appwrite/Realtime/Message/Validators/SubscribePayload.php, src/Appwrite/Realtime/Message/Validators/UnsubscribePayload.php Applies message-based limits, updates reused subscription query groups, transfers connection ownership during authentication, and rejects guest subscriptions when policy forbids them.
src/Appwrite/Platform/Modules/Project/Http/Project/Policies/DenyRealtimeGuests/Update.php, src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php, src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php, src/Appwrite/Platform/Modules/Project/Services/Http.php Adds the project policy update endpoint and includes the policy in project policy retrieval and registration.
src/Appwrite/Utopia/Response.php, src/Appwrite/Utopia/Response/Model/PolicyDenyRealtimeGuests.php, src/Appwrite/Utopia/Response/Model/PolicyList.php, app/init/models.php Registers the deny-realtime-guests response model and adds it to the policy response list.
app/config/sdks/parameters.lock.json, tests/e2e/Security/baseline.json Updates SDK parameter locks and the security route baseline for the new project policy endpoint.
tests/e2e/Services/Project/PoliciesBase.php, tests/e2e/Services/Realtime/RealtimeCustomClientTest.php, tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Covers policy updates, guest restrictions and connection caps, and message-based subscription limit boundaries.
tests/unit/Messaging/MessagingTest.php, tests/unit/Realtime/Message/Validators/SubscribePayloadTest.php, tests/unit/Realtime/Message/Validators/UnsubscribePayloadTest.php Tests adapter connection ownership and query/channel limits, plus subscribe and unsubscribe payload validation.
app/init/constants.php Defines the realtime subscription and connection limits.
app/realtime.php Checks connection and URL channel limits, and releases connection counts on close.
src/Appwrite/Messaging/Adapter/Realtime.php Tracks per-user connection counts and limits URL subscription and query construction.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Transfers a connection's count when its authenticated user changes.
src/Appwrite/Realtime/Message/Handlers/Subscribe.php Checks aggregate channels and subscriptions before mutating realtime state.
src/Appwrite/Realtime/Message/Validators/SubscribePayload.php Validates message subscription, channel, and query payload sizes.
src/Appwrite/Realtime/Message/Validators/UnsubscribePayload.php Caps unsubscribe batch size.
tests/e2e/Services/Realtime/RealtimeCustomClientQueryTestWithMessage.php Exercises message-based subscription and unsubscribe limits.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Exercises per-user connection and URL channel limits.
tests/unit/Messaging/MessagingTest.php Covers adapter subscription limits and connection-count tracking.
tests/unit/Realtime/Message/Validators/SubscribePayloadTest.php Covers subscription, channel, and query payload validation boundaries.
tests/unit/Realtime/Message/Validators/UnsubscribePayloadTest.php Covers unsubscribe payload size validation.
✅ Fixed since the last review · 1
  • [minor] Aggregate query limits for reused subscription IDs · src/Appwrite/Realtime/Message/Validators/SubscribePayload.php:73

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

@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.

ghost
ghost previously requested changes Oct 26, 2026

@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

Comment thread app/realtime.php Resolved
- Subscribing again with an existing id adds its channels, so the
  per-subscription channel limit now applies to the merged set
- The subscription limits are checked on fresh state after the tail
  lookups, which can yield, so concurrent messages cannot both pass
- URL subscriptions and queries are counted in constructSubscriptions
  before any query is parsed

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

@luxor-code-review luxor-code-review Bot 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.

Adds per-user realtime connection and subscription limits enforced at connect and subscribe time, with matching validators and e2e/unit coverage.

Key findings

  • 🟡 Auth-vs-close race permanently leaks a connection slot — Realtime.php:452

@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

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

Metric Before After Change
🚀 Requests/sec 187.86 190.74 ⚪ +1.5%
⏱️ Latency P50 90.8 ms 90.96 ms ⚪ +0.2%
⏱️ Latency P95 217.11 ms 207.87 ms ⚪ -4.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 90.96 207.87 12,084 190.74 -9.24
Account 169.9 322.43 636 10.52 +3.45
TablesDB 88.1 164.09 6,572 106.27 -18.23
Storage 85 187.54 3,180 53.07 -6.32
Functions 123.3 241.31 1,696 28.95 +10.05

Top API waits (after)

API request Max wait (ms)
account.prefs.update 497.45
account.name.update 421.86
functions.variables.update 379.56
functions.variables.create 376.59
account.get 338.99

@ghost
ghost dismissed their stale review October 26, 2026 06:04

The findings that requested changes are resolved. See the summary comment for what is still open.

onOpen and the authentication handler yield on lookups before counting
the connection. If the socket closed meanwhile, onClose had already
released it and the late count leaked a slot. onOpen now skips sockets
that are no longer established, and authentication rejects a connection
whose entry onClose has dropped.

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

The websocket client connects on its first receive, so the close helper
saw a disconnected client and returned no frames. Also applies Rector's
generator data providers and string casts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ArnabChatterjee20k and others added 2 commits October 26, 2026 12:34
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]>
ArnabChatterjee20k and others added 2 commits October 26, 2026 13:11
Guests were not counted, so the per-user cap could be skipped by not
signing in. Guest connections are now counted per IP, or per IPv6 /64,
per project on one worker, with a higher cap than a user since many
people can share one address. Signing in moves the count from the
address to the user.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The subscription, channel and query totals per connection now come from
the plan's realtimeSubscriptions, realtimeChannels and realtimeQueries,
falling back to the defaults. Self-hosted has no plan, so nothing
changes there. The limits are resolved once when the connection opens
and kept on it, including across in-band authentication and permission
changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ArnabChatterjee20k and others added 3 commits October 26, 2026 13:44
New project policy deny-realtime-guests. When enabled, a guest that
opens a connection with channels is refused, and a guest subscribe
message is refused while the connection stays open, so cookie-less web
clients can still sign in over the connection and then subscribe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ArnabChatterjee20k and others added 5 commits October 26, 2026 13:49
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]>
…limits

# Conflicts:
#	tests/unit/Messaging/MessagingTest.php
ArnabChatterjee20k and others added 8 commits October 26, 2026 13:52
The guest cap test closes 128 connections at once, and those closes can
hold up new connections for a few seconds, past the default 2s read
timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
_APP_LIMIT_REALTIME_SUBSCRIPTIONS, _APP_LIMIT_REALTIME_CHANNELS and
_APP_LIMIT_REALTIME_QUERIES set the defaults, falling back to 100, the
same way _APP_LIMIT_DATABASE_BATCH works. A plan still overrides them
on Cloud.

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

Authentication rebuilds a connection from its subscriptions. A
connection with none, such as a cookie-less client that connects,
signs in and only then subscribes, lost its project, roles and user,
so its next subscribe ran as a guest. Record them the same way the
permission-change path already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The realtime limits now come from the environment, so the tests read
the same constants instead of assuming 100. Cloud CI can then lower
them to match a plan and run the CE suite as is. The URL path also
checks its channel list against the connection's channel total rather
than a fixed 100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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

…tion-limits

# Conflicts:
#	src/Appwrite/Messaging/Adapter/Realtime.php
@pkg-pr-new

pkg-pr-new Bot commented Oct 27, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/appwrite/appwrite/@appwrite.io/console@14945

commit: 916bc62

@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

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 90fbb27 into main Oct 27, 2026
74 of 75 checks passed
ArnabChatterjee20k added a commit that referenced this pull request Oct 28, 2026
The pkg.vc build predates Videos, so the console no longer built, and
lint:sdk-pins refuses pkg.vc on main. Pins the pkg.pr.new build of #14945
instead, rewords the guests card for connections that list channels, and
adds a mocked e2e spec for the Realtime policies tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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