Home > Net >  Firestore - Some doubts about Transactions and locking
Firestore - Some doubts about Transactions and locking

Time:01-26

I'm working with the Cloud Functions on a couponing system that assign a coupon to user, when he verifies his mail address.

For my design, I've a /coupons collections with a lot of coupons preloaded.

The user verifies his mail address invoking an HTTP firebase function, into this I would like to assign the coupon to user picking one from coupons collections querying by a field named "userId" on coupons collection.

Sample of query:

const pickOne = () => {
    return firestore
        .collection('coupons')
        .where('userId', "==", 'none')
        .limit(1)
}

I know the Firestore Transactions.

My idea (if possibile) is to invoke pickOne as parameter of transaction get() function, and write value "userId" on it, then close and commit the transaction.

My doubt is related to locking system: is it possible to avoid that concurrent users could have same coupons?

CodePudding user response:

Yes, you can do this type of query in a transaction to effectively find a single document for a user, write their ID in it, and prevent it from being used again in other transactions with the same query. It only works with backend SDKs (like nodejs) and not client SDKs. I've done exactly this sort of things in other projects.

See the API documentation for details.

The only thing you should be aware of is, under high write pressure, the transaction might fail due to being retried too many times. In that case, you would have to either show an error or manually retry in your code.

  •  Tags:  
  • Related