Introduction
ROS2 Topics are a key part of the Robot Operating System 2 (ROS2), a robust and flexible framework for building modern robotic applications. Designed to support real-time systems and distributed computing, ROS2 is ideal whether you’re working on a mobile robot, robotic manipulator, or sensor network. Understanding the core communication mechanisms, Topics, Services, and Actions, is fundamental to architecting efficient robotic systems.
Each of these communication methods addresses a specific type of interaction between nodes in a ROS2 system. Misusing them can lead to inefficiencies, bugs, or sluggish robot performance. In this beginner-friendly guide, we will explore what Topics, Services, and Actions are, their distinct purposes, when to use them, and how to implement them in practice. This blog is ideal for those starting their journey into ROS2 development.
Understanding ROS2 Communication Mechanisms
At the heart of any ROS2-based system are nodes—independent processes that communicate over well-defined interfaces. ROS2 Topics, along with services and actions, provide the three primary mechanisms for node-to-node communication.
- Topics for streaming data
- Services for synchronous requests
- Actions for long-duration goals with feedback
Let’s explore each of them in detail.
Topics
ROS2 Topics are the backbone of most real-time ROS2 communication. They follow a publisher-subscriber model, where one or more nodes publish data, and other nodes subscribe to receive that data. Topics are ideal for high-frequency, asynchronous communication.
Key Characteristics of Topics:
- Unidirectional: Data flows from publisher to subscriber
- Asynchronous: No waiting or blocking; publishers send messages regardless of subscriber state
- Many-to-Many Relationships: Multiple publishers and subscribers can coexist
- Real-Time Streaming: Ideal for continuous data like sensor streams
Real-World Example:
A mobile robot with a LiDAR sensor continuously publishes distance data to a /scan topic. Several nodes—like localization, obstacle avoidance, and SLAM—subscribe to this topic to process data in real-time.
Common Use Cases:
- IMU or GPS data streaming
- Camera or LiDAR feeds
- Status updates from hardware
- Motor encoder feedback
Services
Services provide a synchronous, two-way communication model. A node (client) sends a request to a service (server), waits for it to be processed, and receives a response. It’s a blocking interaction, suited for operations requiring an immediate answer.
Key Characteristics of Services:
- Bidirectional: Request from client, response from server
- Synchronous: Client waits for a response before proceeding
- One-to-One Communication: Request targets a single server
- Atomic Tasks: Ideal for quick, clearly defined operations
Real-World Example:
A monitoring node sends a request to a /get_battery_level service on the robot. The power management server reads and returns the current voltage level.
Common Use Cases:
- Set or retrieve configuration parameters
- Request robot state or location
- Perform calibration routines
- Reset or reboot subsystems
Actions
Actions are suited for long-running operations that need progress tracking and optional cancellation. They offer a goal-feedback-result pattern and blend the asynchronous nature of Topics with the structure of Services.
Key Characteristics of Actions:
- Goal-Oriented: Client sends a goal to the server
- Feedback Support: Periodic progress updates available
- Cancelable: Tasks can be stopped during execution
- Asynchronous Execution: Non-blocking operation with monitoring
Real-World Example:
A robotic arm receives a goal to pick and place an object. The action server updates the client on progress stages (e.g., “reaching,” “grasping,” “placing”) and can cancel the task if the object is moved or an error occurs.
Common Use Cases:
- Navigate to a target location
- Execute arm manipulation tasks
- Start and monitor charging sequence
- Run multi-step autonomous routines
Comparison: Topics vs Services vs Actions
Feature | Topics | Services | Actions |
Communication Type | Unidirectional (Pub/Sub) | Bidirectional (Req/Resp) | Bidirectional with Feedback |
Synchronization | Asynchronous | Synchronous | Asynchronous |
Use Case | Continuous Data Streams | Quick Requests | Long-running Tasks |
Feedback Support | No | No | Yes |
Cancellation | No | No | Yes |
Complexity | Low | Medium | High (requires .action file) |
Implementing ROS2 Topics, Services, and Actions in Python
Let’s look at simple examples using rclpy to illustrate how to use each mechanism.
Topics: Publishing and Subscribing
Publisher Node
python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class PublisherNode(Node):
def __init__(self):
super().__init__(‘publisher_node’)
self.publisher_ = self.create_publisher(String, ‘topic’, 10)
self.timer = self.create_timer(0.5, self.timer_callback)
def timer_callback(self):
msg = String()
msg.data = ‘Hello, ROS2!’
self.publisher_.publish(msg)
self.get_logger().info(f’Publishing: “{msg.data}”‘)
Subscriber Node
python
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class SubscriberNode(Node):
def __init__(self):
super().__init__(‘subscriber_node’)
self.subscription = self.create_subscription(String, ‘topic’, self.listener_callback, 10)
def listener_callback(self, msg):
self.get_logger().info(f’Received: “{msg.data}”‘)
Services: Client and Server
Service Server
python
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts
class ServiceServerNode(Node):
def __init__(self):
super().__init__(‘service_server_node’)
self.srv = self.create_service(AddTwoInts, ‘add_two_ints’, self.add_callback)
def add_callback(self, request, response):
response.sum = request.a + request.b
self.get_logger().info(f’Request: {request.a} + {request.b} = {response.sum}’)
return response
Service Client
python
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts
class ServiceClientNode(Node):
def __init__(self):
super().__init__(‘service_client_node’)
self.client = self.create_client(AddTwoInts, ‘add_two_ints’)
while not self.client.wait_for_service(timeout_sec=1.0):
self.get_logger().info(‘Waiting for service…’)
self.request = AddTwoInts.Request()
self.request.a = 2
self.request.b = 3
self.future = self.client.call_async(self.request)
Actions: Setting Goals and Receiving Feedback
Implementing actions requires defining a .action file, generating interfaces, and writing both server and client nodes. It’s more involved than Topics or Services.
For a full guide, refer to the official ROS2 Actions tutorial.
Practical Applications in Robotics
Communication Type | Use Case Examples |
Topics | Stream IMU data, camera feed, GPS updates, joint states |
Services | Set robot modes, calibrate sensors, request diagnostics |
Actions | Navigate to waypoint, execute arm task, charging routine |
By aligning your communication mechanism with application needs, your system becomes more modular, responsive, and scalable.
Frequently Asked Questions (FAQs)
1. Can I use Actions instead of Services for everything?
Technically yes, but it’s not ideal. Actions introduce additional complexity and overhead. Use Services for quick, atomic operations and Actions only when progress monitoring or cancellation is needed.
2. What happens if a Topic has no subscribers?
The publisher still works and sends messages, but no node will receive them. This doesn’t cause errors unless your logic depends on acknowledgment or feedback.
3. Can one node both publish and subscribe to the same Topic?
Yes. This is common in control loops or monitoring systems where the node needs to track what it’s publishing.
4. Are Services and Actions reliable for critical safety operations?
Services are reliable but blocking; they depend on the server’s availability. Actions are good for controlled tasks with feedback but add complexity. For safety-critical functions, consider implementing watchdogs or fallback systems.
5. How do I choose between ROS2 Topics, Services, and Actions?
Use this rule of thumb:
- Use Topics for streaming sensor or state data
- Use Services for requests that expect quick replies
- Use Actions for tasks that require monitoring or cancellation
Additional Resources
- ROS2 Documentation (Official): Core concepts, API references, and tutorials
- AutomaticAddison.com – Topics vs Services vs Actions: Clear beginner-friendly comparison with visuals and real-world use cases
Continue Learning ROS2
To deepen your understanding of ROS2 Topics and apply these concepts in real robotics projects, explore the Robotisim ROS2 Tutorial Series. Learn how to build a robot using Raspberry Pi, microcontrollers, and real-world ROS2 patterns from scratch.