Latches and Locks Are Not the Same

You may hear or read about locks and latches and assume these terms are being used interchangeably. After all, if you search for synonyms for the word “lock”, you’ll find “latch” as a potential substitute:

In database terms, lock and latch are similar but have unique purposes of their own. It’s not as simple as “you say toMAYto, I say toMAHto.”

Locks and Latches

What do locks do? Locks are logical and keep transactions consistent from the standpoint of things like rows and tables. You may be familiar with the use of shared locks for reading data, exclusive locks for writing data, etc.

Latches still handle a level of consistency, but not logical. Latches handle the physical aspect of an operation and keep consistency for in-memory data structures.

Another difference is that locks can be controlled by the user, but latches are always going to be managed by SQL Server. For locks, you have the option to use the sp_getapplock and sp_releaseapplock stored procedures to specify locks to use. See this recent post by Andy Brownsword for more details on using these procedures to handle deadlocks.

Types of Latches

I feel like latches get less attention than locks, so we’re going to keep the focus on latches. There are 5 types of latches in SQL Server. Here is a quick rundown of each:

  • Keep Latch (KP) – ensures that a referenced structure cannot be destroyed
  • Shared Latch (SH) – used when a thread needs to read a data page
  • Update Latch (UP) – allows threads to read but prevents any writes, similar to an Update Lock
  • Exclusive Latch (EX) – used when a data structure is modified, similar to an Exclusive Lock
  • Destroy Latch (DT) – used when a data structure is to be destroyed

Latches may be compatible with certain latches but incompatible with others. Microsoft provides a compatibility table to see just that:

If you’re curious about latches, click the link or table above. The whitepaper page has plenty of details explaining latches, handling latch-related issues, and more.

Thanks for reading!

One thought on “Latches and Locks Are Not the Same”

Leave a comment