The previous post looked at the on-disk file. This one looks at what happens before: a transaction’s events go into the binlog cache and are written to the binlog as a unit at commit.

The problem it solves

A binlog transaction must be all-or-nothing: either every event lands in the file or none does. The cache is that staging area — small transactions stay in memory, large ones spill to a temporary file, and commit writes the whole thing at once.

Seven states

                         write_event()
   [UNUSED] ─────────────────────────────────────► [IN_MEMORY]
      ▲                                              │  │
      │ close_cached_file()                          │  │ buffer full / large write
      │ (connection close)                           │  ▼
   [CLOSED] ◄─────────────────────────────────── [SPILLED]
                                                     │  │  fd != -1, disk_writes > 0
                        finalize()                   │  │
                             ▼                       │  │
                        [FINALIZED] ── flush() ──► [RESET] ──► reusable (fd kept)
                             │           success      │
                             └── flush() failure ────►│ disk_writes = 0
                                 (commit_error)       └─► back to IN_MEMORY

   any IN_MEMORY / SPILLED:
        truncate(pos)  ── savepoint rollback ──► [TRUNCATED]
        logical length = pos; the physical file does not shrink

State table

Statem_io_cache.filelength()disk_writes()Can write
UNUSED-100yes (first write moves to IN_MEMORY)
IN_MEMORY-1bytes in buffer0yes
SPILLED>=0pos_in_file + buffered>0yes
TRUNCATED>=0 or -1back to savepointunchangedyes (overwrites)
FINALIZED>=0 or -1fixedunchangedno
RESETmaybe >=0 (size 0)00yes (reused)
CLOSED-100no (object gone)

Key transitions

TransitionTriggerFunction
UNUSED → IN_MEMORYfirst event of a transactionbinlog_cache_data::write_event
IN_MEMORY → SPILLEDbuffer full or oversized write_my_b_write → my_b_flush_io_cache → real_open_cached_file
SPILLED → TRUNCATEDROLLBACK TO SAVEPOINTbinlog_cache_data::truncate → IO_CACHE_binlog_cache_storage::truncate
→ FINALIZEDend event appended before commitbinlog_cache_data::finalize
FINALIZED → RESETflush succeededbinlog_cache_data::flush → reset
any → CLOSEDconnection closeclose_cached_file

Eight questions

1. How many layers between write_event and IO_CACHE?

binlog_cache_data::write_event(ev)
  └─ binary_event_serialize(ev, &m_cache)
       └─ Binlog_cache_storage::write
            └─ IO_CACHE_binlog_cache_storage::write
                 └─ my_b_safe_write → my_b_write
                      ├─ fits: memcpy into the buffer
                      └─ does not fit: _my_b_write → flush or direct write

2. When is the temp file created?

At the first moment disk is needed (buffer full, or one write larger than the remaining space):

_my_b_write
  └─ my_b_flush_io_cache
       └─ if (info->file == -1) real_open_cached_file(info);
            └─ mysql_file_create_temp(..., UNLINK_FILE, ...)

3. What are pos_in_file, write_pos and write_end?

  • pos_in_file: file offset of buffer byte 0;
  • write_pos: next free byte in the buffer;
  • write_end: buffer capacity;
  • end_of_file: in WRITE_CACHE this is the maximum writable position (max_cache_size), not the current file length.

Logical length:

my_b_tell(info) = pos_in_file + (write_pos - buffer)

4. How do length() and disk_writes() relate?

  • length(): in WRITE mode returns my_b_tell (on-disk plus buffered bytes), including header, body and checksum;
  • disk_writes(): number of spills, cleared by reset();
  • Binlog_cache_use: incremented when a non-empty cache is reset;
  • Binlog_cache_disk_use: incremented when that reset follows at least one spill.

5. What does finalize() do, and why is writing forbidden afterwards?

  1. If the cache is non-empty: flush_pending_event() closes any pending Rows event;
  2. write_event(end_event) appends the terminator (Xid_log_event or Query "COMMIT");
  3. compress if configured;
  4. flags.finalized = true.

The event sequence is complete; writing more would break the transaction boundary. flush() only writes to the binlog when finalized is set.

6. Why reset() after a successful flush()?

if (flags.finalized) {
  ... write_transaction (GTID + cache bytes) ...
  reset();          // clear cache and flags, disk_writes = 0
}
assert(!flags.finalized);

reset() returns the cache to a reusable state (truncate the temp file to 0, keep the fd); finish_commit asserts that no cache is finalized-but-unflushed; on failure the same path runs and the error propagates via thd->commit_error.

7. Does ROLLBACK TO SAVEPOINT shrink the file?

Not immediately.

binlog_savepoint_rollback
  └─ binlog_cache_data::truncate(pos)
       └─ IO_CACHE_binlog_cache_storage::truncate(pos)
            └─ reinit_io_cache(WRITE_CACHE, pos, ..., clear_cache)
  • The logical length returns to pos;
  • The physical file is not truncated: only pos_in_file/write_pos are reset, later writes overwrite;
  • Actual shrinking happens in reset() (my_chsize(fd, 0)) or close_cached_file().

8. stmt_cache or trx_cache?

Decided by is_using_trans_cache():

  • DML on transactional (InnoDB) tables → trx_cache;
  • Non-transactional statements and some DDL → stmt_cache.

Counters map to Binlog_stmt_cache_use and Binlog_cache_use.

Experiment log

ExperimentObservation
small transactionno ML temp file, no new deleted fd in /proc
large transaction (binlog_cache_size=4096)during the transaction fd 42 has size=36864, /tmp/MLfd=42; after commit size=0
connection closefd 42 disappears
countersBinlog_cache_use=16, Binlog_cache_disk_use=4
ROLLBACK TO SAVEPOINTrows revert, cache reverts logically, file size unchanged

One sentence

The binlog cache is an append-only store with an in-memory buffer and a lazily created temp file: write_event serializes into it, finalize marks the transaction complete, flush writes GTID plus cache bytes to the binlog and resets for reuse — savepoint rollback is purely logical.

Previous: binlog file format

Follow this series

MySQL 8.0 source reading, one verifiable result at a time.