MEDIUM: Add file locking for concurrent JSON persistence #37
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem
Multiple modules persist state to JSON files with no file-level locking. Both the Discord bot event loop and the FastAPI API endpoints can write to the same files concurrently, risking data corruption:
Affected Files and Writers
Race Condition Scenario
Since these are full-file rewrites (json.dump), partial writes during crashes can also produce corrupted JSON.
Proposed Solutions (pick one)
Option A: fcntl file locking (minimal change)
Option B: Atomic write pattern
Write to a temp file, then os.rename() (atomic on Linux):
def atomic_json_write(path, data):
tmp = path + '.tmp'
with open(tmp, 'w') as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.rename(tmp, path)
Option C: Migrate to SQLite
Replace all JSON persistence with a single SQLite database. Gets ACID transactions, no corruption risk, better query performance. Higher effort but most robust.
Impact
Files Affected