0

so I'm building kind of a social app in react native and firestore. I want to let a user "favorite" a shop . I added a favoritesShops array in my user doc cause I need to compare the nearby shops id to the ones containg in this array. I also have another collection for analytics that let me save a doc in this structure userId+"@"+ShopId and the status: 1 for "favorite" and -1 for "not favorite". For now I made a button next to each shop to favorite the shop. So each click triggers a batch.set on analytics and batch.update on the array. Everything works as expected but now a single user can spam the "favorite" button trigerring a lot of batch writes for each 1 or -1 (and updating the array). So my question is, how do i prevent this?

julia
  • 11
  • 3
  • To implement a write rate limit per user, see https://stackoverflow.com/questions/56487578/how-do-i-implement-a-write-rate-limit-in-cloud-firestore-security-rules/56487579#56487579 – Frank van Puffelen Jun 23 '21 at 13:58
  • hey @FrankvanPuffelen I thought about that but in that case if user spam the button and rules doesnt let it update then when will the batch commit? Since batch fails doesnt retry maybe I should use transaction but I'm not sure if unsuccessful transactions are charged – julia Jun 23 '21 at 20:24
  • If save the users uid along with their vote, then they can click favorite all day long and it will keep overwriting their own node so the count will not change. e.g. if the structure has *shops* and then documents that store the users who have marked that shop as their favorite, just store the document as the users uid as the documentID and a field favorite as true of false. Just a thought. – Jay Jun 24 '21 at 19:12

1 Answers1

1

You can add a listener that captures the value after the change and wait 1+ seconds before committing the changes. this ensures that users can spam the button multiple times, but once they stop, it'll update.

You want to emulate the change on the client to keep the user experience updated. Make sure you are tracking the change in the root of your app to process it if the user switches away rapidly.

Another solution that you can also implement is a "lastLiked" for each user, this would double all reads and writes, but you can use this value in Security Rules to deny frequent changes. but it is read/write heavy and should be used only if needed.

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20
  • I like the first idea. What do you think of changing the batch to transaction and adding firebase rule to prevent to many update like @FrankvanPuffelen suggested. I could retry the transaction until rules let me update. But I can't find anything about the cost of failed transaction. I'm not sure if they are billed or not – julia Jun 23 '21 at 20:27