Skip to content

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

Closed
ArnabChatterjee20k wants to merge 19 commits into
appwrite:mainfrom
ArnabChatterjee20k:fix-realtime-presences-refcount
Closed

ArnabChatterjee20k wants to merge 19 commits into
appwrite:mainfrom
ArnabChatterjee20k:fix-realtime-presences-refcount

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 14, 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::incrementConnections() / decrementConnections(), which take 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.

Dead sockets reach this 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

Covered by testPresenceCloseKeepsPresenceHeldByAnotherConnection.

Fixes #14342
Fixes #14343

HarshMN2345 and others added 6 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.
@ghost

ghost commented Oct 14, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

Previously reported lock-lease and holder-counter recovery issues remain open.

The PR serializes realtime presence upserts and connection-close cleanup with per-user distributed locks and Redis holder counts, keeping a user's single presence row until its final connection releases it. It also configures Swoole heartbeat detection and balances holder counts when REST deletes remove presence references from realtime connections. The newest change preserves presence holds when a socket reauthenticates as the same user and releases the previous user's holds when identity changes.

Latest changes: The newest commits preserve presence ownership across same-user reauthentication and release the previous user's holds, usage, and delete events when the socket switches identities.

Verdict New comments Fixed Still open
💬 Commented 0 0 4

Note

Not approving while a bug finding is open: The lock can expire during a slow database operation

Fix with agent prompt
### Issue 1
src/Appwrite/Realtime/Message/Handlers/Presence.php:26
**The lock can expire during a slow database operation**

This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.

### Issue 2
src/Appwrite/Presences/State.php:40
**Orphaned counters never expire after a worker crash**

If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.

### Issue 3
src/Appwrite/Presences/State.php:137
**Lock contention drops the REST-delete counter compensation**

If the per-user lock stays busy past `LOCK_TIMEOUT`, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; `expiresAt` only expires the row, not the Redis counter.

### Issue 4
src/Appwrite/Realtime/Message/Handlers/Authentication.php:137-154
**Cover reauthentication while a connection holds presence**

This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.

---

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 Balances counters when REST deletes remove presence references from realtime connections.
src/Appwrite/Messaging/Adapter/Realtime.php Returns stripped presence-holder counts grouped by user.
src/Appwrite/Presences/State.php Implements locked presence release, Redis counter operations, and event/usage helpers.
src/Appwrite/Realtime/Message/Handlers/Authentication.php Carries presence holds across same-user reauthentication and releases them when the user changes.
src/Appwrite/Realtime/Message/Handlers/Presence.php Serializes presence upserts and registers each connection's first hold.
src/Appwrite/Utopia/WebSocket/Adapter/Swoole.php Configures heartbeat timeouts so silent dead connections enter the close path.
tests/e2e/Services/Presences/PresenceRealtimeClientTest.php Exercises realtime presence behavior with multiple connections.
tests/unit/Messaging/MessagingTest.php Checks holder counts returned when realtime presence references are stripped.
⏳ Still open from earlier reviews · 4

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

ghost
ghost previously requested changes Oct 14, 2026

@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 · 1 blocking finding to address. Summary

Comment thread app/config/collections/common.php Resolved
Comment thread app/realtime.php Resolved
@ArnabChatterjee20k
ArnabChatterjee20k force-pushed the fix-realtime-presences-refcount branch from 895b625 to 553d021 Compare October 14, 2026 07:20
@ArnabChatterjee20k ArnabChatterjee20k changed the title Simplify presence liveness: refcount + lock instead of a Redis holder set Tie presences to live connections: lock + Redis counter 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
ArnabChatterjee20k force-pushed the fix-realtime-presences-refcount branch from 553d021 to 81e0b4e Compare October 14, 2026 07:22

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

class Presence extends Action
{
public const int LOCK_TTL = 10;

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 lock can expire during a slow database operation

This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.

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

Comment:
**The lock can expire during a slow database operation**

This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.

---

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.

Addressed by fencing the destructive step on lease ownership rather than sizing the TTL to the worst case.

Before deleting a presence at zero holders, the close now calls $lock->refresh() — a token-guarded CAS. If it returns false (the locked work outran the TTL, or the key was evicted) we skip the delete and let expiresAt reclaim the row, instead of wiping a presence another operation may already own. The locked section is a single DECR plus a single-row get/delete — milliseconds against a 10s TTL — so a lapse is a degraded-DB edge, and the fence makes that edge fail toward over-retention, never a wrong delete.

We deliberately did not add a background refresh/watchdog (that pattern is for minutes-long holds); the inline fence is sufficient here. (commit 4f68d76)

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 does not fully close the lease-expiry race. refresh() extends the Redis lease once; it does not fence the database writes that follow it (lock refresh, close path). If the get/delete work outlasts that refreshed TTL, another upsert can acquire the lock and write the presence before the old close’s delete completes, leaving an active connection without its row.

The upsert path also performs its database write and counter increment without refreshing or checking lease ownership (upsert path). So the 10-second slow-operation case is still possible; this finding remains open.

@ArnabChatterjee20k
ArnabChatterjee20k changed the base branch from fix-realtime-presences to main October 14, 2026 07:24
@ArnabChatterjee20k ArnabChatterjee20k changed the title Tie presences to live connections: lock + Redis counter fix(realtime): synchronise presence upsert and close Oct 14, 2026

@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 C · See the inline comments. Summary

// Counts a connection as a holder of the user's presence.
public function incrementConnections(\Redis $redis, string $projectId, string $userId): void
{
$redis->incr(self::getConnectionCounterKey($projectId, $userId));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Orphaned counters never expire after a worker crash

If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.

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

Comment:
**Orphaned counters never expire after a worker crash**

If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.

---

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.

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

@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
@ghost
ghost dismissed their stale review October 14, 2026 07:35

The findings that requested changes are resolved. See the summary comment for what is still open.

ArnabChatterjee20k and others added 8 commits October 15, 2026 17:09
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]>

@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

try {
$lock->withLock(fn () => $this->decrementConnectionsBy($redis, $projectId, $userId, $count), timeout: self::LOCK_TIMEOUT);
} catch (Contention) {
// On contention, let the counter drift; the row is already gone and expiresAt covers it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Lock contention drops the REST-delete counter compensation

If the per-user lock stays busy past LOCK_TIMEOUT, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; expiresAt only expires the row, not the Redis counter.

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

Comment:
**Lock contention drops the REST-delete counter compensation**

If the per-user lock stays busy past `LOCK_TIMEOUT`, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; `expiresAt` only expires the row, not the Redis counter.

---

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.

@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 +137 to +154
if (!empty($presences) && !empty($projectId) && $projectId !== 'console') {
if ($previousUserId === $user->getId()) {
if (isset($realtime->connections[$connectionId])) {
$realtime->connections[$connectionId]['presences'] = $presences;
}
} else {
$this->releasePreviousHolds(
$pools,
$presenceState,
$database,
$publisherForUsage,
$queueForEvents,
$queueForRealtime,
$project,
(string) $projectId,
(string) $previousUserId,
\array_keys($presences),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cover reauthentication while a connection holds presence

This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.

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

Comment:
**Cover reauthentication while a connection holds presence**

This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.

---

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

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

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Superseded by #14597, which is the same change on a branch in this repo (so CI runs there) and carries the CI fix plus the latest main. Continuing review there.

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