title: ActiveRecord touch causing deadlocks
body: <p>My app uses <code>touch</code> extensively in order to take advantage of Rails' template caching system. There's a certain type of work my app does when many relationships are created between many different objects in a batch. Sometimes, some of this work results in the resulting cascading <code>touch</code>es causing deadlock.</p>
  
  <p>I can code around this for the one scenario where I am seeing it happen often, but seeing it has brought to light the larger problem, which could happen in other scenarios, albeit it's very unlikely.</p>
  
  <p>To understand this, think about two people following one another on Twitter at exactly the same moment. They both click "Follow", resulting in the relationship objects being created between them and then each of their records being <code>touch</code>ed. If these touches become interweaved:</p>
  
  <ol>
  <li>process 1 touches user A</li>
  <li>process 2 touches user B</li>
  <li>process 1 touches user B</li>
  <li>process 2 touches user A</li>
  </ol>
  
  <p>Each process is using a database transaction, so this will result in deadlock.</p>
  
  <p>Am I wrong that this could happen in normal app operation outside of my weird batch job scenario? If I'm not wrong, is there any solution? Can I somehow move the <code>touch</code>es to be outside of the transactions? (Last Write Wins is fine for updating updated_at anyway...)</p>
  
  <p><strong>update - more explanation of data models</strong></p>
  
  <pre><code>class Follow
    belongs_to :follower, touch: true
    belongs_to :followee, touch: true
  end
  
  @u1 = User.find(1)
  @u2 = User.find(2)
  
  # Background Job 1
  Follow.create!(follower: @u1, followee: @u2)
  
  # Background Job 2
  Follow.create!(follower: @u2, followee: @u1)
  </code></pre>