Repository navigation
fix(realtime): close realtime connections that go silent - #15059
Conversation
…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.
|
Review complete. 🟠 4 high · 🟡 1 medium 💬 Inline comments (5)
🧹 Nitpicks (1) — 🟢 1 low
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
The hold key derives from Reviewed commit: 7dc3dd7 |
🟡 Tier B · Needs changes before merging
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.
Note Not approving while a bug finding is open: Keep claimed holds recoverable until release completes
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
⏳ Still open from earlier reviews · 2
✅ Fixed since the last review · 3
Merged |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
| $cache->save('presence-holds:' . $this->host, [ | ||
| 'projectId' => $projectId, | ||
| 'userId' => $userId, | ||
| 'sequence' => $sequence, | ||
| ], $this->boot . ':' . $connection); |
There was a problem hiding this 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.
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.
| $cache->purge('presence-holds:' . $this->host, $this->boot . ':' . $connection); | ||
| } catch (Throwable $th) { | ||
| Span::current()?->setError($th); | ||
| } |
There was a problem hiding this 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.
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.
There was a problem hiding this comment.
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
- 🟠
onCloseforgets hold before release, failures strand counts — realtime.php:1657 - 🟡 Orphaned-hold cleanup is single-shot with no retry — realtime.php:445
| 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; | ||
| } |
There was a problem hiding this comment.
🟠 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.
|
|
||
| $realtime = getRealtime(); | ||
| $presenceState = new PresenceState(); | ||
| $presenceState = new PresenceState(host: \gethostname() ?: '', boot: \uniqid()); |
There was a problem hiding this comment.
🟠 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.
| if (\str_starts_with((string) $field, $this->boot . ':')) { | ||
| continue; | ||
| } | ||
| $cache->purge($key, (string) $field); |
There was a problem hiding this comment.
🟠 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.
| Span::add('user.id', $holdUserId); | ||
|
|
||
| try { | ||
| $presenceState->forgetHold(getCache(), $connection); |
There was a problem hiding this comment.
🟠 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.
| 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; | ||
| } |
There was a problem hiding this comment.
🟡 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.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
…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.
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.
…t-realtime-presence
| */ | ||
| public function claimOrphanedHold(Cache $cache, string $field): bool | ||
| { | ||
| return $cache->purge('presence-holds:' . $this->host, $field); |
There was a problem hiding this 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.
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.
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.
|
@hansi-codes re-review |
|
No findings in the current diff. It only adds Swoole’s heartbeat check interval and idle timeout ( |
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 reachedonClose, so its user stayed online untilexpiresAt, 30 days later.The realtime server now sets Swoole
heartbeat_check_interval: 30andheartbeat_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 andonClosereleases 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 untilexpiresAt, as before.Test plan
Part of #14343