Skip to content

fix(realtime): tie presences to live connections - #14398

Closed
HarshMN2345 wants to merge 6 commits into
mainfrom
fix-realtime-presences
Closed

HarshMN2345 wants to merge 6 commits into
mainfrom
fix-realtime-presences

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

  • Dead connections close. The realtime server now sets Swoole heartbeat_check_interval: 30 and heartbeat_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 and onClose deletes its presence and sends the delete event as usual. Two minutes leaves room for browsers that throttle background tabs to one timer a minute.
  • Realtime presences are leased. A realtime presence now expires 180 seconds after it is written instead of after 30 days. Every realtime worker renews the lease every 60 seconds for the presences its open connections hold (one bulk update per project, only for rows whose source is still realtime). If a realtime server dies without closing its connections (SIGKILL, OOM, crash), its presences expire within the lease.
  • A presence stays while another connection of its user holds it. Each connection that upserts a presence is recorded as a holder under 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.
  • No race between a close and an upsert. The upsert records its holder before writing (and releases it again if the write fails), and the close path deletes only rows not written since its holder check ($updatedAt before 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.
  • testPresenceCloseKeepsPresenceHeldByAnotherConnection covers 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:

Scenario main this branch
User has connections c1 and c2, both upsert, c1 closes (same server) presence deleted, delete event GET 200, no event; deleted with one event when c2 closes
Same, c1 and c2 on different realtime servers not run (one main server) same as above, in both close orders
Client container upserts, then is cut off the network (docker network disconnect) and killed GET 200 after 4 min; still in the DB after 21 min, expiresAt +30 days, no event GET 404 and one delete event at +150 s
Realtime container SIGKILLed and restarted while holding a presence GET 200 after 3 min; still in the DB after 17 min GET 404 at +180 s (expired, no event)
Healthy client pinging every 20 s, otherwise idle, for 6 min – connection stays open, expiresAt moves forward every minute, presence deleted on clean close

testPresenceCloseKeepsPresenceHeldByAnotherConnection fails on main (delete event after the first close). PresenceRealtimeClientTest, PresenceCustomClientTest, PresenceCustomServerTest and PresenceConsoleClientTest pass 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

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.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 2 high

💬 Inline comments (2)

  • 🟠 Cache outage masquerades as empty holders, deleting live presences — State.php:214
  • 🟠 Holder check and presence delete are not atomic — State.php:214

The change introduces Appwrite\Presences\State, a lease-backed presence registry used by the realtime worker: connections hold presence documents in cache keyed by holder identity, a recurring timer renews leases, and connection close releases held presences.

Files Change
src/Appwrite/Presences/State.php New lease registry: hold/release/renew track holders per presence with per-field TTL envelopes in cache and purge stale holders.
src/Appwrite/Realtime/Message/Handlers/Presence.php Presence message handler integrated with the new state registry.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Swoole WebSocket adapter hooks for presence lifecycle (hold on connect/update, release on close).
app/realtime.php Realtime worker wiring: registers the presence renewal timer and passes the registry to connection callbacks.

Two high-severity issues remain in the release path of State.php: a cache outage is conflated with an empty holder list (deleting live presences), and the holder check plus presence delete is not atomic.

Reviewed commit: 1e321fb

@ghost

ghost commented Oct 12, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

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

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 5
File Change
app/realtime.php Renews leases for active realtime connections and uses holder-aware, update-time-fenced close cleanup.
src/Appwrite/Presences/State.php Defines presence lease durations and shared-cache holder registration, release, and renewal.
src/Appwrite/Realtime/Message/Handlers/Presence.php Applies realtime lease expiry and registers a connection as a holder before upserting.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Configures Swoole heartbeat and idle-timeout settings.
tests/e2e/Services/Presences/PresenceRealtimeClientTest.php Covers realtime presence lifecycle, including retention while another connection holds the presence.

Merged main (b509020); no changes to this PR's code since 81f1c85 · 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 A · Looks good to merge. Summary

@github-actions

github-actions Bot commented Oct 12, 2026 •

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.

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

Comment on lines +214 to +217
return !empty($dbForProject->getCache()->loadMany($key, self::LEASE));
} catch (\Throwable) {
return false;
}

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

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread src/Appwrite/Presences/State.php Resolved
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-realtime-presences (after).

Metric Before After Change
🚀 Requests/sec 221.93 215.96 ⚪ -2.7%
⏱️ Latency P50 78.08 ms 81.48 ms ⚪ +4.4%
⏱️ Latency P95 181.77 ms 182.18 ms ⚪ +0.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 81.48 182.18 13,623 215.96 +0.41
Account 145.25 254.62 717 12.02 -5.8
TablesDB 77.45 131.94 7,409 119.95 -17.87
Storage 80.19 166.03 3,585 59.49 +9.12
Functions 116.39 224.42 1,912 32.48 +17.14

Top API waits (after)

API request Max wait (ms)
functions.variables.update 469.26
functions.create 441.68
account.name.update 437.6
functions.variables.create 361.32
tablesdb.rows.create 352.81

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

@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

Comment on lines +93 to +113
// 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;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Its kind of a distributed lock right? We can use the lock service that we have if required

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

ArnabChatterjee20k added a commit to ArnabChatterjee20k/appwrite that referenced this pull request Oct 14, 2026
…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]>
ArnabChatterjee20k added a commit to ArnabChatterjee20k/appwrite that referenced this pull request Oct 14, 2026
…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]>
@HarshMN2345

Copy link
Copy Markdown
Member Author

Superseded by #14606 and #14661, which are on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants