Error: 10 ABORTED: Too much contention on these documents. Please try again

前端 未结 6 801
臣服心动
臣服心动 2020-12-10 16:24

What does this error mean?

Especially, what do they mean by : Please try again

Does it mean that the transaction failed I have to re-run the

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 16:59

    Firestore re-runs the transaction only a finite number of times. As of writing, this number is hard-coded as 5, and cannot be changed. To avoid congestion/contention when many users are using the same document, normally we use the exponential back-off algorithm (but this will result in transactions taking longer to complete, which may be acceptable in some use cases).

    However, as of writing, this has not been implemented in the Firebase SDK yet — transactions are retried right away. Fortunately, we can implement our own exponential back-off algorithm in a transaction:

    const createTransactionCollisionAvoider = () => {
      let attempts = 0
      return {
        async avoidCollision() {
          attempts++
          await require('delay')(Math.pow(2, attempts) * 1000 * Math.random())
        }
      }
    }
    

    …which can be used like this:

    // Each time we run a transaction, create a collision avoider.
    const collisionAvoider = createTransactionCollisionAvoider()
    db.runTransaction(async transaction => {
      // At the very beginning of the transaction run,
      // introduce a random delay. The delay increases each time
      // the transaction has to be re-run.
      await collisionAvoider.avoidCollision()
    
      // The rest goes as normal.
      const doc = await transaction.get(...)
      // ...
      transaction.set(...)
    })
    

    Note: The above example may cause your transaction to take up to 1.5 minutes to complete. This is fine for my use case. You might have to adjust the backoff algorithm for your use case.

提交回复
热议问题