Repository navigation
fix(realtime): tie presences to live connections - #14398
HarshMN2345 wants to merge 6 commits into
Conversation
A client that lost its network, or a realtime server that was killed, left its presence online: nothing ever closed the connection, and a realtime presence expired only after 30 days. Swoole now closes a connection that sends nothing for 120 seconds (SDKs ping every 20), so the close path deletes its presence as usual. A realtime presence now expires after a 180-second lease that its server renews every minute while the connection is open, so one whose server died expires within the lease.
…olds it A user has one presence, but closing any connection that upserted it deleted it, even while another tab or device of the same user was still connected. Each connection that upserts the presence is now recorded as a holder in the shared cache, so this works across realtime servers. Closing a connection deletes the presence only when no other holder remains. Holders are renewed with the lease, so those of a server that died stop counting.
|
Review complete. 🟠 2 high 💬 Inline comments (2)
The change introduces
Two high-severity issues remain in the release path of Reviewed commit: 1e321fb |
🟢 Tier S · Ready to mergeThis PR configures Swoole heartbeat timeouts and gives realtime presences short, renewable leases. It tracks which connections hold each user's presence in shared cache, keeps the record until the final holder closes, and adds close-time protection against deleting a row rewritten during cleanup. Latest changes: The latest commits register the holder before the upsert, release it if the upsert fails, fence close-time deletion by the row's update time, and add an E2E regression for two connections sharing a presence.
📂 Walkthrough · 5
Merged |
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
This PR adds lease-based presence expiry to the realtime server, with per-connection holder tracking in cache and periodic renewal, but the release path treats a cache outage as an empty holder set and its check-then-delete is non-atomic.
Key findings
- 🟠 Cache outage masquerades as empty holders, deleting live presences — State.php:214
- 🟠 Holder check and presence delete are not atomic — State.php:214
| return !empty($dbForProject->getCache()->loadMany($key, self::LEASE)); | ||
| } catch (\Throwable) { | ||
| return false; | ||
| } |
There was a problem hiding this comment.
🟠 bug · high
Cache outage masquerades as empty holders, deleting live presences
release() treats any empty loadMany result as "no holders" (src/Appwrite/Presences/State.php:214-217): a Redis outage (exception caught, returns false), an open circuit breaker (CircuitBreaker::loadMany returns the [] fallback, packages/cache/src/Adapter/CircuitBreaker.php:58), and a non-Batchable adapter (Cache::loadMany returns [], packages/cache/src/Cache.php:157-159) all look identical to a genuinely empty holder set.
In every case the onClose cleanup proceeds to deleteDocuments('presenceLogs', ...) (app/realtime.php:1576-1586) for a user whose connections on other servers are still open and renewing, so still-connected users appear offline until each client re-sends presence. The safe direction on an unanswerable check is to keep the presence and let the 180s LEASE expiry clean it up.
📋 Prompt for AI Agents
In src/Appwrite/Presences/State.php release() (lines 207-218), change the failure handling so an unanswerable holder check is not conflated with an empty holder set: return a tri-state (e.g. bool|null where null means "cache could not answer") from the catch block and from the non-Batchable/empty-fallback paths, and update the caller in app/realtime.php (~line 1551) so an unknown result skips the deleteDocuments path and leaves the presence to expire via its expiresAt.
There was a problem hiding this comment.
Keeping the fallback to delete. It is the behaviour before this PR, so a cache outage costs no more than today. Keeping the presence instead would leave every clean single-connection close online for up to the 180 s lease with no delete event, and that is the common case. The realtime cache is Sharding over Pool over the Redis adapter, all Batchable and with no circuit breaker, so those two paths do not apply here.
There was a problem hiding this comment.
The argument that the realtime stack is always 'Batchable' and circuit-breaker-free is worth noting, but it is an operational assumption, not a code-level guarantee. The catch block still returns false on any Redis exception (network blip, timeout, connection pool exhaustion), which is indistinguishable from a confirmed empty holder set, and the caller then deletes live presence records. The 'same cost as today' framing also understates the regression: before this PR there was no holder check at all, so a cache failure had no presence-deletion side effect. The safe fix remains returning null on an unanswerable check and skipping deleteDocuments in that case, letting the 180s lease expiry do the cleanup instead.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
…t claimed A connection that upserted the user's presence while another one was closing was recorded as a holder only after its write, so the closing connection could miss it and delete the presence it had just written (4 of 40 runs with the two messages 0-2 ms apart). The upsert now records its holder before writing, and the close path deletes only rows not written since its holder check. A failed write releases the holder again.
| // Hold before writing, so another connection of this user that closes meanwhile | ||
| // either sees this one or deletes only what was written before it. | ||
| $presenceState->hold($database, $project->getId(), $user->getId(), $connectionId); | ||
|
|
||
| try { | ||
| $presence = $presenceState->upsertForUser( | ||
| $database, | ||
| $presenceDocument, | ||
| $presenceId, | ||
| (string) $user->getSequence(), | ||
| function () use ($presenceState, $publisherForUsage, $project): void { | ||
| $presenceState->triggerUsage($publisherForUsage, $project, 1); | ||
| }, | ||
| ); | ||
| } catch (\Throwable $th) { | ||
| if (empty($realtime->connections[$connectionId]['presences'])) { | ||
| $presenceState->release($database, $project->getId(), $user->getId(), $connectionId); | ||
| } | ||
|
|
||
| throw $th; | ||
| } |
There was a problem hiding this comment.
Its kind of a distributed lock right? We can use the lock service that we have if required
There was a problem hiding this comment.
Not exactly. It’s more of a holder set than a lock. We don’t need to block anything here, just know if another connection for the same user is still active. Even if we used the lock service, we’d still need this state to track active connections.
…ounter Replaces the cache-backed holder set, the per-worker lease-renewal ticker and the 180s lease from appwrite#14398 with a per-user distributed lock guarding a soft Redis connection counter: - A `presence:connections:{project}:{user}` counter in Redis tracks how many live connections hold the one presence row per user. First upsert of a connection INCRs it; close DECRs and deletes the row only when it hits zero. - Upsert and close take a `presence:{project}:{user}` Distributed lock, so counting a new holder never races a decrement-to-zero. No DB schema change. - The count is soft state: if Redis loses it the row just lives on until its expiresAt, which returns to +30 days as the crash backstop (OOM/SIGKILL is out of scope again). - The DB row stays the single source of truth; Redis holds only the lock and the counter. State::hold/release/renew, the LEASE constants and the renewal timer are removed. The Swoole heartbeat config is kept so dead sockets still reach onClose. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ounter Replaces the cache-backed holder set, the per-worker lease-renewal ticker and the 180s lease from appwrite#14398 with a per-user distributed lock guarding a soft Redis connection counter: - A `presence:connections:{project}:{user}` counter in Redis tracks how many live connections hold the one presence row per user. First upsert of a connection INCRs it; close DECRs and deletes the row only when it hits zero. - Upsert and close take a `presence:{project}:{user}` Distributed lock, so counting a new holder never races a decrement-to-zero. No DB schema change. - The count is soft state: if Redis loses it the row just lives on until its expiresAt, which returns to +30 days as the crash backstop (OOM/SIGKILL is out of scope again). - The DB row stays the single source of truth; Redis holds only the lock and the counter. State::hold/release/renew, the LEASE constants and the renewal timer are removed. The Swoole heartbeat config is kept so dead sockets still reach onClose. Co-Authored-By: Claude Opus 4.8 <[email protected]>
What does this PR do?
heartbeat_check_interval: 30andheartbeat_idle_time: 120. SDKs ping every 20 seconds, so a connection that sends nothing for two minutes lost its client without a close ever arriving (lost network, suspended device). Swoole closes it andonClosedeletes its presence and sends the delete event as usual. Two minutes leaves room for browsers that throttle background tabs to one timer a minute.sourceis stillrealtime). If a realtime server dies without closing its connections (SIGKILL, OOM, crash), its presences expire within the lease.presence-holders:{projectId}:{userId}in the shared cache, so this works across realtime servers. Closing a connection deletes the presence only when no other holder remains. Holders are renewed with the lease, so those of a dead server stop counting. If the cache cannot answer, the close deletes the presence as before.$updatedAtbefore the check). Without this, an upsert from c2 sent 0-2 ms before c1 closed lost c2's presence in 4 of 40 runs; with it, 0 of 80.testPresenceCloseKeepsPresenceHeldByAnotherConnectioncovers closing one of two connections that hold the presence.Verification
Node WebSocket clients against a local stack, with one or two realtime containers running this branch:
GET200, no event; deleted with one event when c2 closesdocker network disconnect) and killedGET200 after 4 min; still in the DB after 21 min,expiresAt+30 days, no eventGET404 and one delete event at +150 sGET200 after 3 min; still in the DB after 17 minGET404 at +180 s (expired, no event)expiresAtmoves forward every minute, presence deleted on clean closetestPresenceCloseKeepsPresenceHeldByAnotherConnectionfails on main (delete event after the first close).PresenceRealtimeClientTest,PresenceCustomClientTest,PresenceCustomServerTestandPresenceConsoleClientTestpass against this branch, except the two maintenance-expiry tests, which need the Docker socket my test container did not have. Pint and PHPStan pass on the changed files.Fixes #14342
Fixes #14343