October 25, 2014

One more InnoDB gap lock to avoid

While troubleshooting deadlocks for a customer, I came around an interesting situation involving InnoDB gap locks. For a non-INSERT write operation where the WHERE clause does not match any row, I expected there should’ve been no locks to be held by the transaction, but I was wrong. Let’s take a look at this table and and example UPDATE.

InnoDB status shows that this UPDATE holds an X lock on a PRIMARY index record:

For the why, Heikki explained on this aging bug report, which makes sense and I understand the fix can be difficult, though at the same time a bit annoying I wished it was handled differently. To complete this post, let me demonstrate the deadlock situation I was telling about earlier mysql1 for first session and mysql2 for the second, the order of queries apply:

So you see how easy it is to cause a deadlock, so make sure to avoid this situation – if a non-INSERT write operation is more likely to not match any row because the INSERT part is yet to come on the transaction, don’t do it or use REPLACE INTO or use READ-COMMITTED transaction isolation.

About Jervin Real

Jervin is a member of Percona's Rapid Response Consulting team. When you come to Percona for consulting, chances are he'll be greeting you first. His primary role is to make sure customer issues are handled efficiently and professionally. Jervin joined Percona in April 2010.

Comments

  1. Jervin,

    So are you saying REPLACE INTO would not have set the lock in this case ? Why is its handling different ?

    Also you mention it does not happen with READ-COMMITTED. Is it the case with both ROW and STATEMENT replication modes ?

  2. ferny says:

    Yo mean REPLACE INTO does not create gap lock?

  3. Jervin Real says:

    @Peter, @ferny,

    REPLACE INTO sets the same lock, but in the context of the deadlock example I gave, it prevents premature locking in turn avoiding the deadlock. Also, READ-COMMITTED only works with ROW binlog format.

Speak Your Mind

*