MySQL Transaction Logs: Redo and Undo Mechanisms
Redo Log
Purpose of Redo Log
Buffer pools help bridge the CPU-disk gap, but checkpoint mechanisms don't trigger with every change. If a crash occurs after transaction commit but before data persistence, redo logs ensure durability by recording all modifications.
Redo Log Characteristics
- Advantages:
- Reduces disk write frequency
- Occupies minimal storage space
- Features:
- Sequential disk writes
- Continuous logging during transaction execution
Redo Log Components
- In-Memory Buffer:
innodb_log_buffer_sizecontrols size (default 16MB)
- Persistent Files:
- Disk-based log files
Redo Log Workflow
- Read original data into memory
- Generate redo logs in buffer (recording post-modification values)
- On commit: flush buffer to log files (append-only)
- Periodically flush modified data to disk
Flush Strategies
innodb_flush_log_at_trx_commit controls commit behavior:
0: No immediate flush (sync every 1s via master thread)1: Full flush on commmit (default)2: Write to OS cache only
Log File Configuration
innodb_log_group_home_dir: Log file locationinnodb_log_files_in_group: Number of log files (default 2)innodb_log_file_size: Individual log file size (default 48MB)
Undo Log
Purpose of Undo Log
Ensures atomicity by enabling rollback through:
- Recording pre-modification data
- Supporting MVCC (Multi-Version Concurrency Control)
Undo Log Storage
- Organized in rollback segments (128 max)
- Each segment contains 1024 undo slots
- Stored in dedicated undo tablespaces
Undo Log Types
- Insert Undo Log:
- Transaction-specific
- Discardabel after commit
- Update Undo Log:
- Required for MVCC
- Retained post-commit for potential rollbacks
Lifecycle Example
For an UPDATE operation:
- Create undo record with previous values
- Modify data in buffer pool
- On rollback:
- Aply undo records in reverse order
- Restore original state
Key Differences
- Redo logs: Physical records of page changes
- Undo logs: Logical records of data modifications