title: Is it safe to rely on Postgres' deadlock detection for concurrency control?
body: <p>I've been running into occasional deadlocks in my application because two transactions which need to update the same rows but in different orders (ex, transaction A updates rows <em>X</em> then <em>Y</em>, while transaction B updates rows <em>Y</em> then <em>X</em>).</p>
  
  <p>For various Reasons, the traditional approaches to resolving avoiding this kind of deadlock – locking, or updating rows in a consistent order – are less than ideal.</p>
  
  <p>Since the updates I'm trying to perform are otherwise idempotent and order-independent, is it safe and reasonable to simply catch these occasional deadlocks at the application level and retry the transaction?</p>
  
  <p>For example:</p>
  
  <pre class="lang-py prettyprint-override"><code>def process_update(update):
      attempt = 0
      while attempt &lt; 10:
          try:
              execute("SAVEPOINT foo")
              for row in update:
                  execute("UPDATE mytable SET … WHERE …", row)
              execute("RELEASE SAVEPOINT foo")
              break
          except Deadlock:
              execute("ROLLBACK TO SAVEPOINT foo")
          attempt += 1
      raise Exception("Too many retries")
  </code></pre>
  
  <p>Is this a reasonable idea? Or are there costs associated with Postgres' deadlock detection that might make it dangerous?</p>