Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore rules, atomic writes, and write limits

I have a two-part question regarding Firestore rule evaluations. The parts are related which is why the single question here...

Part I - Atomic write access

Let's say that I have a written rule such as

allow write: if resource.data.claimedBy == null && request.data.claimedBy == request.auth.uid;

The idea is that any user can make a claim to this resource. But, what if this resource is made available to 1000 users all at once and they all jump to make a claim and make the .update() call all at the same time?

Will this be a first wins scenario? Firebase will be set as the field for the first user, the winner, and then everyone else will have their writes rejected because the rule would fail due to a value being present from the winner's write? Or is there any risk whatsoever that a race condition could result and somehow for a moment the value was one thing and then became another?

I feel like the rules would prohibit a race condition, but I don't know for certain.

Part II - Write limits

Ok, so this part builds off of the first. Firestore has a write limit of 1 write/second in general for a single document. Let's assume Part I works how I hope and the other 999 users will get a write rejection. Do these rejections count towards the write limit of 1 write/sec because a write was initiated, or do they not count because the rules prohibit an actual write?

Obviously, having all these claim attempts at once count as 1000 writes would be bad for the 1 write/second limit.

I am assuming here, but I believe it would not count toward that limit because my understanding is that the limit is imposed by the nature of the underlying storage mechanics, and the rules prevent going to that layer upon rejection. But also again, I don't know for certain.

Part III - Bonus part

Do writes that are rejected by a rule still count as a "write" as far as billing is concerned? I know a query for a document that does not exist (no documents actually read) still counts as a single read, so I am wondering if writes with regards to rules which prohibit the underlying write works in a similar way and incurs a charge.

Thank you so much!

like image 984
Eric Olson Avatar asked Aug 26 '26 14:08

Eric Olson


1 Answers

You should use a transaction to avoid and prevent concurrent writes. The transaction can check if the document was previously claimed, then abort if it was.

If a write was denied by a rule, it doesn't count toward any write limits or billing, as no data in the document was actually changed.

like image 128
Doug Stevenson Avatar answered Aug 30 '26 04:08

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!