Building a Crash-Safe Shared Audit Log Writer in Java
System DesignModel answerLast updated
Design a thread-safe file logger whose records never interleave, and explain how fsync, batching and OS caching trade throughput against durability.
Shared audit log for many worker threads
A service runs many worker threads, and each one must append structured audit records to one shared file on a POSIX filesystem. Implement this in Java, but feel free to reason about OS behavior.
What to deliver
- Design a thread-safe
FileLoggerwith alog(String message)method. - Guarantee that under heavy concurrency each record is written as one contiguous line. Records must never be interleaved or split by another thread's data.
- Explain how you balance throughput against durability, meaning the guarantee that accepted records reach physical storage.
Example
If two threads call log("A") and log("B") at the same moment, the file may contain them in either order:
[timestamp] A
[timestamp] B
It must never contain a merged line such as:
[timestamp] AB
Points to address in your answer
- Does the OS guarantee that a large
write()is atomic with respect to other writers, for example one bigger than the pipe buffer size? - What does
FileChannel.force(boolean)(that is,fsync/fdatasync) do to performance? - If the process dies after
write()returns but before the kernel has flushed its page cache, is the data lost? What if the whole machine loses power?
Give a design, the reasoning behind it, the trade-offs, and working code.
Hints
Hint 1
Separate two questions: who is allowed to touch the file descriptor, and when do the bytes become durable. Each needs its own mechanism.
Hint 2
O_APPEND makes seek-to-end plus write atomic, but a write can still return a short count, and the retry may land after another thread's bytes. PIPE_BUF atomicity only covers pipes and FIFOs.
Hint 3
fsync is expensive and its cost is mostly per call, not per byte. Think about letting many records share one fsync, as a database write-ahead log does.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach in one paragraph
Funnel all writes through a single writer thread. Producer threads format a complete record (timestamp, message, trailing newline) into a byte array and put it on a bounded queue. The writer drains whatever has accumulated, writes it, and calls fsync once for the whole batch. Interleaving becomes impossible because only one thread touches the file. Durability becomes cheap because one fsync covers many records (group commit).
Why O_APPEND alone is not enough
PIPE_BUFis irrelevant to regular files. POSIX guarantees non-interleaving for writes of up toPIPE_BUFbytes (at least 512, 4096 on Linux), but only for pipes and FIFOs. Nothing comparable is promised for files.O_APPENDgives offset atomicity. Finding end-of-file and writing happen as one step, so two appenders never overwrite each other. It does not make a write indivisible.- Short writes happen. A signal, a full disk or a quota limit can make
write()return fewer bytes than requested. The caller must loop, and the continuation can land after another thread's record, producing something like[ts] A[ts] B...rest-of-A. - Local filesystems often look safe by accident. Linux filesystems typically serialize writers on the inode lock, so whole writes rarely interleave. That is an implementation detail. On NFS, appends from different clients are not atomic at all.
So the application must serialize. A single writer does that without having N threads fight over a lock held across a slow syscall.
Where the data lives
| Stage | Survives process crash | Survives kernel crash / power loss |
|---|---|---|
In-process queue or BufferedWriter | No | No |
OS page cache (after write() returns) | Yes | No |
| Device write cache | Yes | Only with power-loss protection or honored flush/FUA |
| Physical media | Yes | Yes |
This answers the crash question. If only the process dies after write() returned, the bytes are already in kernel memory and will be written back later (Linux dirty pages expire after roughly 30 s by default). Only a kernel crash or power failure before writeback loses them. Records still sitting in your own queue are lost on any crash, which is why the durability policy matters.
FileChannel.force(false) corresponds roughly to fdatasync, and force(true) to fsync. For an append-only file the size changes with every write, so even fdatasync must persist that metadata. Do not expect it to be dramatically cheaper here.
Throughput versus durability
An fsync costs about 5-10 ms on a spinning disk and about 0.05-1 ms on SSD/NVMe, and it can be worse on consumer drives without power-loss protection. Syncing every record under a lock therefore caps you at roughly 100 to 20,000 records per second regardless of thread count.
Expose three policies:
- Cache only: never call
fsync. Highest throughput. Survives a process crash, not power loss. - Interval:
fsyncevery T ms. You lose at most about T ms of records on power loss. Many systems default to this (for example Redisappendfsync everysec). - Every record:
log()returns only after its record is synced. Batching still applies, so 1,000 concurrent callers pay for about onefsync, not 1,000.
The bounded queue adds backpressure: when the disk cannot keep up, producers block instead of exhausting memory. For a non-critical logger you could instead drop or count overflow, but for an audit log blocking is the right default.
Code
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static java.nio.charset.StandardCharsets.UTF_8;
public final class FileLogger implements AutoCloseable {
public enum Mode { CACHE_ONLY, INTERVAL, EVERY_RECORD }
private record Item(byte[] data, CompletableFuture<Void> ack) {}
private static final Item STOP = new Item(new byte[0], null);
private static final int MAX_BATCH = 1024;
private final FileChannel channel;
private final BlockingQueue<Item> queue;
private final Mode mode;
private final long intervalNanos;
private final Thread writer;
private volatile boolean closed;
public FileLogger(Path path, Mode mode, long intervalMs, int capacity) throws IOException {
this.channel = FileChannel.open(path, StandardOpenOption.CREATE,
StandardOpenOption.WRITE, StandardOpenOption.APPEND);
this.queue = new ArrayBlockingQueue<>(capacity);
this.mode = mode;
this.intervalNanos = TimeUnit.MILLISECONDS.toNanos(intervalMs);
this.writer = new Thread(this::drainLoop, "file-logger-writer");
this.writer.start();
}
public void log(String message) {
if (closed) throw new IllegalStateException("logger closed");
String line = "[" + Instant.now() + "] " + message.replace("\n", "\\n") + "\n";
CompletableFuture<Void> ack =
mode == Mode.EVERY_RECORD ? new CompletableFuture<>() : null;
try {
queue.put(new Item(line.getBytes(UTF_8), ack)); // blocks when full
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
if (ack != null) ack.join(); // wait for the fsync
}
private void drainLoop() {
List<Item> batch = new ArrayList<>(MAX_BATCH);
long pollNanos = mode == Mode.INTERVAL ? intervalNanos : 100_000_000L;
long lastSync = System.nanoTime();
boolean dirty = false, alive = true;
while (alive) {
try {
Item head = queue.poll(pollNanos, TimeUnit.NANOSECONDS);
if (head != null) { batch.add(head); queue.drainTo(batch, MAX_BATCH - 1); }
alive = !batch.removeIf(i -> i == STOP);
if (!batch.isEmpty()) {
int total = batch.stream().mapToInt(i -> i.data().length).sum();
ByteBuffer buf = ByteBuffer.allocate(total);
for (Item i : batch) buf.put(i.data());
buf.flip();
while (buf.hasRemaining()) channel.write(buf); // handle short writes
dirty = true;
}
long now = System.nanoTime();
boolean sync = dirty && (!alive || mode == Mode.EVERY_RECORD
|| (mode == Mode.INTERVAL && now - lastSync >= intervalNanos));
if (sync) { channel.force(false); dirty = false; lastSync = now; }
for (Item i : batch) if (i.ack() != null) i.ack().complete(null);
batch.clear();
} catch (IOException | InterruptedException e) {
for (Item i : batch) if (i.ack() != null) i.ack().completeExceptionally(e);
batch.clear();
if (e instanceof InterruptedException) alive = false;
}
}
}
@Override public void close() throws Exception {
closed = true;
queue.put(STOP);
writer.join();
channel.close();
}
}
Complexity
log() is O(1) amortized plus any blocking on a full queue. The writer does O(total bytes) work per batch with one write loop and at most one fsync. Memory is bounded by queue capacity times record size.
Alternatives and trade-offs
- A
ReentrantLockaroundwrite(+force) is simpler and correct, but threads queue behind a slow syscall, and per-record syncing gets no batching. - One file per thread, merged later, removes contention but complicates ordering and reads.
- Memory-mapped files make durability semantics harder to reason about and offer no clear win for appends.
Common mistakes
- Assuming a single
write()is always atomic, or citingPIPE_BUFfor files. - Not looping on short writes.
- Writing the timestamp and message in separate calls so they can be split.
- Calling
fsyncper record under a global lock and then adding threads to "scale". - Letting messages contain raw newlines, which breaks the one-record-per-line format.
- Unbounded queues that turn a slow disk into an out-of-memory crash.
- Forgetting to flush and sync on shutdown, or to surface writer-thread I/O errors to callers. In production, a failed
fsyncshould be treated as fatal for that file, because the kernel may have already dropped the dirty pages.