Heuristic:1mcp app Agent File Lock Retry For Atomic Writes
| Knowledge Sources | |
|---|---|
| Domains | Reliability, Configuration |
| Last Updated | 2026-10-29 00:00 GMT |
Overview
Use exclusive file creation (`O_WRONLY|O_CREAT|O_EXCL`) with 10 retries at 100ms intervals to implement a simple, cross-platform file lock for atomic config writes.
Description
The `backupManager` implements a file-based locking mechanism for atomic file operations (backup creation, config snapshots). It attempts to create a `.lock` file using `fs.writeFileSync(lockPath, process.pid, { flag: 'wx' })` — the `wx` flag maps to `O_WRONLY|O_CREAT|O_EXCL`, which atomically creates the file only if it does not already exist. If the lock file exists (EEXIST error), it waits 100ms and retries, up to 10 times (1 second total). After the operation completes, the lock file is deleted. If the lock cannot be acquired after all retries, an error is thrown.
Usage
Use this heuristic when:
- Implementing atomic file operations in a concurrent environment (multiple processes writing to the same config directory)
- Understanding config backup contention when multiple 1MCP processes share a config directory
- Debugging "Failed to acquire lock" errors in backup or config operations
The Insight (Rule of Thumb)
- Action: The lock is automatic for backup operations. No user configuration needed.
- Parameters:
- `maxRetries`: 10
- `retryDelay`: 100ms
- Total wait: up to 1000ms (1 second)
- Lock file: `{filePath}.lock` containing the acquiring process's PID
- Flag: `wx` (exclusive create) — atomic on POSIX and Windows
- Trade-off: Simple and portable, but not fault-tolerant: if the process crashes while holding the lock, the lock file remains stale and must be manually removed. No timeout or stale-lock detection.
- Cleanup: Lock file is deleted in a `finally` block; cleanup errors are silently ignored.
Reasoning
The `O_EXCL` flag ensures atomic lock acquisition: the OS guarantees that only one process can create the file, even if multiple processes attempt it simultaneously. This is more reliable than check-then-create patterns, which have a TOCTOU (time-of-check to time-of-use) race.
The retry mechanism handles transient contention: if another process is mid-operation, waiting 100ms gives it time to finish and release the lock. 10 retries (1 second total) is sufficient for normal operations but will fail fast if a process has died while holding the lock.
This approach is intentionally simple — it does not implement:
- Stale lock detection (checking if the PID in the lock file is alive)
- Lock timeout/lease mechanism
- Distributed locking
For the backup use case, simplicity is preferred over robustness because backup operations are infrequent and the operator can manually remove a stale lock file.
Code Evidence
File lock implementation from `src/domains/backup/backupManager.ts:414-449`:
export async function withFileLock<T>(filePath: string, operation: () => Promise<T>): Promise<T> {
const lockPath = `${filePath}.lock`;
let lockAcquired = false;
const maxRetries = 10;
const retryDelay = 100;
for (let i = 0; i < maxRetries; i++) {
try {
fs.writeFileSync(lockPath, process.pid.toString(), { flag: 'wx' });
lockAcquired = true;
break;
} catch (error: unknown) {
if (isErrnoExceptionWithCode(error, 'EEXIST')) {
await new Promise((resolve) => setTimeout(resolve, retryDelay));
continue;
}
throw error instanceof Error ? error : new Error(String(error));
}
}
if (!lockAcquired) {
throw new Error(`Failed to acquire lock for ${filePath} after ${maxRetries} retries`);
}
try {
const result = await operation();
return result;
} finally {
try {
fs.unlinkSync(lockPath);
} catch (_error) {
// Ignore cleanup errors
}
}
}