Skip to content

feat(realtime): telemetry for the pub/sub event handler - #15111

Merged
ArnabChatterjee20k merged 2 commits into
fix/realtime-permission-check-capfrom
feat/realtime-pubsub-heartbeat-stacked
Oct 30, 2026
Merged

ArnabChatterjee20k merged 2 commits into
fix/realtime-permission-check-capfrom
feat/realtime-pubsub-heartbeat-stacked

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Issue / Description

Closes #15107. Stacked on #15094.

The realtime pub/sub handler has almost no telemetry of its own. If it keeps reading events from Redis but stops delivering them, the only sign is that realtime.server.arrival_delay and realtime.server.message.sent go flat, and nothing says why. Two places also throw failures away silently: the arrival-delay and delivery-delay catch (\Throwable) {} blocks.

Solution

New instruments, created through the telemetry adapter the same way the MQTT broker's are (mqtt.messages.dropped with a reason, mqtt.messages.failed, …):

Instrument Type Meaning
realtime.server.events.received counter every event the handler is called with
realtime.server.events.dropped counter, reason no_subscriber: nobody on this worker matched; invalid_payload: not a JSON event
realtime.server.events.failed counter, stage an error in that step: arrival, delivery_delay, or whatever step handle() was in when it threw
realtime.server.event.stage observable gauge, stage + workerId seconds the event being handled has spent in its current step (decode, arrival, permissions, deliver, close, tail), 0 when idle

How to read them when delivery stops:

  • events.received flat: nothing is reaching the handler.
  • event.stage climbing: the handler is blocked, and the stage label names the step.
  • events.failed rising: events throw. The stage label shows where; this used to be silent for arrival and delivery delay.
  • events.received rising, events.dropped{reason=no_subscriber} equal to it: events are handled but match nobody on the worker.

The two silent catch blocks still don't stop delivery. They now count the failure.

A payload that isn't a JSON object is now counted and dropped up front, instead of failing further down with a TypeError.

Tests

  • New tests/unit/Realtime/Event/HandlerTest.php, with a named RecordingAdapter and the telemetry Test adapter:
    • an event with no subscribers is counted as received and dropped, and records its arrival;
    • an event with a bad timestamp is counted as failed instead of silently swallowed (this fails on the base branch, which has no such counter);
    • a payload that isn't JSON is counted as dropped;
    • the stage gauge reads 0 with stage=idle after an event.
  • One realtime.event span per event, with project id, event name, result no_subscriber, 0 receivers and resolved_at ≥ arrived_at; no span for a payload that isn't an event.
  • php -l, Pint and Rector on all changed files. I couldn't run PHPUnit locally (no Swoole), so CI's unit job is the first run.

🤖 Generated with Claude Code

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 eventsFailed miscounts: swallowed timestamp errors, double increments (Handler.php:130) — realtime.server.events.failed is incremented for events whose overall handling succeeded: a bad arrival timestamp bumps ['stage' => 'arrival'] in recordArrival's catch (src/Appwrite/Realtime/Event/Handler.php:130), and a bad delivery timestamp bumps ['stage' => 'delivery_delay'] in deliver()'s catch, after which the event is delivered normally.

This PR instruments the realtime subsystem with OpenTelemetry metrics: event arrival, delivery latency, failure, drop and close counters plus an observable gauge reporting the handler's current processing stage and its age, wired into the realtime worker's metrics registry.

Files Change
src/Appwrite/Realtime/Event/Handler.php Adds per-event telemetry counters/histograms, a stage state machine (idle/arrival/delay/delivery/close) with stageSince tracking, and an observable gauge callback registered in the constructor.
app/realtime.php Registers the new OTel instruments (including the stage gauge) via lazy-init closures on worker start and passes them into the handler.
tests/unit/Realtime/Event/HandlerTest.php Updates handler unit tests to assert the new metric observations and stage transitions through the adapter.
tests/unit/Realtime/Event/RecordingAdapter.php Extends the in-memory metrics recording adapter to capture counter/histogram/gauge observations for the updated tests.

Reviewed commit: 86fdf3b

@ghost

ghost commented Oct 30, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

Limited by an open minor finding: Avoid exporting an info span for every pub/sub event

The pub/sub handler now records received, dropped, and failed event metrics, exposes its active processing stage, and reports arrival and delivery-delay failures. It also emits a span for each valid event with its project, event name, result, receiver count, and processing timestamps. Tests cover the metrics, malformed payload handling, idle stage reporting, and span attributes.

Latest changes: The newest commits add per-event spans with project, event, result, receiver-count, and timing attributes, plus a recording exporter and span assertions in the handler tests.

Verdict New comments Fixed Still open
✅ Approved 1 0 0
Finding Where
🟡 Avoid exporting an info span for every pub/sub event src/Appwrite/Realtime/Event/Handler.php:118
Fix with agent prompt
### Issue 1
src/Appwrite/Realtime/Event/Handler.php:118-119
**Avoid exporting an info span for every pub/sub event**

This now finishes an info span for every valid event, and the default exporter in `app/init/span.php` writes spans to stdout with no sampling when trace filters are unset. Since this handler processes the realtime firehose, that creates a log entry per event and can overwhelm log volume and add substantial per-event overhead; the prior failed-event-only span avoided this.

---

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 handler's event metrics and stage gauge.
src/Appwrite/Realtime/Event/Handler.php Tracks event metrics and stages, and adds per-event spans with delivery details.
tests/unit/Realtime/Event/HandlerTest.php Tests event metrics, malformed payload handling, idle gauge state, and span attributes.
tests/unit/Realtime/Event/RecordingAdapter.php Adds a named WebSocket adapter for handler tests.
tests/unit/Realtime/Event/RecordingExporter.php Adds a span exporter that records finished spans for assertions.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Keep malformed event attributes inside the guarded path Verifier: Span::set() would indeed reject arrays before the try, but no reachable producer of those malformed attributes was found. The only realtime-channel publisher is Messaging\Adapter\Realtime::send(), whose projectId parameter is string-typed. Its sole production caller, Event\Realtime::trigger(), supplies events from Event::generateEvents(), which constructs string event names using implode/str_replace. The finding therefore depends on an invented malformed Redis publication rather than an input produced by the repository.

Reviewed the commits since 86fdf3b · 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 30, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix/realtime-permission-check-cap (before) → feat/realtime-pubsub-heartbeat-stacked (after).

Metric Before After Change
🚀 Requests/sec 209.49 206.22 ⚪ -1.6%
⏱️ Latency P50 80.95 ms 84.49 ms ⚪ +4.4%
⏱️ Latency P95 198.33 ms 196.09 ms ⚪ -1.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 84.49 196.09 12,768 206.22 -2.23
Account 151.89 280.99 672 11.15 -4.35
TablesDB 83.04 153.5 6,944 114.39 -8.62
Storage 75.6 182.94 3,360 57.56 +9.03
Functions 114.66 230.75 1,792 31.43 +12.13

Top API waits (after)

API request Max wait (ms)
account.name.update 379.53
functions.create 364.97
account.prefs.update 362.7
functions.variables.create 354.04
account.get 349.1

@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 · Looks good to merge. Summary

Comment on lines +118 to +119
$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 an info span for every pub/sub event

This now finishes an info span for every valid event, and the default exporter in app/init/span.php writes spans to stdout with no sampling when trace filters are unset. Since this handler processes the realtime firehose, that creates a log entry per event and can overwhelm log volume and add substantial per-event overhead; the prior failed-event-only span avoided this.

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

Comment:
**Avoid exporting an info span for every pub/sub event**

This now finishes an info span for every valid event, and the default exporter in `app/init/span.php` writes spans to stdout with no sampling when trace filters are unset. Since this handler processes the realtime firehose, that creates a log entry per event and can overwhelm log volume and add substantial per-event overhead; the prior failed-event-only span avoided this.

---

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

🟡 Minor · 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