Skip to content

fix(realtime): detect dead presence sockets via heartbeat + boot reconciliation - #14661

Merged
ArnabChatterjee20k merged 5 commits into
fix-realtime-presence-connections-counterfrom
fix-realtime-dead-connection-heartbeat
Oct 21, 2026
Merged

ArnabChatterjee20k merged 5 commits into
fix-realtime-presence-connections-counterfrom
fix-realtime-dead-connection-heartbeat

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Stacked on #14606 (per-socket presence counter) — base branch fix-realtime-presence-connections-counter. Review/merge that first.

Issue

Fixes #14343 — a realtime presence stays "online" for days after a silent network loss or a realtime crash. Neither the WebSocket adapter nor app/realtime.php sets a Swoole heartbeat or TCP keepalive, so a client that vanishes without a FIN is never detected, onClose never runs, and the row lingers until its 30-day expiresAt.

Solution

  • Heartbeat. The Swoole adapter now sets heartbeat_check_interval = 30 / heartbeat_idle_time = 60. A socket that sends nothing for longer than the idle time is closed by Swoole and runs the normal onClose → releaseConnectionForUser path, so the presence is released and the delete event fires. Clients ping every ~20s (there's a ping→pong handler), well within the idle window, so a live connection is never cut. No extra DB work — only the existing close path, on an actual disconnect. This covers the issue's primary repro (silent network loss).
  • Boot reconciliation (CE). A hard crash (SIGKILL/OOM) fires no onClose, so a dead instance's presence rows linger. On a clean boot every presenceLogs row tagged with this hostname is such an orphan (new connections are only accepted after onStart), so they're deleted across the console and every project, purging the list cache where rows were removed. CE only — a Cloud host is shared across tenants on sharded databases, where a per-host sweep doesn't apply.
  • Expiry stays 30 days. Realtime presence is upserted once per connection and never refreshed, so a short expiry would delete live long-lived connections (the row can't tell a held-but-stale presence from an orphan). With the heartbeat and reconciliation handling the real cases, the expiry stays a long, harmless far backstop.

Alternatives Discovered

  • Per-connection expiry refresh on a ticker. Rejected: hitting the DB on a ticker is a bad idea — realtime connections can be a lot, so the writes scale with connection count.

Known residual

A host that crashes and is replaced by a different hostname (reschedule / autoscale) leaves orphans the same-hostname boot sweep won't catch; those lean on the 30-day expiry. Tightening it needs a cross-container liveness check (against the live-container stats), not a shorter expiry — a follow-up, still no per-connection writes.

ArnabChatterjee20k and others added 2 commits October 19, 2026 15:57
…piry

A silently dead realtime client (network loss, or a peer that vanished without a
FIN) never ran onClose, so its presence lingered until the 30-day expiry
(#14343). Configure Swoole's heartbeat so a socket idle past the
idle time is closed and runs the normal onClose/release path; clients ping every
~20s, well within the window, so live connections are untouched. Shorten the
realtime presence expiry from 30 days to 1 day as the backstop for a hard crash
that fires no onClose at all.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Presence expiresAt never refreshed on live connections — Presence.php:86

This change tightens realtime presence cleanup: presence documents now expire after one day instead of thirty, and the Swoole WebSocket adapter configures heartbeat checking so zombie connections are reaped and their presence holds released.

Files Change
src/Appwrite/Realtime/Message/Handlers/Presence.php Presence upsert now stamps expiresAt as now + 1 day instead of + 30 days.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Adds heartbeat_check_interval / heartbeat_idle_time server config so idle connections are closed, triggering presence cleanup via onClose.

One notable gap: the heartbeat path (ping handler) does not refresh expiresAt, so a connection kept alive purely by pings will have its presence read as offline after one day — expiry acts as a session ceiling rather than a crash backstop.

Reviewed commit: 0b77495

@ghost

ghost commented Oct 19, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

I found no additional actionable issues in the changes since the prior review.

Realtime now closes sockets that exceed Swoole's heartbeat idle window, allowing normal presence cleanup to run, while retaining the 30-day expiry as a backstop. Self-hosted startup also reconciles same-host presence records in the console and project databases and routes deleted records through offline cleanup side effects.

Latest changes: The newest commits add a boot-time $createdAt cutoff, process matching presence records in batches, and invoke the shared offline path after each deletion.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 2
File Change
app/realtime.php Adds self-hosted boot reconciliation for same-host presence records and runs offline usage, cache, and event cleanup for deleted rows.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Sets Swoole heartbeat checks so idle sockets are closed and enter the normal disconnect cleanup path.

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

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

Shortens the realtime presence record expiry from 30 days to 1 day and adds a Swoole heartbeat timer so dead WebSocket connections are closed and their presence rows cleaned up.

Key findings

  • 🟡 Presence expiresAt never refreshed on live connections — Presence.php:86

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

A hard crash fires no onClose, so a dead instance's presence rows linger until
expiry. On a clean boot every presenceLogs row tagged with this hostname is such
an orphan (new connections are only accepted after onStart), so delete them
across the console and every project, purging the list cache where rows were
removed. CE only -- a Cloud host is shared across tenants on sharded databases,
where a per-host sweep does not apply (#14343).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix-realtime-presence-connections-counter (before) → fix-realtime-dead-connection-heartbeat (after).

Metric Before After Change
🚀 Requests/sec 218.23 221.1 ⚪ +1.3%
⏱️ Latency P50 77.12 ms 78.04 ms ⚪ +1.2%
⏱️ Latency P95 191.87 ms 181.62 ms 🟢 -5.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 78.04 181.62 13,680 221.1 -10.24
Account 143.15 291.18 720 12.4 +4.09
TablesDB 76.72 148.4 7,440 123.47 +10.81
Storage 69.37 157.25 3,600 60.96 -14.09
Functions 110.42 217.24 1,920 33.13 -36.93

Top API waits (after)

API request Max wait (ms)
account.prefs.update 433.5
account.name.update 414.38
functions.create 406.02
functions.variables.delete 335.8
tablesdb.rows.create 331.7

@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

Comment thread app/realtime.php Resolved
Comment thread app/realtime.php Resolved
Realtime presence is upserted once per connection and never refreshed (a per-ping
refresh is a DB write per connection, which doesn't scale). So a short expiry
deletes live long-lived connections, since the row can't tell a held-but-stale
presence from an orphan. #14343's real cases are handled without the expiry --
the heartbeat closes silently-dead sockets and boot reconciliation clears
same-host crash orphans -- so the expiry stays a long, harmless far backstop.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ArnabChatterjee20k ArnabChatterjee20k changed the title fix(realtime): detect dead presence sockets via heartbeat; shorten expiry fix(realtime): detect dead presence sockets via heartbeat + boot reconciliation Oct 19, 2026
…ffline

Addresses two review findings on the hostname sweep:

- Race: the detached go() runs while the server accepts connections, so a fresh
  presence upserted on this hostname mid-sweep could be deleted as an orphan.
  Capture a `$since` at boot and only sweep rows created before it; anything a
  live connection writes during the sweep is created after `$since` and left
  alone.
- Side effects: the raw bulk delete bypassed the offline path, so usage was not
  decremented and no delete event reached other workers. Each orphan is now
  deleted individually and run through triggerPresenceDeleted (usage -1 + the
  presences.[presenceId].delete event), resiliently per row.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 5d0b547 into fix-realtime-presence-connections-counter Oct 21, 2026
69 checks passed
ArnabChatterjee20k added a commit that referenced this pull request Oct 21, 2026
…nection-heartbeat"

This reverts commit 5d0b547, reversing
changes made to 5f8f6c3.
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