KatInterview

Building a Crash-Safe Shared Audit Log Writer in Java

System DesignModel answer
MediumModel answerSystem Designconcurrencyfile-iodurability

Last 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

  1. Design a thread-safe FileLogger with a log(String message) method.
  2. 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.
  3. 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.