Skip to content

fix(realtime): synchronise presence upsert and close - #14597

Closed
ArnabChatterjee20k wants to merge 20 commits into
mainfrom
fix-realtime-presences-refcount
Closed

ArnabChatterjee20k wants to merge 20 commits into
mainfrom
fix-realtime-presences-refcount

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

A user has one presence row (unique userId), but several realtime connections (tabs, devices) can hold it, spread across workers and nodes. Two things went wrong:

  • Closing one connection deleted the shared row while the user's other connections were still open (presences.*.delete fired, user shown offline).
  • A close and a near-simultaneous upsert could interleave, so a close clobbered a presence another connection had just written.

This synchronises the two paths so the row lives exactly as long as a connection holds it, whichever operation runs first.

How it synchronises

A per-user Utopia\Lock\Distributed lock (presence:{project}:{user}) wraps both the upsert and the close, and a soft Redis counter (presence:connections:{project}:{user}) tracks how many connections hold the row:

  • Upsert — under the lock, write the row and, on a connection's first hold, INCR the counter.
  • Close — under the lock, DECR the counter and delete the row (and emit presences.*.delete) only when it reaches zero; otherwise the row stays.

Because both sides take the same lock, counting a new holder can never race a decrement-to-zero, so the outcome is the same no matter which runs first:

  • close-before-upsert → row removed, then re-created by the upsert.
  • upsert-before-close → new holder counted, so the close sees a non-zero count and keeps the row.

The counter arithmetic lives in Presences\State, which takes the Redis handle; the realtime layer only orchestrates the lock. The DB row stays the single source of truth — Redis holds only the lock and the counter, both soft state.

Every holder-leave path feeds the counter, not just socket close, so the count can never drift above the live holders:

  • Close — State::releaseConnection() (lock → decrement → fence → delete at zero).
  • Re-authentication — unsubscribe() clears the connection's holds, so the handler captures them first: a re-auth to the same user carries the holds across, a re-auth to a different user releases the previous user's holds.
  • REST delete — removing the row over HTTP strips it from each holder's in-memory map, so the worker decrements the counter for those holders (counter only — the row is already gone).

Lease safety. The destructive delete is fenced on lock ownership: before deleting, refresh() proves the lease is still held (a token-guarded CAS). If the locked work outran the TTL or the key was evicted, another operation may already own the user, so the delete is skipped and the row left to its expiresAt. Lock contention falls the same way — toward keeping the row — never toward deleting a live one.

Abnormal death (worker OOM/kill) decrements nothing; the row's expiresAt is the intended backstop for that case.

Dead sockets reach the close path too: the Swoole heartbeat_check_interval / heartbeat_idle_time config closes a silently-gone connection (lost network, suspended device), so its onClose decrements like a clean close.

Behaviour

Scenario Result
c1, c2 both hold; c1 closes count 2 → 1, row stays, no event
then c2 closes 1 → 0, delete + presences.*.delete
network loss (no FIN) heartbeat closes the socket → onClose → decrement
close vs upsert interleave serialised by the per-user lock, order-independent
re-auth to a different user previous user's holds released under the lock
REST delete of the row holder counter balanced so a later upsert isn't a phantom holder
lease lost mid-delete delete skipped; row left to expiresAt
worker OOM / kill row reclaimed by expiresAt

Covered by testPresenceCloseKeepsPresenceHeldByAnotherConnection.

Fixes #14342
Fixes #14343

🤖 Generated with Claude Code

HarshMN2345 and others added 18 commits October 12, 2026 22:29
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.
…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.
…ounter

Replaces the cache-backed holder set, the per-worker lease-renewal ticker and
the 180s lease from #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]>
Addresses review findings on the lock + counter:

- Determine the holder and record it inside the lock, so two concurrent
  presence messages on one connection cannot both count the same hold.
- On lock-acquire timeout, upsert still writes the presence but leaves the
  counter and the hold untouched (no unsynchronised count); close leaves the
  row to its expiresAt instead of decrementing and deleting outside the lock.
- Delete the row only on an exact zero count. A negative count means Redis
  lost the key while holders were open, so the row is kept for expiresAt
  rather than deleted out from under a live connection.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Replace the hand-rolled acquire() + try/finally/release() at the upsert
and close sites with withLock(), which handles release itself. Behavior
is unchanged: the contention fallbacks are preserved via catch(Contention).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Before deleting a presence row at zero holders, refresh() to prove the
lease is still held. If the locked work outran the TTL (or the key was
evicted) another operation may already own the user and have re-created
the row, so skip the delete and let expiresAt reclaim it rather than wipe
a live presence.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Drop self-explanatory method comments and compress multi-line rationale
to a single line; the full reasoning lives in the PR description.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Move the close path's lock -> decrement -> fence -> delete into
State::releaseConnection, so the one destructive path lives in one place.
onClose now calls it; the upsert handler shares State's lock key, TTL
constants and attribute stripping. No behaviour change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A REST DELETE strips the presence from each holder's in-memory map, so
those connections' closes can no longer decrement the counter and the
count leaks. removePresenceFromConnections now reports the per-user holders
it stripped, and the realtime worker decrements the counter for them under
the lock (counter only -- the row is already gone).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
unsubscribe() clears the connection's presence map on re-auth, so its
later close could not decrement the counter and the count leaked. The
handler now captures the holds first: a re-auth to the same user carries
them across, and a re-auth to a different user releases the previous
user's holds (decrement, delete at zero, emit delete) under the lock.

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

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

Copy link
Copy Markdown

Review complete. 🟠 2 high

💬 Inline comments (2)

  • 🟠 Stripping one presence releases the connection's whole hold — Realtime.php:278
  • 🟠 Presence handler resurrects closed connection entry — Presence.php:117

This PR introduces multi-connection presence holds: a Redis holder counter plus distributed locking in Presences\State, hold bookkeeping in the Presence and Authentication message handlers, stripping of presences from live connections on delete events, a new two-holder e2e test, and Swoole heartbeat tuning.

Files Change
src/Appwrite/Presences/State.php New distributed-lock and per-user holder counter for presence release, with usage decrement on release
src/Appwrite/Realtime/Message/Handlers/Presence.php, .../Authentication.php Acquire and carry presence holds under lock during subscribe and re-auth
src/Appwrite/Messaging/Adapter/Realtime.php, app/realtime.php Strip presences from live connections on delete events and release stripped-holder counts on close
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php, app/realtime.php Swoole heartbeat idle/check configuration
tests/e2e/Services/Presences/..., tests/unit/Messaging/... Two-holder close e2e coverage and updated unit expectations for the new return shape

Reviewed commit: de20a4e

The REST-delete holder-balancing ran in the pubsub closure, which is
nested in onWorkerStart and had neither $presenceState nor $container in
scope. Thread $presenceState through onWorkerStart and resolve the lock
pool via $register->get('pools'), matching the rest of the file.

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

github-actions Bot commented Oct 16, 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.

Adds multi-holder presence accounting with a Redis-backed hold counter and distributed lock, but two high-severity counter-imbalance bugs can leak presence rows and usage metrics for up to 30 days.

Key findings

  • 🟠 Stripping one presence releases the connection's whole hold — Realtime.php:278
  • 🟠 Presence handler resurrects closed connection entry — Presence.php:117

Comment on lines 278 to +283
unset($this->connections[$connectionId]['presences'][$presenceId]);
$removed++;

$userId = (string) ($connection['userId'] ?? '');
if ($userId !== '') {
$removed[$userId] = ($removed[$userId] ?? 0) + 1;
}

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

Stripping one presence releases the connection's whole hold

The holder counter is incremented once per connection, no matter how many presences that connection holds (firstHold in src/Appwrite/Realtime/Message/Handlers/Presence.php). But removePresenceFromConnections counts one released holder for a connection whenever any presence is stripped from it, without checking whether the connection still holds other presences (src/Appwrite/Messaging/Adapter/Realtime.php:278-283). A connection holding presences A and B loses its whole hold when A is deleted via REST, driving the counter to zero early; on close, releaseConnection decrements again, goes negative, and keeps B's row alive until expiresAt (30 days) with no presences.[presenceId].delete event.

📋 Prompt for AI Agents

In src/Appwrite/Messaging/Adapter/Realtime.php, removePresenceFromConnections (lines 278-283): after unset($this->connections[$connectionId]['presences'][$presenceId]), increment $removed[$userId] only if the connection's 'presences' array is now empty; if other presences remain, the connection still holds one counted hold and must not be released. Update tests/unit/Messaging/MessagingTest.php to cover a connection holding two presences where only one is deleted.

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.

A realtime connection holds at most one presence, so the "A and B" case can't arise. presenceLogs has a unique index on userId (one row per user) and a connection is authenticated as exactly one user, so upsertForUser always resolves to that user's single row — the connection's presences map never holds more than one id. removePresenceFromConnections groups the stripped holders by userId, and each held exactly one presence and incremented the counter once, so the per-user decrement matches the increment. (If the one-row-per-user model were ever dropped, this would need per-presence counting.)

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 architectural claim is worth examining carefully, but it doesn't fully address the original finding.

Even accepting that one connection maps to one user and one presence row, the core counter mismatch remains: firstHold increments the holder count once when a connection subscribes, but the current diff increments $removed[$userId] once for every connection that held the removed presence — which could be multiple connections from the same user (e.g. two browser tabs). More critically, the fix in the diff does not add the guard called for in the original finding: it should only count a connection as 'released' when its presences array becomes empty after the unset. Without that check, a connection that somehow holds more than one presence (or if the one-row assumption is relaxed) would still be over-counted. The diff changes the grouping key from a flat counter to a per-user map, but does not add empty($this->connections[$connectionId]['presences']) as a condition before incrementing.

If the invariant 'one presence per connection' is guaranteed by the data model, please point to where that constraint is enforced (e.g. the unique index or the subscription logic), so the assumption can be validated. Otherwise, the safer fix — checking that presences is empty before counting a released hold — is still needed.

@ghost

ghost commented Oct 16, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

Limited by an open major finding: Do not let a delayed delete event remove a newer hold

Adds distributed per-user locking and Redis holder counts so realtime presence rows remain while any connection holds them, with cleanup integrated into socket close, re-authentication, and REST-delete paths. It also configures websocket heartbeats, groups removed holders by user, and adds coverage for multi-connection presence retention.

Latest changes: The latest commits move the lease refresh to immediately before each row deletion and skip holder registration when the connection disappeared while the upsert was suspended.

Verdict New comments Fixed Still open
💬 Commented 1 0 3
Finding Where
🟡 Clean up an upsert that finishes after its socket closes src/Appwrite/Realtime/Message/Handlers/Presence.php:123
Fix with agent prompt
### Issue 1
src/Appwrite/Realtime/Message/Handlers/Presence.php:123-124
**Clean up an upsert that finishes after its socket closes**

If the first upsert suspends and `onClose` removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.

### Issue 2
app/realtime.php:738
**Do not let a delayed delete event remove a newer hold**

A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.

### Issue 3
src/Appwrite/Realtime/Message/Handlers/Presence.php:127-129
**Do not acknowledge an upsert without tracking its holder**

When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.

### Issue 4
src/Appwrite/Presences/State.php:109
**Keep the lease valid through the database delete**

`refresh()` proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 8
File Change
app/realtime.php Coordinates presence cleanup and holder-counter updates across REST deletes and socket closes.
src/Appwrite/Messaging/Adapter/Realtime.php Returns holder counts grouped by user when removing presence state from connections.
src/Appwrite/Presences/State.php Implements shared presence-holder counters and release operations with lock checks before deletion.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Preserves holds across same-user re-authentication and releases them when the authenticated user changes.
src/Appwrite/Realtime/Message/Handlers/Presence.php Serializes upserts and tracks the connection's initial hold while checking that the connection remains active.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Configures heartbeat timeouts for idle websocket connections.
tests/e2e/Services/Presences/PresenceRealtimeClientTest.php Covers presence retention until the final realtime connection closes.
tests/unit/Messaging/MessagingTest.php Checks that removed presence holders are grouped by user.
⏳ Still open from earlier reviews · 3

Reviewed the commits since 6e8219f · 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 B · See the inline comments. Summary

Comment thread app/realtime.php
$deletedPresenceId,
);
$deletedProjectId = (string) ($event['project'] ?? '');
$strippedHolders = $realtime->removePresenceFromConnections($deletedProjectId, $deletedPresenceId);

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 let a delayed delete event remove a newer hold

A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.

Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 738

Comment:
**Do not let a delayed delete event remove a newer hold**

A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.

---

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

🟠 Major · concurrency · Reply if this doesn't apply.

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.

@hansi-codes what do you think can be a good way of doing this? we are refresh() where delete just giving up if token is changed

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

refresh() fences only the database delete in releaseConnection(); it does not protect this pub/sub cleanup path. Here the event immediately strips the connection’s hold, then schedules the counter decrement separately (app/realtime.php lines 735–745, State.php lines 88–110). The delete event is matched by presence ID alone (Realtime.php lines 296–324), so it can’t distinguish an old delete from a newer hold for the same ID. REST delete also does not take this lock (Delete.php lines 62–84).

I’d make the cleanup generation-aware: include a lifecycle token/revision in the delete event and the connection’s hold, then under the same per-user lock as upsert, strip and decrement only matching holds. Alternatively, under that lock, verify the current row is still absent/the deleted generation is still current before stripping and decrementing. Just putting the strip under the lock is not enough: a delayed event can acquire it after the newer upsert and still remove that hold.

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.

Agreed it's a real race and the pub/sub strip isn't under the lock. In this design it's an uncoordinated cross-system event, so it falls to the expiresAt backstop like the other abnormal paths (worker crash, lock contention): the row is still correctly deleted by the REST call; the only residual is a counter that can drift for the sub-second window where a re-upsert and the delayed event overlap, which expiresAt reclaims.

For full race-freedom the generation-token idea works, or — since HTTP requests already have a lock resource (app/init/resources/request.php) — the REST Delete.php could take the same per-user lock and clear the counter atomically with the row delete, making the pub/sub path strip-only. I can do that to close the window rather than lean on expiry; the tradeoff is added coordination on the REST path vs. a self-healing soft-state drift.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Locking REST Delete and clearing the counter would not close this race: after that lock is released, a new upsert can add a hold for the same presence ID before the old delete event is processed. The pub/sub handler still removes holds by project and presence ID alone (app/realtime.php, Realtime.php), while upsert records that ID as the connection’s hold (Presence.php). If the event also decrements, it can decrement the new counter; if it becomes strip-only, the new hold is still lost and its close cannot release it.

The delete event needs to identify the hold generation it invalidates, and the handler should strip/decrement only matching holds. The REST lock can serialize the row deletion and counter update, but it does not make a delayed event safe by itself. The finding still applies.

Comment on lines +127 to +129
} catch (Contention) {
// On contention, upsert anyway but skip the count and hold so they stay balanced.
return $upsert();

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 acknowledge an upsert without tracking its holder

When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 127-129

Comment:
**Do not acknowledge an upsert without tracking its holder**

When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.

---

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.

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.

Deliberate. On contention we skip the increment and the hold together, so no unsynchronised half-state is written. The timed-out connection isn't tracked, so if a counted holder closes the row can be removed and this connection re-publishes on its next presence message. Contention on a per-user lock around a millisecond op is rare; we take the brief gap over an unlocked increment (the read-modify-write flagged elsewhere).

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 still permits the failure the finding describes: after lock contention, the handler upserts and returns the normal response and event without recording a hold for that connection (Presence.php lines 134–157). If another counted holder then closes, its decrement reaches zero and deletes the row (State.php lines 92–110), even though the contended connection remains live. A later presence message is not guaranteed, so this is more than a brief gap. Please reject or retry the upsert on contention rather than acknowledge it without tracking its holder.

Comment thread src/Appwrite/Presences/State.php Resolved
continue;
}

$dbForProject->getAuthorization()->skip(fn () => $dbForProject->deleteDocument(self::COLLECTION_ID, $presenceId));

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 the lease valid through the database delete

refresh() proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.

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

Comment:
**Keep the lease valid through the database delete**

`refresh()` proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.

---

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.

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.

Tightened in 300a354. The refresh() fence now sits immediately before each deleteDocument (after the read), so ownership is re-proven right before the destructive write rather than before the read. For a single-row delete the read -> refresh -> delete window is sub-millisecond. A token-fenced conditional delete would close the residual gap entirely, but utopia/database doesn't expose one; given the over-retention bias the remaining window fails safe (skip delete -> expiresAt).

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 narrows the race, but the lease is still not guaranteed through the delete. It can expire after refresh() succeeds and before deleteDocument() commits; a new upsert can then acquire the lock, write the row, and have that write removed by the old, unconditional delete (delete path). A slow or suspended database operation means the remaining window is not necessarily sub-millisecond, and this path does not skip the delete if the lease expires during it.

The lock implementation documents this limitation: refresh() proves ownership when it returns, not when a later write commits (Distributed.php). So the delete still needs protection through commit, such as a conditional/fenced delete or another guarantee that the lease cannot expire while it runs.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

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

Metric Before After Change
🚀 Requests/sec 218.19 221.79 ⚪ +1.7%
⏱️ Latency P50 78.95 ms 79.65 ms ⚪ +0.9%
⏱️ Latency P95 178.93 ms 176.78 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 79.65 176.78 13,680 221.79 -2.15
Account 141.52 261.68 720 12.37 -9.42
TablesDB 78.18 146.33 7,440 122.82 -0.33
Storage 71.06 161.7 3,600 61.2 -3.71
Functions 106.84 193.23 1,920 33.39 -3.9

Top API waits (after)

API request Max wait (ms)
account.prefs.update 445.84
account.name.update 432.75
tablesdb.rows.decrement 414.98
storage.buckets.create 358.89
tablesdb.rows.increment 348.76

- Presence upsert: after the (suspending) DB upsert, bail if onClose has
  since removed the connection, so the map write cannot resurrect a dead
  connection entry and leak an un-decrementable holder.
- releaseConnection: move the refresh() fence to immediately before each
  deleteDocument so the lease is re-proven right before the destructive
  step, not before the preceding read.

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

@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 on lines +123 to +124
if (!isset($realtime->connections[$connectionId])) {
return $presence;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Clean up an upsert that finishes after its socket closes

If the first upsert suspends and onClose removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 123-124

Comment:
**Clean up an upsert that finishes after its socket closes**

If the first upsert suspends and `onClose` removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.

---

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

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

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