Of course! A Write-Ahead Log (WAL), sometimes called a transaction log, is a fundamental component of most modern relational database management systems (RDBMS) like PostgreSQL, MySQL (InnoDB), Oracle, and SQL Server.
Its primary purpose is to ensure durability and atomicity, two of the core ACID properties of a transaction. The core principle is: Changes must be written to the log before they are written to the main data files.
Here is a breakdown of the information normally stored in a WAL record for a single data modification.
Core Components of a Log Record
For every change made to the database (like an INSERT, UPDATE, or DELETE), a new record is appended to the WAL. This record contains everything needed to reconstruct the change.
Information Stored
Purpose / Why it's needed
1. Log Sequence Number (LSN)
A unique, monotonically increasing number for each log record. It acts as the "address" or coordinate of the change within the log. Crucial for ordering operations during recovery.
2. Transaction ID (TxID)
An identifier for the transaction that generated this change. This allows the database to group all changes belonging to a single transaction. Essential for COMMIT or ROLLBACK operations.
3. Type of Operation
A code indicating what kind of change was made (e.g., INSERT, UPDATE, DELETE, PAGE_SPLIT, INDEX_UPDATE). This tells the recovery process what action to perform.
4. Location of the Change
The physical or logical address of the data that was modified. This typically includes the Table ID, Page/Block ID, and the offset within that page where the change occurred.
5. "Before" Image (Undo Data)
The state of the data before the modification. This could be the entire row or just the specific bytes that were changed. Purpose: This is essential for rolling back a transaction (UNDO).
6. "After" Image (Redo Data)
The state of the data after the modification. Again, this could be the full new row or just the new values. Purpose: This is the primary data used for crash recovery (REDO).
7. Checksum / CRC
A checksum calculated from the contents of the log record. Purpose: To detect corruption in the WAL file itself. If a log record is read and its checksum doesn't match, the database knows the log is damaged.
Note: To save space, many systems don't store the full "before" and "after" images. Instead, they might store a more compact delta or diff (e.g., "changed bytes 40-52 from value X to value Y").
Special Log Record Types
Besides records for data modifications, the WAL also contains special records to manage the state of transactions and the database itself.
Transaction Control Records:
BEGIN: Marks the start of a transaction.
COMMIT: Marks that a transaction has completed successfully. Once this record is safely written to the WAL on disk, the transaction is considered durable, and the database can acknowledge success to the client.
ABORT / ROLLBACK: Marks that a transaction has been aborted and its changes must be undone.
Checkpoint Records:
A checkpoint is a point in time where the database guarantees that all data modifications logged before the checkpoint have been safely written from memory (the buffer cache) to the main data files on disk.
The checkpoint record in the WAL contains information like the LSN of the last record flushed to disk.
Purpose: This dramatically speeds up crash recovery. When a database restarts after a crash, it doesn't have to replay the entire WAL from the beginning of time. It can find the last checkpoint and only needs to replay the logs generated after that checkpoint.
A Concrete Example
Let's trace a simple UPDATE statement:
BEGIN;
UPDATE employees SET salary = 60000 WHERE id = 123;
COMMIT;
Here's what gets written to the WAL (conceptually):
This is the core data modification record. It has all the information needed to either redo or undo this specific salary change.
[LSN: 102, TxID: 501, Type: COMMIT]
Transaction 501 is now considered complete and durable. The database can now respond COMMIT successful to the client.
After these records are safely on disk, a background process will eventually write the actual change (salary = 60000) to the employees data file on disk. The WAL ensures that even if the server crashes before that happens, the change is not lost.
How is this information used for Crash Recovery?
The database starts up after a crash.
It finds the last checkpoint record in the WAL.
It begins scanning the log forward from that checkpoint's LSN.
For each log record it finds:
It checks the Transaction ID (TxID).
If the transaction was committed (i.e., a COMMIT record exists for its TxID), it applies the "After" image (Redo Data) to the in-memory data pages, ensuring the change is not lost.
If the transaction was not committed (i.e., it was in-flight when the crash happened), it is treated as aborted, and its changes are either ignored or undone later using the "Before" image.
User
How WAL is stored on disk?
Assistant
Excellent follow-up question! Storing the Write-Ahead Log (WAL) efficiently and safely is just as important as what goes into it. The storage strategy is designed for two primary goals: extreme speed and unquestionable durability.
Here’s a breakdown of how the WAL is typically stored and managed on disk.
1. A Sequence of Segment Files
The WAL is not stored as one single, enormous file that grows forever. Instead, it is broken down into a series of smaller, fixed-size files called log segments or log files.
Fixed Size: Each segment file has a predefined size (e.g., 16MB by default in PostgreSQL, configurable in MySQL).
Sequential Naming: These files are given sequential names that allow the database to know their correct order. For example, in PostgreSQL, you'll see files in the pg_wal directory named something like 0000000100000000000000FF, 000000010000000000000100, etc.
Why Segments? Breaking the log into segments makes it much easier to manage. Instead of dealing with a multi-terabyte file, the system only needs to handle smaller, predictable chunks. This is crucial for tasks like cleanup and archiving.
2. The Circular Buffer Model
Conceptually, the database treats these segment files as a circular buffer.
Writing: The database writes new log records sequentially into the current active segment file.
Switching: When the current segment file is full, the database closes it and begins writing to the next segment in the sequence (e.g., switches from ...FF to ...100). This is called a log switch.
Recycling: Once the changes recorded in an old segment file are no longer needed for crash recovery (meaning they have been successfully applied to the main data files and a checkpoint has occurred), that segment file can be recycled. Recycling means the file is either deleted or, more commonly, renamed to a future sequence number to be reused later.
This circular process prevents the WAL from growing infinitely while the database is running normally.
3. The Writing Mechanism: Append-Only and Buffered
This is the key to the WAL's performance.
Append-Only: New log records are always added to the end of the current log file. This is a sequential write operation. Sequential I/O on a spinning disk is orders of magnitude faster than random I/O, as the disk's read/write head doesn't have to jump around to different locations. This benefit also extends to SSDs, though to a lesser degree.
User
I have a raw device, how can I make a file system on it (I want to bypass OS file system)
Assistant
Excellent and very advanced question! This is a task that moves from the realm of a system administrator to that of a systems programmer or database kernel developer.
First, let's clarify the terminology. When you say you want to "make a file system... and bypass the OS file system," there are two common interpretations:
Using a Raw Device for an Application: You want to give a raw block device (like /dev/sdb1) directly to an application (like a database) and let that application manage the blocks. The application essentially implements its own storage logic on top of the raw blocks. This is a common high-performance technique.
Creating a General-Purpose Filesystem: You want to write your own version of ext4 or XFS from scratch, with your own mkfs.myfs and a driver that allows the OS to mount and see it like a normal filesystem. This is a major computer science project.
Let's cover both, starting with the more practical one for database contexts.
Approach 1: Using a Raw Device Directly with an Application (The Pragmatic Way)
This is what high-performance databases like Oracle (with ASM) do to gain maximum control and eke out performance. You are not creating a "filesystem" in the traditional sense (with ls, cp, etc.), but rather a proprietary, application-specific data layout.
Why do this?
Bypass OS File System Cache (Double Caching): The database has its own intelligent cache (e.g., the buffer pool). The OS file system also has a cache. Using a raw device can prevent the same data from being cached twice, saving memory and CPU cycles.
Direct I/O Control: The application has full control over I/O patterns, block sizes, and write ordering, which can be optimized for its specific workload (e.g., aligning writes with the WAL).
No File System Overhead: You eliminate the overhead of journaling, metadata updates (like access times), and fragmentation handling from the general-purpose OS file system.
How to Do It (Conceptual Steps):
You don't "make a file system" on the device. Instead, you prepare the device and then tell your application to use it.
Identify and Prepare the Device:
Choose a disk or partition (e.g., /dev/sdc or /dev/sdc1).
CRITICAL: Ensure it contains no data you need.
User
Where should we store the metadata?
Assistant
Excellent question. This gets to the very heart of filesystem design.
When creating your own filesystem on a raw device, the metadata must be stored on the device itself, in well-defined, predictable locations, separate from the file content (the "data").
Think of the raw device as a giant, empty book. You can't just start writing stories (data) on random pages. You first need to create a Table of Contents and an Index (metadata) so you can find the stories later.
Here is the classic and most common approach for storing metadata, heavily influenced by the Unix/Linux filesystem design (ext2/3/4, UFS).
The Three Core Metadata Structures
You will dedicate specific blocks on your device to three primary types of metadata:
The Superblock
The Inode Table (and the Inodes within it)
Directory Entries (which are stored in special data blocks)
Let's look at their roles and where they are typically placed.
A Typical On-Disk Layout
Imagine your raw device is just a linear sequence of blocks (e.g., 4KB each). A simple layout would look like this:
This is the most critical piece of metadata. It describes the entire filesystem.
What it Stores:
Magic Number: A unique ID to identify your filesystem type (e.g., 0xEF53 for ext2).
Filesystem Size: Total number of blocks, total number of inodes.
Layout Information: Block size, blocks per group, location of the inode table, etc.
State: A flag indicating if the filesystem is "clean" or was mounted when the system crashed.
Where to Store It:
At a fixed location, near the beginning of the device (e.g., Block 1). This is so the operating system knows exactly where to look when it tries to mount the filesystem.
WAL Buffers: To be even faster, the database does not write every single log record to disk immediately. Instead, it places them in a dedicated area in memory called the WAL buffer.
Flushing to Disk (fsync): The contents of the WAL buffer are "flushed" (written and synchronized) to the physical disk at critical moments:
On Transaction Commit: This is the most important one. When you issue a COMMIT, the system must flush all log records for that transaction from the buffer to the disk. The COMMIT operation is not considered successful until the operating system confirms that the data is durably stored (via a system call like fsync()).
When the Buffer is Full: If the WAL buffer fills up, it must be flushed to disk to make room for new records.
Periodically: A background process (like a "log writer") may flush the buffer periodically to ensure that recent changes don't linger in memory for too long.
This "buffer-then-flush" strategy combines the speed of writing to memory with the safety of writing to disk, giving the best of both worlds.
4. Management and Maintenance
Checkpoints: A checkpoint is the process that flushes modified data pages (not log pages) from memory to the main data files on disk. A checkpoint record is then written to the WAL. This record essentially says, "All changes before this point in the log are now safely in the main data files." This is what marks older WAL segments as obsolete and eligible for recycling or deletion.
Archiving: For point-in-time recovery (PITR) and creating replicas, you can't just recycle old WAL segments. Instead, the database can be configured to archive them. When a WAL segment is full, instead of being recycled, it is copied to a separate, safe storage location (like another disk, a network share, or cloud storage). This creates a continuous, unbroken history of all changes ever made to the database, allowing you to restore the database to any single moment in time.
Database-Specific Examples
Database
Directory Name
File Names (Example)
Key Behavior
PostgreSQL
pg_wal (v10+) or pg_xlog (v9.6 and older)
000000010000000A0000005B
A sequence of 16MB segment files. Recycled or archived after checkpoints.
MySQL (InnoDB)
The data directory
ib_logfile0, ib_logfile1
A pre-configured, fixed set of files used in a circular fashion. The number and size are defined at initialization.
Oracle
Configurable
redo01.log, redo02.log
Uses "Redo Log Groups". Can be multiplexed (mirrored) for redundancy, writing the same log data to multiple files simultaneously.
SQL Server
The data directory
databasename_log.ldf
Typically a single transaction log file that grows and is managed internally, but conceptually it behaves similarly.
Summary: How the WAL is Stored
Characteristic
How it's done
Why it's done
File Structure
A sequence of fixed-size segment files.
Easy to manage, clean up, and archive.
Writing Pattern
Append-only, sequential writes.
Maximizes I/O performance, especially on spinning disks.
Data Flow
Changes go to an in-memory WAL buffer first.
Buffering is fast; avoids hitting the slow disk for every small change.
Durability
Buffer is flushed and fsynced to disk on COMMIT.
Guarantees that a committed transaction will survive a crash.
Space Management
Old segments are recycled (reused) in a circular fashion after a checkpoint.
Prevents the log from growing infinitely.
Disaster Recovery
Segments can be archived to another location instead of recycled.
Enables Point-in-Time Recovery (PITR) and replication.
All data will be overwritten.
Set the correct permissions so the user running the application (e.g., postgres or oracle) can read from and write to the device file.
# Example: Give ownership to the 'postgres' user and group
sudo chown postgres:postgres /dev/sdc1
sudo chmod 660 /dev/sdc1
Configure the Application:
You then configure your application to use this raw device as its storage. The application's own initialization process is what will "format" the device with its internal data structures.
Example with PostgreSQL:
PostgreSQL can use raw devices for tablespaces, though it's less common today with modern file systems like XFS and direct I/O options.
You would create a tablespace pointing to a directory, and that "directory" would contain a single file that is symbolically linked to the raw device. The initialization is handled by the CREATE TABLESPACE command.
Example with Oracle ASM (Automatic Storage Management):
This is the canonical example. You provide raw disks to the Oracle ASM instance.
ASM is a volume manager and a file system built specifically for Oracle database files.
You use ASM tools (asmca) to create a "disk group" from one or more raw devices. ASM then manages the layout, striping, and mirroring of data across these devices, presenting a unified file system only to the Oracle database.
In this approach, your "mkfs" is the database's own initialization command (initdb, CREATE TABLESPACE, CREATE DISKGROUP, etc.).
Approach 2: Creating a True, General-Purpose Filesystem (The Computer Science Project)
If you literally want to create your own filesystem that the OS can mount and use, you are building it from scratch. This is a fantastic learning experience.
WARNING: NEVER do this on a disk with real data. Use a loop device or a virtual disk in a VM for all development and testing.
A filesystem is fundamentally just a set of data structures laid out on a disk to organize data. You will need to design and implement:
The Core On-Disk Structures
Superblock:
The very first block of the filesystem. It's the metadata for the entire filesystem.
Contents: A magic number (to identify your filesystem type), total number of blocks, block size, number of inodes, a pointer to the start of the inode table, and a pointer to the free space map.
Inode Table:
An inode (index node) stores metadata about a single file or directory.
Contents: File type (regular, directory, symlink), permissions, owner/group IDs, file size in bytes, timestamps (created, modified, accessed), and most importantly, pointers to the actual data blocks. For larger files, these pointers can be indirect (a pointer to a block of more pointers).
Data Blocks:
These are the blocks that hold the actual file content. They are pointed to by the inodes.
Free Space Map (or Bitmap):
A data structure that tracks which data blocks are in use and which are free. The simplest form is a bitmap: a long sequence of bits where the Nth bit is 1 if block N is used and 0 if it's free.
Directories:
A directory is just a special type of file. Its data block(s) contain a list of (filename, inode_number) pairs. When you do ls, you are reading this special file to map names to inodes.
Implementation Steps
Write the mkfs.myfs Tool:
Write a program (in C, Rust, Go, etc.) that takes a device path (e.g., /dev/loop0) as an argument.
This tool opens the device, writes the superblock to the first block, initializes the inode table (creating a root / directory inode), sets up the free block bitmap, and writes everything to the device.
Write the Filesystem Driver:
This is the hardest part. You need a way for the OS kernel to understand your on-disk structures.
The Hard Way (Kernel Module): Write a Linux kernel module. This is extremely powerful but also very difficult and dangerous. A bug in your code can crash the entire system. You would implement the Virtual Filesystem (VFS) interface functions (read_inode, d_lookup, etc.).
The Sane Way (FUSE - Filesystem in Userspace): This is the highly recommended approach for learning and prototyping.
FUSE is a kernel module that acts as a bridge. It forwards VFS calls from the kernel to a daemon process running in userspace.
You write a userspace program that implements the FUSE API (e.g., myfs_getattr, myfs_read, myfs_write). Your program opens the raw device and translates these high-level requests into low-level block reads and writes according to your filesystem's design. It's safer, easier to debug, and you can write it in many languages (C, C++, Python, Go, Rust).
A Safe, Practical Example using losetup and FUSE
Here's a workflow for the second approach:
Create a "virtual disk" file:
# Create an empty 100MB file to act as our disk
dd if=/dev/zero of=mydisk.img bs=1M count=100
Associate it with a loop device:
# This makes mydisk.img available as a block device at /dev/loop0 (or similar)
sudo losetup -fP mydisk.img
# Check it
losetup -a
# Output might be: /dev/loop0: [64768]:3448 (/path/to/mydisk.img)
Write your mkfs.myfs:
Your C program would look something like int main(int argc, char **argv) { open_and_format(argv[1]); }.
Run it: sudo ./mkfs.myfs /dev/loop0
Write your FUSE driver:
Using a library like libfuse, you'll implement functions like getattr, readdir, read, and write.
These functions will use standard open(), pread(), and pwrite() system calls on /dev/loop0 to manipulate your superblock, inodes, and data blocks.
Mount your filesystem:
mkdir /mnt/myfs
# Run your FUSE daemon in the foreground for debugging
sudo ./myfs_driver /dev/loop0 /mnt/myfs -f
Now, in another terminal, you can cd /mnt/myfs, ls, touch a_file, echo "hello" > a_file, and watch the debug output from your FUSE driver
Crucially, store backup copies! If the primary superblock is corrupted, the entire filesystem is lost. Filesystems like ext4 sprinkle backup copies of the superblock throughout the disk in different "block groups".
2. The Inode Table
An inode (index node) is a data structure that stores all the metadata about a single file or directory, except for its name.
What an Inode Stores:
File Type: Is it a regular file, a directory, a symbolic link, etc.?
Permissions: Read, write, execute permissions for user, group, and others (rwx).
Owner/Group IDs: Who owns the file.
Size: The file's size in bytes.
Timestamps: Last access time, last modification time, creation time.
Link Count: The number of hard links pointing to this inode.
Pointers to Data Blocks: This is the most important part! It's an array of block numbers that point to the actual data blocks holding the file's content.
Where to Store It:
In a large, contiguous region of the disk called the Inode Table. This region is reserved at format time (mkfs).
Each inode has a unique number (its index in the table). This inode number is the ultimate identifier for a file on the disk.
3. Directory Entries
So where is the file's name stored? A directory is just a special type of file. Its data block(s) contain the directory entries.
What a Directory Entry Stores:
It's a simple mapping structure. It's a list of (filename, inode_number) pairs.
Example: The content of a directory file for /home might look like: ( '.', 12 ), ( '..', 2 ), ( 'user1', 508 ), ( 'user2', 912 ).
Where to Store It:
Directory entries are stored in regular data blocks, just like a text file's content.
The inode for the directory has pointers that lead to these data blocks.
Tying It All Together: How a File is Read
Let's trace the path to read /home/user/file.txt:
Find Root (/): The filesystem driver knows the inode number for the root directory is a fixed value (e.g., inode #2).
Read Root Inode: Go to the Inode Table, calculate the position of inode #2, and read its contents. From the inode's pointers, find the data block(s) for the root directory.
Scan Root Directory Data: Read the data block for the / directory. Scan its list of entries to find the name "home". The entry ("home", 435) is found. Now you have the inode number for /home.
Read /home Inode: Go to the Inode Table, find inode #435, and read its data block pointers.
Scan /home Directory Data: Read the data block(s) for the /home directory. Scan the entries to find "user". The entry ("user", 819) is found.
Read /home/user Inode: Go to the Inode Table for inode #819.
Scan /home/user Directory Data: Read its data block(s). Scan the entries to find "file.txt". The entry ("file.txt", 1024) is found.
Read file.txt Inode: Go to the Inode Table for inode #1024. Now you have all the metadata for file.txt: its size, permissions, and most importantly, the list of pointers to its data blocks.
Read File Data: Follow the data block pointers from inode #1024 to read the actual content of the file from the data blocks.
This separation of concerns—metadata in inodes, name mapping in directories—is what makes features like hard links possible. A hard link is simply creating a second directory entry (with a different name, possibly in a different directory) that points to the exact same inode number.