Repository navigation
Description
👟 Reproduction steps
- Self-hosted Appwrite 2.5.0 (Postgres adapter, two API nodes, requests sent to both), a table with a
statusand anownercolumn and one row withstatus = "open". - Two clients try to "claim" that row in a transaction, the usual way to build a lock with transactions (the first staged operation registers the row, then a read inside the transaction decides):
POST /tablesdb/transactions- stage a no-op
updateof the row ({"n": 0}) viaPOST /tablesdb/transactions/{id}/operations GET /tablesdb/{db}/tables/{table}/rows/{rowId}?transactionId={id}- if
status == "open": stageupdatewith{"status": "taken", "owner": "<me>"} PATCH /tablesdb/transactions/{id}with{"commit": true}
- Run the two clients at the same time, with the commit of one of them taking a while (it also updates other rows, e.g. 20 to 90 operations on rows that no other client touches).
Script (Python, requests only; probe starts client 2 a fixed time after client 1 begins its commit, burst runs N parallel clients):
"""Minimal reproduction: two transactions both commit a "claim" of the same row (Appwrite 2.5.0, TablesDB).
APPWRITE_ENDPOINT=https://<host>/v1 APPWRITE_PROJECT=<id> APPWRITE_KEY=<server key with databases.write> \
python3 repro.py setup | probe [extra_ops=90] [offset_ms=300] [rounds=10] | burst [clients=10] [extra_ops=20] [rounds=30] | cleanup
"""
import os, sys, threading, time
import requests
EP, PROJECT, KEY = os.environ["APPWRITE_ENDPOINT"], os.environ["APPWRITE_PROJECT"], os.environ["APPWRITE_KEY"]
H = {"X-Appwrite-Project": PROJECT, "X-Appwrite-Key": KEY, "Content-Type": "application/json"}
DB, T = "race", "rows"
def api(method, path, body=None):
r = requests.request(method, EP + path, json=body, headers=H, timeout=120)
return r.status_code, (r.json() if r.text else {})
def setup():
api("POST", "/tablesdb", {"databaseId": DB, "name": DB})
api("POST", f"/tablesdb/{DB}/tables", {"tableId": T, "name": T, "permissions": [], "rowSecurity": False})
for k in ("status", "owner"):
api("POST", f"/tablesdb/{DB}/tables/{T}/columns/string", {"key": k, "size": 32, "required": False})
api("POST", f"/tablesdb/{DB}/tables/{T}/columns/integer", {"key": "n", "required": False})
while any(c["status"] != "available" for c in api("GET", f"/tablesdb/{DB}/tables/{T}")[1]["columns"]):
time.sleep(1)
def create_rows(ids, **data):
for i in range(0, len(ids), 100):
s, j = api("POST", f"/tablesdb/{DB}/tables/{T}/rows", {"rows": [{"$id": x, **data} for x in ids[i:i + 100]]})
assert s in (200, 201, 409), j # 409: row exists from an earlier run
def op(row, data):
return {"action": "update", "databaseId": DB, "tableId": T, "rowId": row, "data": data}
def begin():
return api("POST", "/tablesdb/transactions", {"ttl": 300})[1]["$id"]
def stage(tx, ops):
s, j = api("POST", f"/tablesdb/transactions/{tx}/operations", {"operations": ops})
assert s in (200, 201), j
def commit(tx):
return api("PATCH", f"/tablesdb/transactions/{tx}", {"commit": True})[0] # 200 = committed, 409 = transaction_conflict
def claim(me, row, noise=()):
"""Stage a no-op update first (registers the row, like a lock), read inside the transaction,
claim only if still open, optionally pad the commit with updates to other rows, commit."""
tx = begin()
stage(tx, [op(row, {"n": 0})])
r = api("GET", f"/tablesdb/{DB}/tables/{T}/rows/{row}?transactionId={tx}")[1]
if r["status"] != "open":
api("PATCH", f"/tablesdb/transactions/{tx}", {"rollback": True})
return "skipped (read: taken)"
stage(tx, [op(row, {"status": "taken", "owner": me})] + [op(x, {"n": 1}) for x in noise])
return {200: "COMMITTED", 409: "409 conflict"}.get(commit(tx), "error")
def probe(extra=90, offset_ms=300, rounds=10):
"""Client 1 commits (target row first, then `extra` other rows -> long commit); client 2 starts offset_ms later."""
noise = [f"noise{k}" for k in range(extra)]
create_rows(noise, n=0)
both = 0
for r in range(rounds):
row = f"target{r}"
create_rows([row], status="open", owner="", n=0)
tx1 = begin()
stage(tx1, [op(row, {"status": "taken", "owner": "c1"})] + [op(x, {"n": 1}) for x in noise])
out = {}
t = threading.Thread(target=lambda: out.update(c1=commit(tx1)))
t.start()
time.sleep(offset_ms / 1000)
out["c2"] = claim("c2", row)
t.join()
final = api("GET", f"/tablesdb/{DB}/tables/{T}/rows/{row}")[1]
win = out["c1"] == 200 and out["c2"] == "COMMITTED"
both += win
print(f"round {r+1}: client1={'COMMITTED' if out['c1']==200 else out['c1']} client2={out['c2']} final owner={final['owner']}{' <-- both committed' if win else ''}")
print(f"both clients committed in {both} of {rounds} rounds (expected: 0)")
def burst(clients=10, extra=20, rounds=30):
"""`clients` parallel claims of one row, each padded with `extra` updates to rows of its own."""
noise = {i: [f"b{i}_{k}" for k in range(extra)] for i in range(clients)}
create_rows([x for v in noise.values() for x in v], n=0)
hist = {}
for r in range(rounds):
row = f"burst{r}"
create_rows([row], status="open", owner="", n=0)
res, bar = [None] * clients, threading.Barrier(clients)
def run(i):
bar.wait()
res[i] = claim(f"c{i}", row, noise[i])
ts = [threading.Thread(target=run, args=(i,)) for i in range(clients)]
[t.start() for t in ts]; [t.join() for t in ts]
w = res.count("COMMITTED")
hist[w] = hist.get(w, 0) + 1
print("committed claims per round -> rounds:", dict(sorted(hist.items())), "(expected: only 1)")
if __name__ == "__main__":
a = sys.argv[1:]
{"setup": setup, "cleanup": lambda: api("DELETE", f"/tablesdb/{DB}"),
"probe": lambda: probe(*map(int, a[1:])), "burst": lambda: burst(*map(int, a[1:]))}[a[0]]()APPWRITE_ENDPOINT=... APPWRITE_PROJECT=... APPWRITE_KEY=... python3 repro.py setup, then python3 repro.py probe 90 300 10 and python3 repro.py burst 10 20 30, then python3 repro.py cleanup.
👍 Expected behavior
Exactly one of the two transactions commits. The other gets 409 transaction_conflict, because the row was changed by another transaction after it was staged in this one (the docs, "Handle conflicts": "Appwrite verifies that rows affected by your transaction haven't changed externally since they were staged").
👎 Actual Behavior
Both commits return 200, and the row ends up with the owner of the second one (the first claim is silently overwritten):
round 1: client1=COMMITTED client2=COMMITTED final owner=c2 <-- both committed
round 5: client1=COMMITTED client2=skipped (read: taken) final owner=c1
both clients committed in 8 of 10 rounds (expected: 0)
Measured on a three-server cluster (2 API nodes, Postgres, READ COMMITTED, CPU steal below 6.1 %), 2 runs of 30 rounds per cell, claims spread over both API nodes. Rounds with two winners instead of one (run 1 / run 2), never more than two:
| parallel clients | no extra operations | 20 extra operations | 60 extra operations |
|---|---|---|---|
| 2 | 1 / 0 | 0 / 0 | 1 / 0 |
| 10 | 0 / 0 | 8 / 4 | 4 / 2 |
| 50 | 0 / 0 | 11 / 7 | 9 / 4 |
With one API node only (60 extra operations): 0 / 1 of 30 for 10 clients, 2 / 0 for 50 clients, so it is not clock skew between nodes (measured below 5 ms). The probe run (client 1 commits 91 operations, client 2 starts 300 ms later): both commit in 8 of 10 and 9 of 10 rounds (the result depends on where client 2's start falls inside the commit of client 1).
Cause (code at tag 2.5.0 / utopia-php/database 7.4.2, which composer.lock pins; main pins the same version and has the same lines):
- Every staged operation carries the time it was staged (
$createdAtof thetransactionLogsrow). On commit it is read per operation (Update.phpL252), all operations run in one database transaction (L334) andwithRequestTimestamp()sets it as$this->timestamp(L723). Database::updateDocument()takes$time = DateTime::now()at the start of the operation (L6368), before theSELECT ... FOR UPDATE(L6370). That value becomes$updatedAt(L6543), but it only becomes visible with the databaseCOMMITafter all other operations of the transaction ran.- The conflict check is
$old->getUpdatedAt() > $this->timestamp(L6548), i.e. wall-clock time of the other write against the stage time of this operation. - Sequence: T1 starts committing and stamps the row with
t1. T2 stages its first operation on the row ats2 > t1and reads the row inside the transaction;TransactionState::getDocument(L53-L93) returns the committed state (no snapshot, no lock), which is still the old row, so T2 seesopen. T1 commits. T2 commits, waits for the row lock, reads$updatedAt = t1, andt1 > s2is false. No conflict, although T1's change became visible after T2 staged and read. - The window is
[t1, T1's commit visible]. It grows with the number of operations in the committing transaction, which is why 2 to 10 clients without extra operations almost never show it and 10 to 50 clients with 20 to 60 extra operations do (10 to 30 % of the rounds).
Two checks that work: increment on a counter (all commits applied, no lost update in 120 rounds; every operation locks the row) and a claim row with a deterministic ID created in the same transaction (derived from the row ID and the $updatedAt that was read; 0 of 180 rounds with two winners, the second commit fails with a duplicate). So this affects the "stage, read, decide" pattern that the conflict detection is meant to protect.
🎲 Appwrite version
2.5.0
💻 Operating system
Linux (Debian 12), Docker
🧱 Your Environment
Self-hosted Appwrite 2.5.0, Postgres adapter (READ COMMITTED), utopia-php/database 7.4.2, two API nodes behind Traefik, requests sent directly to the API containers.
💡 Suggested fix
- Do not compare against the wall-clock time of the other write. Record the row's
$updatedAt(or a version/sequence counter) as it is when the first operation on that row is staged (or read inside the transaction), and at commit, underFOR UPDATE, fail with a conflict if the stored value differs. That compares versions of the same row and does not depend on when a concurrent commit stamped its rows. - Document that the first operation per row is the only one checked (
$dependent), and that reads inside a transaction see the committed state without a lock.
👀 Have you spent some time to check if this issue has been raised before?
- I checked and didn't find a similar issue
🏢 Have you read the Code of Conduct?
- I have read the Code of Conduct
Activity
aryanpatil-07 commentedon Oct 14, 2026
Hi team! 👋 I would love to work on this issue.
Understanding & Proposed Approach:
As highlighted in the reproduction report, the race condition occurs because the conflict check relies on comparing wall-clock timestamps (
$old->getUpdatedAt() > $this->timestamp) taken before concurrent writes become visible, creating a window during multi-operation commits where concurrent transactions can overwrite staged claims.Proposed Solution:
$updatedAt(or sequence/version snapshot) when the first operation targeting the row is staged or read within the transaction.SELECT ... FOR UPDATE, verify that the stored$updatedAtmatches the stage-time snapshot. If the value differs (indicating an external modification since staging), fail with a409 transaction_conflict.409).Could you please assign this issue to me so I can proceed with the implementation according to the contributing guidelines? Thank you!
jackeddisciple commentedon Oct 16, 2026
Hey, I'd like to work on this issue. Is someone already working on it, or would it be okay for me to take it up?