Skip to content

fix(realtime): close realtime connections that go silent - #15059

Merged
HarshMN2345 merged 10 commits into
mainfrom
feat-realtime-presence
Oct 28, 2026
Merged

HarshMN2345 merged 10 commits into
mainfrom
feat-realtime-presence

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

A presence row counts the realtime sockets holding it (connections, from #14606) and is deleted when the last one closes. A client that went away without its close reaching the server (lost network, suspended device) left a socket that never reached onClose, so its user stayed online until expiresAt, 30 days later.

The realtime server now sets Swoole heartbeat_check_interval: 30 and heartbeat_idle_time: 120. Every SDK sends {"type":"ping"} every 20 seconds, so a connection silent for two minutes has lost its client; Swoole closes it and onClose releases its presence and sends the delete event as usual. Two minutes leaves room for background tabs whose timers browsers throttle to one a minute.

A client that never sends anything (a hand-written WebSocket client that only listens) is now closed after two minutes; it has to ping like the SDKs do.

A realtime server that crashes or is killed still runs no onClose; its sockets' holds stay counted until expiresAt, as before.

Test plan

  • Ping intervals checked in the web, React Native, Flutter, Android and Apple SDK templates (20 seconds each).
  • CI.

Part of #14343

…nce holds

Swoole now closes a connection that sends nothing for two minutes, so
onClose releases its presence after a lost network. Each realtime server
records the presence holds its sockets count, per run, and releases the
ones its previous run left behind when it starts again.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 4 high · 🟡 1 medium

💬 Inline comments (5)

  • 🟠 Worker death or reload leaks holds under shared boot — State.php:254
  • 🟠 Presence hold recovery keyed to unstable hostname — realtime.php:314
  • 🟠 Orphan hold purged before its release, lost on failure — State.php:263
  • 🟠 onClose forgets hold before release, failures strand counts — realtime.php:1657
  • 🟡 Orphaned-hold cleanup is single-shot with no retry — realtime.php:445
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Presence hold recorded after counted upsert (Presence.php:147) — In src/Appwrite/Realtime/Message/Handlers/Presence.php:147-149 the hold is recorded via recordHold only after the counted presence upsert at line 108, and recordHold swallows any cache failure (src/Appwrite/Presences/State.php:234).

The change introduces a presence "hold" artifact so a restarted realtime worker can release presence rows left by a crashed predecessor, plus Swoole heartbeat detection and cleanup reordering in onClose. Several ordering and identity issues break that guarantee.

Files Change
src/Appwrite/Presences/State.php New hold record/forget/takeOrphanedHolds cache layer keyed by hostname, purging holds before release
app/realtime.php Boot-time one-shot orphan cleanup timer, hold recording in connect flow, onClose forget-before-release ordering
src/Appwrite/Realtime/Message/Handlers/Authentication.php, .../Presence.php Release previous-user presence on re-auth; record hold after the counted upsert
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Enable 30s/120s Swoole heartbeat check/idle timeouts with reload_async
docker-compose.yml, app/realtime.php (reload settings) Reload configuration interacting with the shared boot identity used by hold cleanup

The hold key derives from gethostname(), which Docker changes on every recreate, so crashed predecessors' holds are never found; the boot id is shared across reloaded workers, so dead workers' holds are indistinguishable from live ones; and both onClose and the orphan sweep purge the hold before releasing, so a failed release strands the count with no recovery record.

Reviewed commit: 7dc3dd7

@ghost

ghost commented Oct 28, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

A worker crash after claiming can permanently lose the recovery record, and previously reported cache failure issues remain open.

Adds Swoole heartbeat checks and a Redis ledger for per-socket presence holds, keyed by server run, worker PID, and connection. Presence updates refresh hold records, while startup cleanup reconciles holds from prior runs and dead workers through the normal presence-release path; close and reauthentication remove the corresponding records. The PR also adds Redis-backed tests for hold ownership, orphan claiming and restoration, and TTL renewal.

Latest changes: The newest commits claim orphan records before releasing them, restore records when cleanup throws, and add Redis-backed tests for claim, restore, and TTL renewal.

Verdict New comments Fixed Still open
💬 Commented 1 3 2

Note

Not approving while a bug finding is open: Keep claimed holds recoverable until release completes

Finding Where
🟡 Keep claimed holds recoverable until release completes src/Appwrite/Presences/State.php:298
Fix with agent prompt
### Issue 1
src/Appwrite/Presences/State.php:298
**Keep claimed holds recoverable until release completes**

If this worker is killed after the purge succeeds but before `releaseConnectionForUser()` runs, the marker is already gone and a later startup pass cannot retry the hold. The same loss occurs if a failed release reaches `restoreOrphanedHold()` and `Cache::save()` returns `false`, since that result is ignored.

### Issue 2
src/Appwrite/Presences/State.php:229-233
**Handle failed cache writes for presence holds**

The Redis cache adapter reports write failures by returning `false` rather than throwing, so this catch does not detect an unavailable cache. The presence counter has already been incremented; if the process then crashes, there is no orphan record to reap and the presence can remain until expiry.

### Issue 3
src/Appwrite/Presences/State.php:242-245
**Do not release a hold when its cache marker remains**

If `purge()` fails or returns `false`, this helper still lets close or reauthentication proceed with the database decrement. The marker can then be treated as an orphan on the next boot and decrement the shared counter a second time, potentially deleting a presence while another socket still holds it.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 6
File Change
app/realtime.php Schedules orphaned-hold cleanup and claims each record before attempting its normal presence release.
src/Appwrite/Presences/State.php Tracks per-socket holds, detects orphan records, claims and restores them, and releases presence connections safely.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Forgets a socket's hold record when its authenticated user changes.
src/Appwrite/Realtime/Message/Handlers/Presence.php Records or refreshes a socket's hold when it sends a presence message.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Configures heartbeat checks and an idle timeout for silent WebSocket connections.
tests/unit/Presences/StateTest.php Adds Redis-backed coverage for hold ownership, orphan claiming and restoration, and TTL renewal.
⏳ Still open from earlier reviews · 2
✅ Fixed since the last review · 3
  • Refresh hold TTL when a live presence is refreshed · src/Appwrite/Presences/State.php:226
  • Add regression coverage for hold TTL refresh · src/Appwrite/Realtime/Message/Handlers/Presence.php:149
  • Prevent concurrent cleanup of the same dead-worker hold · app/realtime.php:449

Merged main (3e79435); no changes to this PR's code since 3d24ca8 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@github-actions

github-actions Bot commented Oct 28, 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 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 src/Appwrite/Presences/State.php Outdated
Comment on lines +229 to +233
$cache->save('presence-holds:' . $this->host, [
'projectId' => $projectId,
'userId' => $userId,
'sequence' => $sequence,
], $this->boot . ':' . $connection);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handle failed cache writes for presence holds

The Redis cache adapter reports write failures by returning false rather than throwing, so this catch does not detect an unavailable cache. The presence counter has already been incremented; if the process then crashes, there is no orphan record to reap and the presence can remain until expiry.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 229-233

Comment:
**Handle failed cache writes for presence holds**

The Redis cache adapter reports write failures by returning `false` rather than throwing, so this catch does not detect an unavailable cache. The presence counter has already been incremented; if the process then crashes, there is no orphan record to reap and the presence can remain until expiry.

---

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

🟡 Minor · error-handling · Reply if this doesn't apply.

Comment thread src/Appwrite/Presences/State.php Outdated
Comment on lines +242 to +245
$cache->purge('presence-holds:' . $this->host, $this->boot . ':' . $connection);
} catch (Throwable $th) {
Span::current()?->setError($th);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Do not release a hold when its cache marker remains

If purge() fails or returns false, this helper still lets close or reauthentication proceed with the database decrement. The marker can then be treated as an orphan on the next boot and decrement the shared counter a second time, potentially deleting a presence while another socket still holds it.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 242-245

Comment:
**Do not release a hold when its cache marker remains**

If `purge()` fails or returns `false`, this helper still lets close or reauthentication proceed with the database decrement. The marker can then be treated as an orphan on the next boot and decrement the shared counter a second time, potentially deleting a presence while another socket still holds it.

---

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

🟡 Minor · error-handling · Reply if this doesn't apply.

Comment thread src/Appwrite/Presences/State.php Resolved

@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 adds presence-hold orphan recovery and Swoole heartbeat handling to the realtime server, but the hold lifecycle leaks permanently online users on worker reload, hostname changes, or failed releases.

Key findings

  • 🟠 Worker death or reload leaks holds under shared boot — State.php:254
  • 🟠 Presence hold recovery keyed to unstable hostname — realtime.php:314
  • 🟠 Orphan hold purged before its release, lost on failure — State.php:263
  • 🟠 onClose forgets hold before release, failures strand counts — realtime.php:1657
  • 🟡 Orphaned-hold cleanup is single-shot with no retry — realtime.php:445

Comment thread src/Appwrite/Presences/State.php Outdated
Comment on lines +254 to +270
public function takeOrphanedHolds(Cache $cache): array
{
$key = 'presence-holds:' . $this->host;
$orphans = [];
// Holds live as long as their socket, so no age makes one stale.
foreach ($cache->loadMany($key, 10 * 365 * 24 * 60 * 60) as $field => $hold) {
if (\str_starts_with((string) $field, $this->boot . ':')) {
continue;
}
$cache->purge($key, (string) $field);
if (\is_array($hold)) {
$orphans[] = $hold;
}
}

return $orphans;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 bug · high

Worker death or reload leaks holds under shared boot

takeOrphanedHolds skips every field prefixed with the current boot (src/Appwrite/Presences/State.php:260), and boot is a single uniqid() created once at file scope in the master process (app/realtime.php:314), inherited by every worker fork — including workers forked by a subsequent reload_async reload. A worker that dies without completing onClose mid-run — an OOM kill, the forced kill after max_wait_time=15 during a reload with reload_async (src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php:23-26), or a failed onWorkerExit sweep — leaves its boot:<connection> holds in place, and a respawned worker 0 re-arms the cleanup with the same boot id, so those holds are indistinguishable from live ones and are never reclaimed. The presence rows those dead sockets count against stay online until the whole master process restarts — the exact leak this cleanup exists to fix.

📋 Prompt for AI Agents

Make orphaned-hold cleanup cover mid-boot worker deaths and reloads. In src/Appwrite/Presences/State.php (lines 223-270), encode the originating worker-generation id (captured at the top of onWorkerStart in app/realtime.php, e.g. boot plus workerId plus a respawn counter, or the worker pid) in the hold field alongside the boot id. In app/realtime.php, extend the one-time boot cleanup (lines 444-481) into a periodic task that also purges holds whose recorded worker generation is no longer running, instead of only skipping the current boot prefix once at startup.

Comment thread app/realtime.php Outdated

$realtime = getRealtime();
$presenceState = new PresenceState();
$presenceState = new PresenceState(host: \gethostname() ?: '', boot: \uniqid());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 bug · high

Presence hold recovery keyed to unstable hostname

Orphaned-hold recovery assumes the next run shares the previous run's key: holds are saved under presence-holds:' . $this->host (src/Appwrite/Presences/State.php:229) and takeOrphanedHolds scans only the current gethostname(), purging and releasing every other field. The shipped appwrite-realtime service in docker-compose.yml sets no hostname:, so Docker assigns a new container-ID hostname on every recreate — including the documented docker compose up -d --force-recreate and any crash replaced as a new container — and the code also falls back to '' when gethostname() fails (app/realtime.php:314), which additionally merges the key across all such servers (and across any two replicas sharing a hostname). After such a restart the new run scans a fresh key, so the crashed run's holds are never released: users stay counted online until the presence row's 30-day expiry, stale fields persist in Redis with no TTL, and a same-hostname sibling's live holds can be cross-released while its sockets are still open.

📋 Prompt for AI Agents

Make the presence-holds: cache key stable per server instance. In docker-compose.yml, add hostname: appwrite-realtime (or an equivalent _APP_REALTIME_HOST env) to the appwrite-realtime service. In app/realtime.php around line 314, replace the \gethostname() ?: '' fallback in the PresenceState constructor with a per-process unique value (e.g. the boot uniqid or hostname plus pid). Without this, PresenceState::takeOrphanedHolds (src/Appwrite/Presences/State.php:254-270) never sees holds recorded by a crashed previous container, leaving users counted online until the 30-day presence expiry.

Comment thread src/Appwrite/Presences/State.php Outdated
if (\str_starts_with((string) $field, $this->boot . ':')) {
continue;
}
$cache->purge($key, (string) $field);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 bug · high

Orphan hold purged before its release, lost on failure

takeOrphanedHolds calls $cache->purge() on each hold (src/Appwrite/Presences/State.php:263) before the caller attempts any release; the worker-0 timer (app/realtime.php:445-479) then runs per-hold releases where a Throwable is swallowed into a span and a top-level takeOrphanedHolds failure path returns with no rescheduling. If the database is unreachable or transiently failing at the 10-second mark, or the process dies mid-loop, the hold is already erased from Redis but the presence row's connections is never decremented — the count leaks permanently with no record left for any later cleanup, and the offline event and usage decrement are skipped.

📋 Prompt for AI Agents

In src/Appwrite/Presences/State.php line 263 and the timer body at app/realtime.php lines 445-479: don't purge a hold inside takeOrphanedHolds before its release is attempted. Return each hold with its cache field name and add a forgetOrphanedHold(Cache $cache, string $field) step the caller invokes only after releaseConnectionForUser returns (success or a definitive no-op); on a thrown error keep the hold in Redis so the cleanup can be retried.

Comment thread app/realtime.php Outdated
Span::add('user.id', $holdUserId);

try {
$presenceState->forgetHold(getCache(), $connection);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 bug · high

onClose forgets hold before release, failures strand counts

In the onClose presence-cleanup coroutine, forgetHold runs as the first act (app/realtime.php:1657) before releaseConnectionForUser (line 1666); if the release throws — DB briefly unreachable, transaction failure — the error is only marked on the span and the cache hold is already gone. The row keeps counting a dead socket with no record anywhere, so not even the next boot's orphan cleanup can release it, and the user stays permanently online with inflated usage. Keeping the hold until the release succeeds (a failed release must leave it recoverable) preserves the recovery artifact this feature depends on.

📋 Prompt for AI Agents

In app/realtime.php inside the onClose presence-cleanup coroutine (lines 1651-1679), reorder so $presenceState->forgetHold(getCache(), $connection) runs only after releaseConnectionForUser completes (whether it returns a document or null) — call it right after the release call at line 1666. Why: if the release throws while the DB is down, an already-forgotten hold leaves the presence row counted forever with no orphan record for the next boot's cleanup to recover.

Comment thread app/realtime.php Outdated
Comment on lines +445 to +451
Timer::after(10000, function () use ($container, $presenceState): void {
try {
$holds = $presenceState->takeOrphanedHolds(getCache());
} catch (Throwable $th) {
Console::error('Realtime orphaned presence holds: ' . $th->getMessage());
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Orphaned-hold cleanup is single-shot with no retry

The boot-time cleanup schedules exactly one Timer::after(10000, ...) that calls takeOrphanedHolds once (app/realtime.php:445-447); if Redis or the console DB is unreachable at that moment, the catch logs and returns, and the holds left by the previous boot are never released for the lifetime of this process — the comment claims release happens "once, after the database is reachable", but nothing actually waits for reachability and there is no re-attempt. Since recordHold stores entries with no TTL (src/Appwrite/Presences/State.php:223-233), users of a crashed predecessor's sockets stay counted online until the next full restart.

📋 Prompt for AI Agents

In app/realtime.php around lines 444-481, replace the one-shot Timer::after(10000, ...) orphan-cleanup with a retried pass: on the catch (Throwable $th) branch around line 449, log and re-arm the same timer (e.g. 10s backoff, capped) instead of returning, so the previous boot's presence holds are eventually released even if the cache or console DB was briefly unreachable at first attempt.

A closing or re-authenticating socket and the restart cleanup now forget a
hold only after releasing it, so a failed release stays recoverable; the
restart cleanup retries every minute until all releases go through. Hold
records expire with the 30-day presence they count on, and a failed write
is recorded on the span.
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → feat-realtime-presence (after).

Metric Before After Change
🚀 Requests/sec 212.96 215.63 ⚪ +1.3%
⏱️ Latency P50 81.4 ms 80.02 ms ⚪ -1.7%
⏱️ Latency P95 186.57 ms 188.84 ms ⚪ +1.2%
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 80.02 188.84 13,680 215.63 +2.27
Account 144.85 278.94 720 12.02 +3.17
TablesDB 76.48 145.04 7,440 118.97 +0.57
Storage 75.74 174.68 3,600 59.34 -21.63
Functions 114.34 230.06 1,920 32.41 +24.96

Top API waits (after)

API request Max wait (ms)
tablesdb.rows.create 524.26
account.name.update 522.6
functions.variables.update 409.29
functions.create 402.06
account.prefs.update 398.64

@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

Comment thread src/Appwrite/Presences/State.php Resolved
…sage

The record then lives as long as the row it counts on, and a failed
write is retried by the next message. Forgetting a released hold retries
a purge that throws, since a record left behind would be released again
on the next restart.
…ut closing

A worker killed by a fatal error runs neither onWorkerExit nor onClose, and
its replacement does not know its sockets. Hold records now carry the
worker's pid, and every starting worker releases this run's holds whose
worker is gone; worker 0 still takes the previous runs' holds. Without a
hostname, holds are not recorded.

@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

@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
Workers starting together see the same records; only the one whose purge
removes a record releases its hold, and a failed release puts the record
back. StateTest covers the hold records against Redis.

@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

Comment thread src/Appwrite/Presences/State.php Outdated
*/
public function claimOrphanedHold(Cache $cache, string $field): bool
{
return $cache->purge('presence-holds:' . $this->host, $field);

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 claimed holds recoverable until release completes

If this worker is killed after the purge succeeds but before releaseConnectionForUser() runs, the marker is already gone and a later startup pass cannot retry the hold. The same loss occurs if a failed release reaches restoreOrphanedHold() and Cache::save() returns false, since that result is ignored.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 298

Comment:
**Keep claimed holds recoverable until release completes**

If this worker is killed after the purge succeeds but before `releaseConnectionForUser()` runs, the marker is already gone and a later startup pass cannot retry the hold. The same loss occurs if a failed release reaches `restoreOrphanedHold()` and `Cache::save()` returns `false`, since that result is ignored.

---

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

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

HarshMN2345 and others added 2 commits October 28, 2026 05:49
Releasing a crashed run's holds exactly once needs an atomic claim the
cache does not offer: forgetting a record before its release can lose a
hold, and after it can release one twice. Keep the heartbeat only.
@HarshMN2345 HarshMN2345 changed the title fix(realtime): close silent sockets and release a crashed run's presence holds fix(realtime): close realtime connections that go silent Oct 28, 2026
@HarshMN2345

Copy link
Copy Markdown
Member Author

@hansi-codes re-review

@HarshMN2345
HarshMN2345 merged commit 626c25b into main Oct 28, 2026
9 checks passed
@ghost

ghost commented Oct 28, 2026

Copy link
Copy Markdown

No findings in the current diff. It only adds Swoole’s heartbeat check interval and idle timeout (Swoole.php). The earlier State.php cache-ledger findings refer to code that isn’t present in this revision.

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