feat(memory): add file locking to support multi-instance #3286
+993
−48
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR implements proper cross-process file locking for the memory server using
proper-lockfileto ensure atomic read-modify-write operations across multiple MCP server instances.Key changes:
proper-lockfiledependency for cross-process file lockingcreateEntities,deleteEntities,createRelations,deleteRelations,addObservations,deleteObservations) inwithLock()to ensure atomic read-modify-writewrite-file-atomicfor more robust atomic file writesWhy PR #3060's in-memory lock solution is insufficient
PR #3060 attempts to fix Issue #2579's race condition using an in-memory Promise-based lock. While this works for concurrent operations within a single process, it fundamentally misses the real-world deployment model:
MCP servers using stdio transport are spawned as separate processes per client.
PR #3060 acknowledges this limitation:
This multi-client scenario is the default use case for many users, not an edge case.
Server Details
Motivation and Context
The memory server experiences file corruption when multiple MCP server instances (spawned by different AI clients) attempt concurrent writes to the same
memory.jsonfile.This is critical because:
How Has This Been Tested?
1. Single-process concurrent writes (10,000 operations)
knowledge-graph.test.tscreateEntitiescalls within a single process2. Multi-process concurrent writes (5 processes × 2,000 = 10,000 operations)
multi-process-lock.test.tsmcp-server-memoryprocesses via stdio transportAdditional testing:
Breaking Changes
No breaking changes:
Types of changes
Checklist
Additional context
Related Issues and PRs
mcp-server-memoryFailures due to Race Condition and Environment Misconfiguration #2579 - Race condition causing "Unexpected non-whitespace character after JSON" errorsWhy
proper-lockfile?proper-lockfile(this PR)proper-lockfileprovides the best balance of correctness and simplicity - true cross-process safety without external dependencies or storage migration.