Course contentsShow
← Databases & SQL
Lesson 773 of 1,9537. Transaction ManagementFree lesson

The Role of Latches in Internals

Distinguish between long-term transactional locks and short-term engine-level mutexes.

In this lesson, you will learn how databases manage physical memory safety using short-term latches, and how they differ from the long-term transaction locks you already know.

Locks vs. Latches

Up until now, we have discussed locks—the tools the database uses to maintain transaction isolation (like SELECT FOR UPDATE or serializable transactions). These locks are held for the duration of a transaction; if your transaction takes ten minutes, the lock stays until you commit or rollback.

Latches, on the other hand, are the database engine's "internal bodyguards." They are short-term, low-level mutual exclusion primitives (mutexes) used to protect memory structures, such as a page in the buffer pool or a specific index node.

Why do we need both?

Imagine two users trying to update a row in the same memory page. The database uses locks to ensure the transaction logic is consistent (Isolation). However, it also needs to make sure that two threads don’t try to modify the physical bytes of that memory page at the exact same microsecond, which would lead to memory corruption.

  • Transaction Locks: Logical. They protect your data's business integrity. They are held for long periods and are visible to the user.
  • Latches: Physical. They protect the engine's internal data structures. They are held for mere microseconds—only long enough to read or write a specific memory address—and are invisible to the user.

An Illustration

Consider this scenario:

-- User A runs a large transaction
BEGIN;
UPDATE Accounts SET Balance = Balance - 100 WHERE ID = 1;
-- Lock is held here for the duration of the transaction
COMMIT;

While that long-term lock is held on the row, the database engine must also perform a brief latch operation to physically write the updated value into the memory page. Once the bits are written to the page, the latch is released immediately, even though the transaction lock remains active until the COMMIT.

If the engine had to hold a latch for as long as a transaction, the entire system would grind to a halt because other threads would be unable to access the memory page at all.

Key Takeaway: While transaction locks ensure your data's logical consistency over time, latches are lightning-fast physical guards that prevent internal memory corruption during concurrent operations.