Push notification API
Centrifugo excels in delivering real-time in-app messages to online users. Sometimes though you need a way to engage offline users to come back to your app. Or trigger some update in the app while it's running in the background. That's where push notifications may be used. Push notifications delivered over battery-efficient platform-dependent transport.
With Centrifugo PRO push notifications may be delivered to all popular application platforms:
- Android devices
- iOS devices
- Web browsers which support Web Push API (Chrome, Firefox, see this matrix)
Centrifugo PRO provides API to manage user device tokens, device topic subscriptions and API to send push notifications towards registered devices and group of devices (subscribed to a topic). API also supports timezone-aware push notifications, push localizations, templating and per user device push rate limiting. You can also use your own device token storage and use Centrifugo PRO as a high-performance way to send push notifications to supported providers.
To deliver push notifications to devices Centrifugo PRO integrates with the following providers:
- Firebase Cloud Messaging (FCM)
- Huawei Messaging Service (HMS) Push Kit
- Apple Push Notification service (APNs)
FCM, HMS, APNs handle the frontend and transport aspects of notification delivery. Device token storage, management and efficient push notification broadcasting is managed by Centrifugo PRO. Tokens are stored in a PostgreSQL database. To facilitate efficient push notification broadcasting towards devices, Centrifugo PRO includes worker queues based on Redis streams (and also provides and option to use PostgreSQL-based queue).
Integration with FCM means that you can use existing Firebase messaging SDKs to extract push notification token for a device on different platforms (iOS, Android, Flutter, web browser) and setting up push notification listeners. The same for HMS and APNs - just use existing native SDKs and best practices on the frontend. Only a couple of additional steps required to integrate frontend with Centrifugo PRO device token and device topic storage. After doing that you will be able to send push notification towards single device, or towards group of devices subscribed to a topic. For example, with a simple Centrifugo API call like this:
curl -X POST http://localhost:8000/api/send_push_notification \
-H "Authorization: apikey <KEY>" \
-d @- <<'EOF'
{
"recipient": {
"filter": {
"topics": ["test"]
}
},
"notification": {
"fcm": {
"message": {
"notification": {"title": "Hello", "body": "How are you?"}
}
}
}
}
EOF
In addition, Centrifugo PRO includes a helpful web UI for inspecting registered devices and sending push notifications:
Motivation and design choices
Centrifugo PRO tries to be practical with its Push Notification API, let's look at its design choices and implementation properties.
Storage for tokens
To start delivering push notifications in the application, developers usually need to integrate with providers such as FCM, HMS, and APNs. This integration typically requires the storage of device tokens in the application database and the implementation of sending push messages to provider push services.
Centrifugo PRO simplifies the process by providing a backend for device token storage, following best practices in token management. It reacts to errors and periodically removes stale devices/tokens to maintain a working set of device tokens based on provider recommendations.
Efficient queuing
Additionally, Centrifugo PRO provides an efficient, scalable queuing mechanism for sending push notifications. Developers can send notifications from the app backend to Centrifugo API with minimal latency and let Centrifugo process sending to FCM, HMS, APNs concurrently using built-in workers. In our tests, we achieved several millions pushes per minute.
Centrifugo PRO also supports delayed push notifications feature – to queue push for a later delivery, so for example you can send notification based on user time zone and let Centrifugo PRO send it when needed.
Unified secure topics
FCM and HMS have a built-in way of sending notification to large groups of devices over topics mechanism (the same for HMS). Topics are great since you can create segments and groups of devices and target specific ones with your notifications.
One problem with native FCM or HMS topics though is that client can subscribe to any topic from the frontend side without any permission check. In today's world this is usually not desired. So Centrifugo PRO re-implements FCM, HMS topics by introducing an additional API to manage device subscriptions to topics.
In some cases you may have real-time channels and device subscription topics with matching names – to send messages to both online and offline users. Though it's up to you.
Centrifugo PRO device topic subscriptions also add a way to introduce the missing topic semantics for APNs.
Centrifugo PRO additionally provides an API to create persistent bindings of user to notification topics. Then – as soon as user registers a device – it will be automatically subscribed to its own topics. As soon as user logs out from the app and you update user ID of the device - user topics binded to the device automatically removed/switched. This design solves one of the issues with FCM – if two different users use the same device it's becoming problematic to unsubscribe the device from large number of topics upon logout. Also, as soon as user to topic binding added (using user_topic_update
API) – it will be synchronized across all user active devices. You can still manage such persistent subscriptions on the application backend side if you prefer and provide the full list inside device_register
call.
Push personalization
Centrifugo PRO provides several ways to make push notifications individual and take care about better user experience with notifications. This includes:
- Timezone-aware push notifications
- Notification templating
- Notification localizations
- Per user device rate limiting
All these features may be used on individual request basis.
Non-obtrusive proxying
Unlike other solutions that combine different provider push sending APIs into a unified API, Centrifugo PRO provides a non-obtrusive proxy for all the mentioned providers. Developers can send notification payloads in a format defined by each provider.
It's also possible to send notifications into native FCM, HMS topics or send to raw FCM, HMS, APNs tokens using Centrifugo PRO's push API, allowing them to combine native provider primitives with those added by Centrifugo (i.e., sending to a list of device IDs or to a list of topics).
Builtin analytics
Furthermore, Centrifugo PRO offers the ability to inspect sent push notifications using ClickHouse analytics. Providers may also offer their own analytics, such as FCM, which provides insight into push notification delivery. Centrifugo PRO also offers a way to analyze push notification delivery and interaction using the update_push_status
API.
Steps to integrate
- Add provider SDK on the frontend side, follow provider instructions for your platform to obtain a push token for a device. For example, for FCM see instructions for iOS, Android, Flutter, Web Browser). The same for HMS or APNs – frontend part should be handled by their native SDKs.
- Call Centrifugo PRO backend API with the obtained token. From the application backend call Centrifugo
device_register
API to register the device in Centrifugo PRO storage. Optionally provide list of topics to subscribe device to. - Centrifugo returns a registered device object. Pass a generated device ID to the frontend and save it on the frontend together with a token received from FCM.
- Call Centrifugo
send_push_notification
API whenever it's time to deliver a push notification.
At any moment you can inspect device storage by calling device_list
API.
Once user logs out from the app, you can detach user ID from device by using device_update
or remove device with device_remove
API.
Configuration
In Centrifugo PRO you can configure one push provider or use all of them – this choice is up to you.
FCM
As mentioned above, Centrifugo uses PostgreSQL for token storage. To enable push notifications make sure database
section defined in the configration and fcm
is in the push_notifications.enabled_providers
list. Centrifugo PRO uses Redis for queuing push notification requests, so Redis address should be configured also. Finally, to integrate with FCM a path to the credentials file must be provided (see how to create one in this instruction). So the full configuration to start sending push notifications over FCM may look like this:
{
"database": {
"enabled": true,
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/postgres"
}
},
"push_notifications": {
"queue": {
"redis": {
"address": "localhost:6379"
}
},
"enabled_providers": [
"fcm"
],
"fcm": {
"credentials_file": "/path/to/service/account/credentials.json"
}
}
}
Actually, PostgreSQL database configuration is optional here – you can use push notifications API without it. In this case you will be able to send notifications to FCM, HMS, APNs raw tokens, FCM and HMS native topics and conditions. I.e. using Centrifugo as an efficient proxy for push notifications (for example if you already keep tokens in your database). But sending to device ids and topics, and token/topic management APIs won't be available for usage.
HMS
{
"database": {
"enabled": true,
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/postgres"
}
},
"push_notifications": {
"queue": {
"redis": {
"address": "localhost:6379"
}
},
"enabled_providers": [
"hms"
],
"hms": {
"app_id": "<your_app_id>",
"app_secret": "<your_app_secret>"
}
}
}
See example how to get app id and app secret here.
APNs
{
"database": {
"enabled": true,
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/postgres"
}
},
"push_notifications": {
"queue": {
"redis": {
"address": "localhost:6379"
}
},
"enabled_providers": [
"apns"
],
"apns": {
"endpoint": "development",
"bundle_id": "com.example.your_app",
"token_key_file": "/path/to/auth/key/file.p8",
"token_key_id": "<your_key_id>",
"token_team_id": "your_team_id"
}
}
}
We also support auth over p12 certificates with the following options:
push_notifications.apns.cert_p12_file
push_notifications.apns.cert_p12_b64
push_notifications.apns.cert_p12_password
Other options
push_notifications.max_inactive_device_interval
This duration option configures the max time interval to keep device without updates. By default, Centrifugo does not remove inactive devices.
push_notifications.dry_run
Boolean option, when true
Centrifugo PRO does not send push notifications to FCM, APNs, HMS providers but instead just print logs. Useful for development.
push_notifications.dry_run_latency
Duration. When set together with push_notifications.dry_run
every dry-run request will cause some delay in workers emulating real-world latency. Useful for development.
push_notifications.read_from_replica
Boolean option, when true Centrifugo will use configured PostgreSQL replicas for push notifications read API where possible. Also, replicas will also be used during brodcasting push notifications. This configuration enables efficient scaling of read operations.
Adding push_notifications.read_from_replica
option requires setting database.replica_dsn
option – which is an array of strings containing PostgreSQL replica DSNs. So config may look like this:
{
"database": {
"enabled": true,
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/postgres",
"replica_dsn": [
"postgresql://postgres:[email protected]:5433/postgres"
]
}
},
"push_notifications": {
"read_from_replica": true
}
}
Use PostgreSQL as queue
Centrifugo PRO utilizes Redis Streams as the default queue engine for push notifications. However, it also offers the option to employ PostgreSQL for queuing. It's as simple as:
{
"database": {
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/postgres"
},
"enabled": true
},
"push_notifications": {
"queue": {
"type": "postgresql",
"postgresql": {
"reuse_from_database": true
}
}
}
}
Queue based on Redis streams is generally more efficient, so if you start with PostgreSQL based queue – you have an option to switch to a more performant implementation later. Though in-flight and currently queued push notifications will be lost during a switch.
You can also use separate PostgreSQL instance for push notification queue, which may be beneficial:
{
...
"push_notifications": {
"queue": {
"type": "postgresql",
"postgresql": {
"dsn": "postgresql://postgres:[email protected]:5432/push_queue"
}
}
}
}
API description
Push notifications of Centrifugo PRO come with a set of additional server API methods.
device_register
Registers or updates device information.
device_register request
Field | Type | Required | Description |
---|---|---|---|
id | string | No | ID of the device being registered (provide it when updating). |
provider | string | Yes | Provider of the device token (valid choices: fcm , hms , apns ). |
token | string | Yes | Push notification token for the device. |
platform | string | Yes | Platform of the device (valid choices: ios , android , web ). |
user | string | No | User associated with the device. |
timezone | string | No | Timezone of device user (IANA time zone identifier, ex. Europe/Nicosia ). See Timezone aware push |
locale | string | No | Locale of device user. Must be IETF BCP 47 language tag - ex. en-US , fr-CA . See Localizations |
topics | array[string] | No | Device topic subscriptions. This should be a full list which replaces all the topics previously accociated with the device. User topics managed by UserTopic model will be automatically attached. |
meta | map[string]string | No | Additional custom metadata for the device |
device_register result
Field Name | Type | Required | Description |
---|---|---|---|
id | string | Yes | The device ID that was registered/updated. |
device_update
Call this method to update device. For example, when user logs out the app and you need to detach user ID from the device.
device_update request
Field | Type | Required | Description |
---|---|---|---|
ids | array[string] | No | Device ids to filter |
users | array[string] | No | Device users filter |
user_update | DeviceUserUpdate | No | Optional user update object |
timezone_update | DeviceTimezoneUpdate | No | Optional timezone update object |
locale_update | DeviceLocaleUpdate | No | Optional locale update object |
meta_update | DeviceMetaUpdate | No | Optional device meta update object |
topics_update | DeviceTopicsUpdate | No | Optional topics update object |
DeviceUserUpdate
:
Field | Type | Required | Description |
---|---|---|---|
user | string | Yes | User to set |
DeviceTimezoneUpdate
:
Field | Type | Required | Description |
---|---|---|---|
timezone | string | Yes | Timezone to set |
DeviceLocaleUpdate
:
Field | Type | Required | Description |
---|---|---|---|
locale | string | Yes | Locale to set |
DeviceMetaUpdate
:
Field | Type | Required | Description |
---|---|---|---|
meta | map[string]string> | Yes | Meta to set |
DeviceTopicsUpdate
:
Field | Type | Required | Description |
---|---|---|---|
op | string | Yes | Operation to make: add , remove or set |
topics | array[string] | Yes | Topics for the operation |
device_update result
Empty object.
device_remove
Removes device from storage. This may be also called when user logs out the app and you don't need its device token after that.
device_remove request
Field Name | Type | Required | Description |
---|---|---|---|
ids | array[string] | No | A list of device IDs to be removed |
users | array[string] | No | A list of device user IDs to filter devices to remove |
device_remove result
Empty object.
device_list
Returns a paginated list of registered devices according to request filter conditions.