Write Consistency and Locking in Bun
Bun does not implement a unified, cross-platform locking abstraction for Bun.file(). The runtime relies on the underlying operating system's native file handling and locking behavior. Consequently, concurrent write operations to the same file path are not automatically serialized by the Bun runtime; the resulting file state depends entirely on the OS kernel, the filesystem, and the specific flags used during the system call.
OS-Level Divergence and Race Conditions
Because Bun maps its high-performance I/O directly to system primitives, developers will encounter the native differences between Linux and macOS:
- Advisory Locking: Both systems primarily use advisory locking (such as
flock or fcntl). These locks are only effective if every process attempting to access the file explicitly checks for the lock before writing. Bun does not implicitly apply these locks to Bun.file() operations.
- Write Interleaving: In high-concurrency bursts, multiple asynchronous writes can overlap. Without application-level synchronization, this may lead to interleaved data or partial overwrites, as the runtime does not maintain an internal queue or contention manager for shared file handles.
- Atomicity: Write atomicity is not guaranteed for large payloads across different filesystems. While small writes may appear atomic, larger buffers are subject to the OS's scheduling and buffer management.
Implementation Strategy for Consistency
To ensure write consistency across Linux and macOS, you must implement synchronization at the application level rather than relying on the runtime. Use the following approach:
- Mutex/Queue: Implement an asynchronous queue or a mutex in JavaScript to ensure only one
Bun.file().write() operation is active for a specific path at any given time.
- Atomic Renames: Write data to a temporary file (e.g.,
file.tmp) and use Bun.file().rename() or a similar atomic move operation to replace the target file. This is the most reliable cross-platform method to avoid corrupted states.
- Append Mode: If the goal is logging, ensure the OS-level
O_APPEND flag is utilized (if supported by the specific Bun method version), which is generally atomic at the kernel level for most POSIX systems.
Verification and Diagnostics
To verify the behavior in your specific environment, you can run a concurrency test:
// Simple concurrency test
const file = Bun.file("test.txt");
await Promise.all([
file.write("Data A".repeat(1000)),
file.write("Data B".repeat(1000))
]);
Inspect the resulting file for interleaved "Data A" and "Data B" strings. If interleaving occurs, the OS is not serializing the writes.
Missing Diagnostic Detail: Please specify the exact version of Bun you are using. The Bun.file() API surface has evolved rapidly, and the availability of specific write methods or flags may vary between versions.