From 6976f01d7dcbc4bf34ebbe410a3c197971fc692d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 3 Dec 2025 20:54:27 -0500 Subject: [PATCH] chore: Reduce lock contention in collaboration server (#10778) * chore: Reduce lock contention in collaboration server * Review suggestions --- server/collaboration/PersistenceExtension.ts | 24 ++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/server/collaboration/PersistenceExtension.ts b/server/collaboration/PersistenceExtension.ts index 688d5aaca3..790911ed63 100644 --- a/server/collaboration/PersistenceExtension.ts +++ b/server/collaboration/PersistenceExtension.ts @@ -29,8 +29,27 @@ export default class PersistenceExtension implements Extension { return; } + // First, try to find the document without a lock to check if it has state + const documentWithoutLock = await Document.unscoped().findOne({ + attributes: ["state"], + rejectOnEmpty: true, + where: { + id: documentId, + }, + }); + + // If the document already has state, we can return it without needing a transaction + if (documentWithoutLock.state) { + const ydoc = new Y.Doc(); + Logger.info("database", `Document ${documentId} is in database state`); + Y.applyUpdate(ydoc, documentWithoutLock.state); + return ydoc; + } + + // If the document doesn't have state yet, we need to acquire a lock and create it return await sequelize.transaction(async (transaction) => { - const document = await Document.scope("withState").findOne({ + const document = await Document.unscoped().findOne({ + attributes: ["id", "state", "content", "text"], transaction, lock: transaction.LOCK.UPDATE, rejectOnEmpty: true, @@ -38,8 +57,9 @@ export default class PersistenceExtension implements Extension { id: documentId, }, }); - let ydoc; + + // Double-check the state in case another process created it if (document.state) { ydoc = new Y.Doc(); Logger.info("database", `Document ${documentId} is in database state`);