Are N snapshot listeners on the same query priced as a single listener or N listeners

Viewed 106

I have multiple listeners using addSnapshotListener:

db.collection("messages")
   .addSnapshotListener { querySnapshot, error in
      // ...
   }

I understand that the first query snapshot contains all the matching documents. And they are retrieved from the server.

Question: What happens when I call .addSnapshotListener again? Does it still make a call to the server for the initial batch, thus incurring the cost of multiple document reads again?

Logically, I don't see a need to call the server, since it actively monitors for changes so the cached documents shouldn't be stale, but it's unclear what Firebase SDK actually does while the costs could be significant if I call this many times (say, in SwiftUI on each navigation).

1 Answers

I would say that how the SDK does what it does is irrelevant as according to the documentation on billing:

When you listen to the results of a query, you are charged for a read each time a document in the result set is added or updated. You are also charged for a read when a document is removed from the result set because the document has changed. (In contrast, when a document is deleted, you are not charged for a read.)

So even though the SDK, on a second execution of the listener, may call for the whole result set in a of the initial batch in order to check for updates, you will only be charged a read for each document added or updated. Also, in a initial execution you would be charged for reading all the documents of the resulting query.

Also, as mentioned by @bsod in the comments to the question, although not described in any documentation, it is very likely that you won't get charged twice if you have 2 instances of the same listener running in your code, as they would share the connection to the Firestore, making only 1 execution of the listener, although this has to be tested.

That being said, ideally you could try to set a single static listener to avoid any unwanted billing.

Related