C-lio Garcia
C-lio Garcia

Reputation: 710

Bulk notifications using firebase cloud functions react native

I'm new on notifications with firebase and Cloud Functions and wondering if even using CF where servers are managed by Firebase's teams and has autoscale, is there a chance, if I was sending 100.000 notifications to my users, to crash my application?

I'm doing something like that:

  1. Someone on the app made a post;
  2. On my CF has a trigger to send notifications for the users;
  3. Then, all users (100.000) received the notifications.

Is Firebase infrastructure has queue or job manage to avoid this kind of situations or can I sleep well like a babe?

Here a snippet of my code:

exports.newPost = functions.database.ref("post/{postId}")
    .onUpdate((change, context) => {
        const before = change.before.val();
        const after = change.after.val();

        if (before.status === after.status) {
            return null;
        }

        const ref = admin.database().ref(`tokens/`);
        return ref.orderByKey().once("value", async snapshot => {

            const fcmTokens = snapshotToArray(snapshot);

            admin.messaging()
                .sendMulticast({
                    data: {},
                    tokens: fcmTokens,
                    notification: {
                        title: 'Title',
                        body: 'Body',
                    },
                    android: {
                        notification: {
                            image: imageUrl,
                        },
                    },
                    apns: {
                        payload: {
                            aps: {
                                "mutable-content": 1,
                            },
                        },
                        fcm_options: {
                            image: imageUrl,
                        },
                    },
                })
                .then(resp => console.log(resp))
                .catch(e => console.log(e))
        })
    })

My questions is: Is there a possible problem with my code?

Upvotes: 0

Views: 561

Answers (2)

Owais ul wara
Owais ul wara

Reputation: 51

The only problem I could see here is the limit to the tokens which can cause the failure of notifications to be delivered.

You’re using sendMulticast which accepts up to 500 FCM Tokens per invocation.

https://firebase.google.com/docs/cloud-messaging/send-message

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317392

There is nothing inherently "bad" with the code you're showing here. FCM regularly sends billions of notifications daily. The hardest part of that isn't even handled by the code you show here - it's handled by FCM servers. The code here is just telling the servers to send those messages, which is requires extremely low effort.

Upvotes: 3

Related Questions