How to Use Google Firebase Cloud Messaging (FCM) Topic Subscriptions to Deliver Targeted Background Push Notifications

Modern Android applications rely heavily on real-time data delivery to keep users engaged. However, maintaining persistent background socket connections on millions of distributed mobile devices rapidly depletes battery life and consumes excessive bandwidth. To solve this, developers must utilise Google Firebase Cloud Messaging (FCM). While FCM supports direct device-to-device messaging using Registration Tokens, this approach scales poorly when attempting to broadcast a message to thousands of users simultaneously (e.g., breaking news alerts or live sports scores). For massive, segmented broadcasts, developers must implement FCM Topic Subscriptions, allowing the backend server to publish a single message that Google’s infrastructure autonomously fans out to millions of targeted devices.

Understanding the Pub/Sub Architecture

FCM Topics operate on a classic Publish/Subscribe (Pub/Sub) pattern. Rather than your backend server maintaining a massive database of millions of individual Android device tokens and iterating through them to send a push notification, the logic is reversed. The Android client application proactively subscribes to a specific string identifier—a “topic.” When the backend server needs to send an alert, it fires a single HTTP request to the Firebase API targeting that topic string. Google’s internal infrastructure instantly handles the complex routing required to deliver the payload to every subscribed device globally.

Implementing Topic Subscriptions in Android

To enable this, the Android application must explicitly tell the Firebase SDK to subscribe to a topic. This is typically done upon application launch, after user authentication, or when the user toggles a specific setting within the app’s notification preferences.

Assuming the Firebase SDK is already initialized in your build.gradle, you invoke the subscribeToTopic() method. Because this requires a network request to Google’s servers, it returns a Task that you should monitor for success or failure.

FirebaseMessaging.getInstance().subscribeToTopic("sports_news_uk")
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            String msg = "Subscribed to UK Sports News";
            if (!task.isSuccessful()) {
                msg = "Subscription failed";
            }
            Log.d("FCM_TOPIC", msg);
        }
    });

A single Android client can subscribe to up to 2,000 distinct topics, allowing for highly granular user segmentation.

Publishing Messages from the Backend

Once clients are subscribed, your backend infrastructure (Node.js, Python, Java, etc.) can trigger the push notifications. While you can send messages using the Firebase Console GUI, production environments require programmatic execution via the Firebase Admin SDK.

In a Node.js environment, the code to publish a targeted broadcast is exceptionally clean. Instead of providing an array of device tokens, you simply provide the topic key in the message payload.

const admin = require('firebase-admin');
admin.initializeApp();

const message = {
  notification: {
    title: 'Goal! Manchester United scores!',
    body: 'Latest update from Old Trafford.'
  },
  topic: 'sports_news_uk'
};

admin.messaging().send(message)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Leveraging Condition Expressions

The true power of FCM topics lies in the backend’s ability to construct complex Boolean logic using Condition Expressions. Instead of sending a message to a single topic, your backend can target users who are subscribed to combinations of topics.

For example, if you want to send a push notification only to users who are subscribed to both “sports_news_uk” AND “premium_subscriber”, you format the condition key in the payload:

const message = {
  notification: {
    title: 'Exclusive Post-Match Interview',
    body: 'Available now for premium members.'
  },
  condition: "'sports_news_uk' in topics && 'premium_subscriber' in topics"
};

This offloads the entirety of the database querying and segmentation logic onto Google’s infrastructure, allowing a single backend API call to instantly and securely reach the exact target demographic without ever exposing individual user tokens.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.