Atlas Robotics
ROS2 BasicsBasic

What is a subscriber in ROS2?

Atlasbot · 16/8/2026 · 10 min read

What is a subscriber in ROS2?
Automatic callback is invoked whenever a new message

If the Publisher is the "say" party, Subscriber is the "hearing" party — a node that wants to receive data from a topic (LiDAR data, control commands, battery states...) will create a Subscriber associated with the topic and the corresponding message type.

Key concepts

Subscriber's most important difference from a manual inquiry: it operates according to the event - driven. When creating a subscriber, the registered node is accompanied by a callback function— this function is automatically called whenever a new message arrives on that topic, the node does not need to actively check ("available data? available data?") in a resource-intensive polling fashion.

The correct callback is the task of the executor— internal mechanism rclpy.spin() that continuously tracks every subscriber/timer/service of the node and calls the corresponding processing function when the event occurs.

Finally: No manual while True: check_for_data() looping — just defining the correct logical callback processing, rclpy.spin() will take care of the "when to call it" part.

How it works

Minimum Subscriber, which prints the velocity each time a new message is received on /cmd_vel:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist

class VelocitySubscriber(Node):
    def __init__(self):
        super().__init__('velocity_subscriber')
        self.subscription = self.create_subscription(
            Twist, '/cmd_vel', self.listener_callback, 10)

    def listener_callback(self, msg):
        # This function is AUTOMATED to be called whenever a new message — does not need manual looping
        self.get_logger().info(f'Nhận được: linear.x = {msg.linear.x}')

def main():
    rclpy.init()
    node = VelocitySubscriber()
    rclpy.spin(node)   # keep node alive, executor calls listener callback when data is available
    rclpy.shutdown()
A new message arrives on /cmd_vel
         ↓
   the executor detects it
         ↓
   calls listener_callback(msg)
         ↓
   the processing code inside the callback runs

An important note when writing callback: should not have long run code (heavy loop, sleep() long) inside the— callback because executors typically process callbacks sequentially on the same stream, a long run callback will prevent the node's (other timer, subscriber) processing of other events until it is completed.

Technical details

Formulas

In order to avoid callbacks being "stuck" (coming messages are faster than processing speed), the processing time per callback should be much less than the cycle between 2 consecutive messages:

Callback processing time must be << 1 / the topic's publishing frequency

Example: a topic publishes at 50Hz (20ms period)
The callback should finish in under ~5-10ms to leave a safety margin,
rather than consuming almost all 20ms — otherwise, even without actually
missing the deadline, the system has almost no margin for jitter or other callbacks

Parameters

Real - world callback processing times vary greatly depending on the type of task — the heavy task needs to be moved out of the primary callback, or use a separate threading/callback group (see Advanced ROS2 section):

Processing type in callbackTypical time
Log, update 1 simple variableLess than 1 ms
Light arithmetic (e.g., unit conversion)Several ms
Image processing (Basic OpenCV)Few tens ms
AI/deep learning inference on imageMaybe 100ms+

Practical applications

Subscriber for secure topics such as /emergency_stop is a good example of a callback that requires to be extremely lightweight and fast — the internal logic should only set 1 state flag (self.estop_triggered = True) and return immediately, so that the reaction latency is always at a minimum; the more complex whole processes (stop the motor, log events, notifications) should be placed elsewhere and this flag should be read periodically, not directly in secure callback — in accordance with the principle of "no block in callback" stated in the Operating Principles section, but here the consequences of the violation are much more severe because of its direct relevance to robot operation safety.

Practical example

# Subscriber as lambda short for simple tasks
self.create_subscription(
    Bool, '/emergency_stop',
    lambda msg: setattr(self, 'estop_triggered', msg.data),
    10)
$ ros2 topic pub /emergency_stop std_msgs/msg/Bool "{data: true}" --once
Output (subscriber node log, if the callback logs messages):
[INFO] [velocity_subscriber]: Nhận được tín hiệu dừng khẩn cấp

The 1-line lambda callback rightly illustrates the principle of "as light as possible" for secure data — that no complex logic can delay the reaction, simply assigning a value to a state variable.

Common mistakes

  • Set long run code inside callback — as stated in Operation Principles section, a delayed callback blocks the entire other event processing of the node (single-stream executor default) — if the node is crypticly "response slow", checking which callback is taking a long time first.
  • Create subscriber but forget rclpy.spin(node) — same error as in Node, do not call spin() and callback will never be executed even if subscriber has created correctly.
  • QoS mismatch with the publisher resulted in no message— subscriber code being completely correct, but if the QoS (reliability, durability) policy is incompatible with the publisher, the non-established connection — has no apparent reporting error, simply callback is never called.
  • Field access does not exist in the message due to erroneous version of the data type— if the custom message definition is changed (add/drop field) but the subscriber has not rebuilt it to the latest version, old/new field access does not match which may cause runtime error — which always rebuilds the entire workspace after fixing the shared message definition.

Conclusion

Subscribers operate in an event-driven model that frees programmers from writing their own polling loops — but in return has to be careful to keep the callback as light as possible, especially with secure associated data. Publisher and Subscriber learned enough to build a complete topic communication between the two nodes. The next article in this issue addresses the Service — feedback-request communication model, which is different from the fire-and-forget type of topic.

Get new articles and lessons by email

When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.

Unsubscribe any time with the link in each email. See our Privacy policy.

What is a subscriber in ROS2? — Atlas Robotics