Cron PHP script for Firebase Cloud Messaging Service with rate-limit




Today I would like to share with you how to create a php script that will send Firebase Cloud Messages to your users with rate-limit control.



For those who don't know, Firebase Cloud Messaging is a service offered by Google that enables app developers who use Firebase to send push notifications to your app users. Firebase has a specific rate-limit for 1000 messages to your users.

For developers who have less than 1000 of users this won't be a problem. The challenge comes when you  have more than 1000 users and you want to send push notifications to all of them at once. That's when rate-limit script come in play.

In order for you to control the frequency and the time between sending push notifications then you may consider using  the following algorithm.


  1. First you have to grab all your FCM ids also known as FCM tokens, these are used to uniquely identify each device that is going to receive the push notifications. This can either be stored in the data base or anywhere that you normally store your FCM ids. 
  2. Secondly you will have to store all the FCM ids into an array and chunk them into smaller arrays of 1000 elements. 
  3. Thirdly you have to create a variable that will store the number of chunk arrays. 
  4. Create another variable that will store the timestamp using the php inbuilt time function. 
  5. Create another variable which will temporary hold the time for the next execution of sending push notifications. 
  6. Create another variable and set its value 20 this will be used to control a while loop. 
  7. Create a while loop, inside the condition expression you have to set the variable that holds the value 0 and it should be less than the variable that holds the number of chunk arrays. 
  8. In the body of the while loop start with an if statement which compares the current timestamp and the timestamp for the next execution. In the body of the if statement creates a variable which will store the batches of FCM ids and remember to encode them into JSON before sending them to the google FCM server for push notifications using the  
  9. In the else statement body, you can then re instantiate the variable which holds the timestamp so as it can be rechecked to c if the amount of waiting time has been achieved for the next iteration. 

This algorithm can be used with any API that has rate-limit associated with it. 

You can download the source code on the github repository which I created using the link below.




No comments

Powered by Blogger.