user13290052
user13290052

Reputation:

If I implement onSnapshot real-time listener to Firestore in Cloud Function will it cost more?

I have a listener to Firestore DB changes and it fetches automatically every time there is a change, however, if I decide to implement it in Cloud Function and call it from the client app, will it cost more because it will running 24h/7 even when users are not using the app?

This is in Client side:

     firestore()
            .collection('Collection').doc().collection('public')
            .where('act', '==', 1)
            .orderBy('time', 'asc')
            .limit(10)
            .onSnapshot({
                error: (e) => this.setState({ errorMessage: e, loading: false }),
                next: (querySnapshot) => { this._calculateLocationDistance(querySnapshot) },
            });

Moreover, is it necessary to do it in Cloud Function? Is it risky if I leave it in the client side?

Upvotes: 0

Views: 1058

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317968

You can't really use listeners effectively in Cloud Functions. Cloud Functions are meant to be stateless. They serve a single request at a time, and clean up afterward. If you try to use a listener, it just won't work the way you expect. Cloud Functions also don't keep a socket open to the requester. Once a response is sent, the connection is closed, and there's no way to keep it open.

Given these constraints, functions typically just use get() to fetch data a single time, and return the results to the client. If you want realtime results, that should be implemented on the client.

If you are working with a backend that can keep a socket connection open to a client, it is no less expensive to have a listener on the backend that delivers results to the client. You are still charged a document read for each document read by the listener as it continues to receive results.

Upvotes: 10

Related Questions