Skip to content

fix(messaging): bound worker memory per push batch - #14438

Merged
ChiragAgg5k merged 2 commits into
mainfrom
fix/messaging-memory-bound
Oct 13, 2026
Merged

ChiragAgg5k merged 2 commits into
mainfrom
fix/messaging-memory-bound

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Since #14238, a push to a large FCM topic actually sends to every token. Each 5,000-token batch now holds a lot of memory, and fra1 worker-messaging was OOMKilled at 512Mi twice (2026-10-12 ~21:37 and 2026-10-13 ~09:37 UTC). Both kills happened during back-to-back pushes of about 12.6k tokens, when two of them overlapped in one worker process. Between pushes, the pod sat at about 445 of 512 MiB.

This change keeps a batch's memory to the requests in flight, instead of growing with the number of recipients:

before: page of 5000 docs ─▶ 5000 bodies ─▶ 5000 PSR-7 requests ─▶ 5000 results (bodies + headers) ─▶ Response
after:  page of 5000 ids  ─▶ 5000 bodies ─▶ 25 requests in flight ─▶ onResult ─────────────────────▶ Response
Change Where
Build each request when a worker coroutine sends it, not all up front (each request held its own php://temp stream) Adapter::requestMulti()
Optional onResult callback that receives each result as it completes, so results are not kept. Without it, requestMulti() still returns every result in request order. Adapter::requestMulti()
FCM and APNS build their Response through onResult FCM, APNS
Free the subscriber page before fetching targets, and the target page before yielding it (both stayed alive through the whole send) Messaging::streamRecipients()

Response results now come back in completion order instead of recipient order. The worker matches results by recipient, so it does not depend on the order.

Benchmark

Setup:

  • The real Messaging::sendExternalMessage() path: streamRecipients → retrySend → FCM adapter → requestMulti.
  • A topic seeded with 12,600 FCM subscribers in Postgres (appwrite/postgres:0.1.0, collections from app/config/collections/common.php).
  • A mock Google OAuth and FCM endpoint with 80 ms latency that returns FCM's response headers.
  • Run in appwrite-dev (Alpine, PHP 8.5, Swoole 6.2, SWOOLE_HOOK_ALL), limited to 1 CPU.
  • Each case is a fresh process with N jobs running as concurrent coroutines, the same as one worker process (_APP_WORKER_MAX_COROUTINES=4).
  • Before and after runs were interleaved, 3 runs each; the table shows medians.
Concurrent 12.6k-token jobs Delivered Wall PHP peak before → after RSS growth at peak before → after RSS kept after the jobs before → after
1 12,600 → 12,600 44 s → 46 s 62 → 24 MB 69 → 30 MB 66 → 7 MB
2 25,200 → 25,200 46 s → 45 s 112 → 36 MB 119 → 41 MB 113 → 24 MB
4 50,400 → 50,400 51 s → 54 s 219 → 58 MB 228 → 67 MB 208 → 39 MB

The process starts at about 65 MB RSS. Peak RSS stayed within ±7 MB across the 3 runs of each case.

Before the change, one process running two overlapping big pushes peaks at about 185 MB and keeps about 180 MB afterwards. With 3 processes per pod, that crosses the 512Mi limit, which matches what fra1 saw. After the change, the same overlap peaks at about 107 MB per process.

Where the remaining memory goes in one 5,000-recipient page, after the change:

Phase PHP heap
Subscribers fetched 10.9 MB
Targets fetched and grouped (was 19.7) 11.8 MB
Bodies built 10.8 MB
All 5,000 sent and Response built (was 27.0) 12.9 MB

Dropping headers from the multi results without the callback saved only about 2 MB per batch, so the result shape is unchanged.

Test Plan

  • bin/monorepo check messaging: Pint, PHPStan and Rector pass
  • bin/monorepo test messaging --linked: 31 tests pass, 7 skipped
  • composer lint and PHPStan on src/Appwrite/Platform/Workers/Messaging.php pass
  • Benchmark above: every case delivered all recipients and set the message status to sent

Related PRs and Issues

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?

Related: #14462

… batch

A 5000-token FCM batch built all 5000 PSR-7 requests (each with its own php://temp stream) before sending, then kept all 5000 results with decoded bodies and header maps until the batch finished. Two overlapping 12.6k-token pushes in one worker process pushed worker-messaging past its 512Mi limit.

requestMulti now builds each request when a worker coroutine sends it, and FCM and APNS take each result through onResult as it completes, so a batch only holds the requests in flight.
streamRecipients kept the page's subscriber and target documents in scope across the yield, so 10k documents stayed alive for the whole send, and the subscriber page was still alive while the target page was fetched.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Non-JSON APNs error body crashes the batch callback — APNS.php:131
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Per-recipient results now arrive in completion order (FCM.php:167) — Moving result aggregation into the onResult callback changes Response::$results ordering from request order to coroutine completion order (previously requestMulti ksorted results before the foreach; now addResult runs inside worker coroutines at packages/messaging/src/Adapter/Push/FCM.php:167-174).

The change replaces batch-result aggregation in the messaging adapter's request pool with a streaming onResult callback, so per-recipient outcomes are surfaced as coroutines finish instead of after the whole batch, and in-flight work is stopped when the callback fails. The APNS and FCM push adapters move their delivered/failed accounting into that callback, and the FCM test fake is updated to mirror the new contract.

Files Change
packages/messaging/src/Adapter.php Rewrites requestMulti into a shared worker pool that invokes an onResult callback per completed request, supports early exit on callback failure, and frees page documents before yield.
packages/messaging/src/Adapter/Push/APNS.php Per-device result handling moved into onResult; aggregates delivered tokens and failure reasons from the streaming callback.
packages/messaging/src/Adapter/Push/FCM.php Same streaming refactor for the FCM fan-out path; response results are collected per recipient as they complete.
packages/messaging/tests/Adapter/Push/FCMTest.php FCM fake now returns an empty array when onResult is set and invokes the callback in request order to match the new adapter contract.
src/Appwrite/Platform/Workers/Messaging.php Adapts the messaging worker's delivery flow to the streaming callback-based requestMulti usage.

Reviewed commit: d9352f8

@ghost

ghost commented Oct 13, 2026

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The callback and bounded-request flow preserve per-recipient delivery accounting, and the recipient generator releases the page data without changing its pagination behavior.

The messaging adapter now builds HTTP requests in bounded worker coroutines and can stream completed results through an optional callback. FCM and APNS use that callback to build their responses incrementally, while recipient streaming releases fetched document pages before yielding them for delivery.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 5
File Change
packages/messaging/src/Adapter.php Builds requests as workers send them and optionally invokes an onResult callback instead of retaining results.
packages/messaging/src/Adapter/Push/APNS.php Accumulates APNS delivery results as each request completes.
packages/messaging/src/Adapter/Push/FCM.php Accumulates FCM delivery results as each request completes.
packages/messaging/tests/Adapter/Push/FCMTest.php Updates the FCM test stub for the callback-capable requestMulti signature.
src/Appwrite/Platform/Workers/Messaging.php Releases subscriber and target document pages before yielding recipient batches.

Reviewed d9352f8 · 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.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • 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.

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

This PR rewrites the shared messaging worker pool in requestMulti to stream per-request results through an onResult callback as they complete, and updates the APNS/FCM push adapters plus the FCM test to the new callback contract.

Key findings

  • 🟡 Non-JSON APNs error body crashes the batch callback — APNS.php:131

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/messaging-memory-bound (after).

Metric Before After Change
🚀 Requests/sec 216.52 224.21 ⚪ +3.6%
⏱️ Latency P50 79.2 ms 77.27 ms ⚪ -2.4%
⏱️ Latency P95 182.13 ms 180.23 ms ⚪ -1%
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 77.27 180.23 13,794 224.21 -1.89
Account 148.42 271.84 726 12.12 +4.33
TablesDB 72.88 128.52 7,502 123.46 -4.43
Storage 75.99 155.56 3,630 62.17 -13.96
Functions 117.91 228.5 1,936 33.99 +3.21

Top API waits (after)

API request Max wait (ms)
functions.variables.update 485.19
functions.create 448.96
account.name.update 446.5
functions.delete 424.77
account.prefs.update 349.18

@ChiragAgg5k
ChiragAgg5k merged commit 03331d8 into main Oct 13, 2026
37 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/messaging-memory-bound branch October 13, 2026 11:52
@ChiragAgg5k ChiragAgg5k self-assigned this Oct 14, 2026
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 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.

2 participants