Search code examples
google-cloud-platformgoogle-cloud-spanner

How to retry Spanner commits that were aborted?


In the Spanner documentation for Commit(), it says:

Commit might return an ABORTED error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If Commit returns ABORTED, the caller should re-attempt the transaction from the beginning, re-using the same session.

https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.Commit

Two Questions:

  1. If the transaction is aborted, do I have to rerun all the statements that were executed from the beginning of the transaction to retry? Or is simply retrying the commit() again sufficient?

  2. How do I reproduce an aborted commit on Spanner to verify my retry logic is correct?


Solution

  • I recommend using the official Cloud Spanner client libraries. They have various transaction runner abstractions that will react to errors appropriately, including retry logic.

    • If a transaction is aborted, the entire transaction should be retried.

    • Cloud Spanner provides no direct way to force a transaction abort. You can set up two transactions to do something like:

      1. BeginTransaction T1
      2. BeginTransaction T2
      3. T1 read row1
      4. T2 read row1
      5. T1 commit (writing row 1) will succeed
      6. T2 commit (writing row 1) will abort