Messaging – Subscribe & Unsubscribe
Overview
Subscribing allows a python application to receive messages published to specific topics or topic patterns. When a subscription is active, the RelayX client opens a live message stream and delivers messages to your handler as they arrive, in real-time.
Subscriptions are how applications react to events in real time. They are commonly used for user events, telemetry, notifications, and system signals. A single client can maintain multiple subscriptions at the same time, each scoped to a different topic or pattern.
Unsubscribing stops message delivery for a topic. This releases resources on both the client and the RelayX backend and should be done when a subscription is no longer needed.
How This Works
When you call the subscribe API, the SDK registers your interest in a topic or topic pattern with the RelayX backend. From that point forward, any message published to a matching topic is delivered to your callback function.
Delivery happens asynchronously. The publisher does not know who is subscribed, and subscribers do not affect publish behavior. Each subscription operates independently.
If the client disconnects due to a network issue, the SDK attempts to reconnect automatically. When reconnection succeeds, messages published while the client was offline are replayed for all active subscriptions. This replay applies only to subscriptions that existed before the disconnect.
API Usage
Subscribing to a Topic
Use the on(topic, handler) method to subscribe.
Parameters
topic(string): A valid topic name or topic pattern. Wildcards*and>are supported.handler(function): A callback invoked for every received message.
Return Value
- Returns
Trueif the subscription was created successfully. - Returns
Falseif:- The topic is already subscribed
- The SDK failed to create the subscription
Unsubscribing from a Topic
Use the off(topic) method to unsubscribe.
Parameters
topic(string): The exact topic or pattern previously subscribed to.
Return Value
- Returns
Trueif the subscription was removed successfully. - Returns
Falseif the unsubscribe operation failed.
Code Example
from relayx_py import Realtime
import os
client = Realtime({
"api_key": os.getenv("RELAYX_API_KEY", None),
"secret": os.getenv("RELAYX_API_SECRET", None)
})
# Subscribe to a topic
def kitchenTemp(data):
# $data is the message the publisher sent
print('Received message:', data)
subscribed = await client.on('devices.kitchen.temperature', kitchenTemp)
if not subscribed:
print('Failed to subscribe to topic')
# Subscribe using wildcards
def kitchenWildcardTemp(data):
print('Temperature update:', data)
"""
Messages from topics that `devices.*.temperature` will be received here
For example,
* devices.kitchen.temperature
* devices.bedroom.temperature
"""
await client.on('devices.*.temperature', kitchenWildcardTemp)
# Unsubscribe from a topic
unsubscribed = await client.off('devices.kitchen.temperature')
if not unsubscribed:
print('Failed to unsubscribe from topic')
Failure & Edge Cases
Network interruptions If the connection drops, the SDK automatically enters a reconnecting state. Messages published during this period are replayed after reconnection for all active subscriptions.
Client crashes If the python process exits, subscriptions are lost. On restart, subscriptions must be recreated explicitly.
Invalid topics Subscription attempts fail if the topic name is invalid or violates topic naming rules. The SDK thows an error immediately. More information here
Duplicate delivery In rare failure scenarios, messages may be delivered more than once. Subscriber logic must be idempotent.
Common Mistakes
Assuming handlers run exactly once RelayX provides at-least-once delivery. Your handler may be invoked more than once for the same message.
Forgetting to unsubscribe Leaving unused subscriptions active consumes resources and may lead to unexpected message handling.
Publishing to wildcards Wildcards are supported only for subscribing, not publishing. Publishing to wildcard topics does not deliver messages.
Ignoring reconnect behavior Applications that do not expect replayed messages may incorrectly process duplicates after reconnect.
Notes & Limitations
- Wildcards are supported only in subscriptions.
- Message replay applies only to subscriptions that existed before disconnect.
- Subscription callbacks must be fast and non-blocking to avoid backpressure.
Join our Discord server, post your concern & someone from our team will help you out ✌️