Skip to content

How to Choose ROS 2 Communication Primitives: Node, Topic, Service, Action, TF2, and QoS Guide

Compare ROS 2 Jazzy nodes, topics, services, actions, parameters, and TF2 by coupling and duration, with Python rclpy examples for sensor and command QoS profiles.

Contents

Key takeaways

  1. Choosing between Topics, Services, and Actions depends on two engineering axes—coupling and task duration: continuous state streams use Topics, sub-second synchronous queries use Services, and multi-second preemptible tasks with progress feedback use Actions.
  2. Production QoS defaults follow physical data behavior: high-rate sensors use best_effort + volatile + depth 5, velocity commands use reliable + volatile + depth 10, and static maps or URDF descriptions use reliable + transient_local + depth 1.
  3. Parameters expose runtime configuration knobs without recompiling code, while TF2 maintains a time-stamped tree of 3D coordinate transforms connecting every sensor frame to the robot base and world map.
  4. Because a default SingleThreadedExecutor processes callbacks sequentially, blocking inside a service or image callback stalls velocity and timer callbacks unless isolated via callback groups, MultiThreadedExecutor, or an Action server.

During the early design phase of a robotics software stack, one architectural question comes up repeatedly: “Should we pass this data over a Topic, wrap it in a Service, or build an Action server?” When Parameters, TF2 coordinate frames, Executors, and Launch files enter the picture at the same time, it is tempting to fall back on familiar Publisher and Subscriber topics for every single interaction.

However, just as our analysis of 2WD mobile robot hardware layers and five core components partitioned electronics by execution cycle time, and our deep dive into ROS 2 Jazzy DDS architecture and the RMW layer showed how discovery and QoS contracts govern transport, ROS 2 communication primitives partition software along two strict engineering axes: inter-node coupling and task duration. Once a team decides when to adopt ROS 2 in a Physical AI project, mastering these interface boundaries is the fastest way to prevent deadlocks and silent packet drops. Using the myros_sketch differential-drive robot as a concrete example, this tutorial walks through Nodes, Topics, Services, Actions, production QoS profiles in rclpy, Parameters, TF2 trees, and Launch files with step-by-step CLI verification.

1. Nodes: Modular Execution Units Defined by Single Responsibility and Replaceability

A Node is the fundamental unit of computation in a ROS 2 graph, responsible for one well-scoped task. In ROS 2 Jazzy, a node does not have to map 1:1 to an operating system process; multiple nodes can be composed into a single process as Composable Nodes to exchange messages via zero-copy shared memory pointers.

The practical litmus test for a well-designed node boundary is replaceability. If you swap the 2D LiDAR on myros_sketch from one manufacturer’s unit to another, or switch from a real robot to Gazebo simulation, the SLAM and navigation nodes should require zero source code edits. To achieve that isolation, myros_sketch divides responsibilities across focused nodes:

  • lidar_driver: Reads raw serial packets from the laser scanner and publishes only /scan (sensor_msgs/msg/LaserScan).
  • camera_driver: Captures USB frames and publishes /camera/image_raw alongside calibration metadata on /camera/camera_info.
  • esp32_bridge (via micro-ROS Agent): Subscribes to /cmd_vel to drive the 200 Hz motor loop on the ESP32-S3, while publishing wheel odometry (/odom) and inertial data (/imu/data).
  • robot_state_publisher: Parses the robot’s URDF description and broadcasts fixed and movable link transforms onto /tf_static and /tf.
# Run a standard C++ demo node and inspect its full interface contract (publishers, subscribers, services)
ros2 run demo_nodes_cpp talker
ros2 node list
ros2 node info /talker

The output of ros2 node info <node_name> acts as the node’s public API specification, listing every topic, service, and action endpoint it exposes to the DDS domain.

2. Topics, Services, and Actions: Selecting Communication Patterns by Coupling and Duration

As outlined in the official ROS 2 Jazzy core concepts documentation, Topics, Services, and Actions solve three distinct synchronization problems.

Topics: Continuous State and Sensor Streams (Many-to-Many · Unidirectional · Asynchronous)

A Topic is an asynchronous, many-to-many (N:M) publish-subscribe data stream. The publisher pushes samples onto the bus without knowing—or caring—whether zero, one, or ten subscribers are listening. This loose coupling is what makes ROS 2 extensible: you can attach rviz2 for 3D visualization or ros2 bag record for data logging while the robot is driving, without touching the navigation nodes.

myros_sketch Topic NameMessage TypeTarget RateWhy a Topic Is the Correct Primitive
/scansensor_msgs/msg/LaserScan10 HzContinuously refreshed planar range array; stale scans are obsolete
/imu/datasensor_msgs/msg/Imu100 HzHigh-frequency inertial stream consumed by odometry fusion filters
/odomnav_msgs/msg/Odometry50 HzContinuously integrated pose and twist estimate from wheel encoders
/cmd_velgeometry_msgs/msg/Twist20 HzStreamed velocity setpoints feeding the MCU watchdog loop
/tftf2_msgs/msg/TFMessage50–100 HzDynamic coordinate frame transforms broadcast to all perception nodes

The limitation of a topic is that it is fire-and-forget: publishing a message on /cmd_vel gives the caller no confirmation that the robot actually reached a target distance or executed a state transition.

Services: Sub-Second Synchronous Transactions (One-to-One · Bidirectional · Request/Response)

A Service implements a synchronous request-response remote procedure call (RPC). A client sends a request payload and waits for the server to return a single response payload. Services are designed for short, discrete operations whose outcome is determined immediately (within a few milliseconds to a few hundred milliseconds):

  • /reset_odometry (std_srvs/srv/Trigger): Zeroes out integrated wheel odometry coordinates.
  • /set_motor_enable (std_srvs/srv/SetBool): Enables or disables H-bridge motor torque.
  • /get_parameters and /set_parameters: Queries or modifies node configuration at runtime.

A strict architectural rule applies to services: never perform long blocking loops or multi-second physical motion inside a service callback. While a service callback is executing, a default single-threaded executor cannot process incoming sensor topics or watchdog timers.

Actions: Long-Running, Preemptible Goals with Continuous Feedback

An Action is built for tasks that span several seconds to several minutes—such as driving across a building (nav2_msgs/action/NavigateToPose), docking onto a charging station, or executing a multi-waypoint arm trajectory. Under the hood, an action combines two services (Goal submission and Cancel request) with two topics (periodic Feedback stream and final Result notification) into a state machine.

Decision CriterionTopicServiceAction
Communication PatternPublish-Subscribe (unidirectional stream)Request-Response (single round-trip RPC)Goal-Feedback-Result (stateful machine)
Inter-Node CouplingLow (publisher is anonymous to subscribers)High (client depends on server response)Moderate (asynchronous goal handle + stream)
Typical Time HorizonContinuous / unbounded streamMilliseconds to ~200 msSeveral seconds to several minutes
Progress FeedbackNoneNone (returns only upon completion)Built-in periodic feedback stream (1–10 Hz)
Preemption / CancelNot applicableCannot be cancelled once sentClient or server can cancel mid-execution
Multiple ListenersYes (N:M)1:1 per request transactionFeedback and status can be monitored by many
myros_sketch Examples/scan, /imu/data, /cmd_vel, /odomReset odometry, toggle motor enable, save mapNavigateToPose, autonomous charger docking

Four-Step Workflow to Select and Verify Communication Interfaces

Follow this four-step procedure whenever you add a new capability to a robot package or debug an existing node graph:

  1. Classify by Duration and Coupling: If the data is a continuously updated measurement or setpoint, choose a Topic. If it is a discrete configuration trigger completing in under 200 ms, choose a Service. If it involves physical travel or computation lasting more than a second and requires cancellation or progress reporting, choose an Action.
  2. Search Standard ROS 2 Interfaces First: Before creating a custom interface package, inspect built-in definitions in sensor_msgs, geometry_msgs, nav_msgs, std_srvs, and nav2_msgs using ros2 interface list and ros2 interface show.
  3. Verify Endpoint Types and Rates via CLI: Launch the node and confirm that topic frequencies (ros2 topic hz), service signatures (ros2 service list -t), and action servers (ros2 action list -t) match your design table.
  4. Audit QoS Compatibility on Silent Links: Whenever a subscriber callback fails to fire even though the topic appears in ros2 topic list, run ros2 topic info <topic_name> -v to compare the publisher’s offered QoS against the subscriber’s requested QoS.
# Inspect and exercise Topics, Services, and Actions directly from the terminal
ros2 topic list -t
ros2 topic echo /scan --once
ros2 service list -t
ros2 service call /reset_odometry std_srvs/srv/Trigger "{}"
ros2 action list -t
ros2 interface show nav2_msgs/action/NavigateToPose

3. Production QoS Profiles and rclpy Implementation for Sensors, Commands, and Maps

As established in our DDS architecture analysis, QoS policies are explicit delivery contracts enforced by the middleware. When translating the official ROS 2 Jazzy Quality of Service settings guide into Python or C++ node code, the five baseline profiles below prevent the vast majority of wireless bottlenecks and matching failures.

Data Category (myros_sketch)ReliabilityDurabilityHistory (Depth)Engineering Rationale for This Profile
Sensors (/scan, /imu/data, /camera)BEST_EFFORTVOLATILEKEEP_LAST (5)Prioritizes low-latency arrival of the newest physical sample over retransmission
Velocity Commands (/cmd_vel)RELIABLEVOLATILEKEEP_LAST (10)Dropped stop commands are hazardous, but late-joining nodes must not replay old twists
Dynamic Transforms (/tf)RELIABLEVOLATILEKEEP_LAST (100)High-rate bursts from multiple links require a deeper queue to prevent dropped frames
Static Transforms (/tf_static)RELIABLETRANSIENT_LOCALKEEP_LAST (1)Published once at boot; late-joining nodes must receive the latched static offsets
Static Map (/map) & /robot_descriptionRELIABLETRANSIENT_LOCALKEEP_LAST (1)Ensures RViz2 or planners started minutes later still receive the map and URDF string

The complete rclpy node below demonstrates how to combine an explicit BEST_EFFORT sensor Topic subscription and publication with runtime Parameters and a synchronous reset Service in a single well-structured class:

import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy, HistoryPolicy
from sensor_msgs.msg import LaserScan
from std_srvs.srv import Trigger


class ScanRelayNode(Node):
    def __init__(self):
        super().__init__('scan_relay_node')

        # 1. Declare runtime parameters (change frame IDs or range limits without recompiling)
        self.declare_parameter('target_frame_id', 'laser_frame')
        self.declare_parameter('max_valid_range', 12.0)

        # 2. Define explicit sensor QoS (BEST_EFFORT + VOLATILE + Depth 5)
        sensor_qos = QoSProfile(
            reliability=ReliabilityPolicy.BEST_EFFORT,
            durability=DurabilityPolicy.VOLATILE,
            history=HistoryPolicy.KEEP_LAST,
            depth=5,
        )

        self.scan_count = 0
        self.pub = self.create_publisher(LaserScan, '/scan_filtered', sensor_qos)
        self.sub = self.create_subscription(
            LaserScan, '/scan', self.on_scan_received, sensor_qos
        )

        # 3. Register a synchronous Service server to reset the processed scan counter
        self.srv = self.create_service(
            Trigger, '/reset_scan_count', self.on_reset_count
        )
        self.get_logger().info('scan_relay_node ready with BEST_EFFORT sensor QoS')

    def on_scan_received(self, msg: LaserScan):
        frame_id = self.get_parameter('target_frame_id').get_parameter_value().string_value
        max_range = self.get_parameter('max_valid_range').get_parameter_value().double_value

        msg.header.frame_id = frame_id
        msg.range_max = float(max_range)
        self.scan_count += 1
        self.pub.publish(msg)

    def on_reset_count(self, request: Trigger.Request, response: Trigger.Response):
        prev = self.scan_count
        self.scan_count = 0
        response.success = True
        response.message = f'Reset scan_count from {prev} to 0'
        return response


def main(args=None):
    rclpy.init(args=args)
    node = ScanRelayNode()
    try:
        rclpy.spin(node)
    finally:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()

A classic beginner bug is passing an integer queue depth like 10 as the fourth argument to create_subscription(LaserScan, '/scan', self.on_scan_received, 10). Passing an integer defaults to RELIABLE reliability. When the hardware LiDAR driver offers BEST_EFFORT, DDS rejects the match silently and on_scan_received is never invoked. Explicitly passing a QoSProfile with ReliabilityPolicy.BEST_EFFORT eliminates that mismatch.

4. Parameters, TF2, Launch Files, and Executors: The Four Supporting Pillars

While Nodes, Topics, Services, and Actions move payloads across the graph, four supporting subsystems turn individual scripts into a coherent robot software stack: Parameters, TF2 coordinate transforms, Packages and Launch files, and Executors.

Parameters: Runtime Tuning Knobs Without Rebuilding Code

Hardcoding physical constants such as wheel_radius = 0.0325, max_linear_speed = 0.5, target_frame_id = 'laser_frame', or use_sim_time = True inside C++ or Python source files forces a rebuild for every minor calibration tweak. Declaring them as node parameters allows you to inject different YAML files for simulation versus physical hardware or adjust gains live from the CLI:

# List, query, and update node parameters dynamically at runtime
ros2 param list /scan_relay_node
ros2 param get /scan_relay_node max_valid_range
ros2 param set /scan_relay_node max_valid_range 8.0

TF2: Tracking 3D Coordinate Transforms Across Space and Time

When the 2D LiDAR detects an obstacle 0.8 m directly ahead in laser_frame, the navigation controller needs to know where that point lies relative to the drive axle (base_link) and the global room map (map). As taught in the ROS 2 Jazzy TF2 tutorials, TF2 buffers time-stamped 3D translation $(x, y, z)$ and quaternion rotation $(q_x, q_y, q_z, q_w)$ transforms across a directed tree of coordinate frames, allowing any node to query the exact transform between two frames at the timestamp when a sensor scan was captured.

The canonical TF2 hierarchy for myros_sketch follows the standard mobile robotics convention:

map (Global world frame: SLAM / AMCL publishes map -> odom to correct drift)
 └── odom (Continuous odometry frame: esp32_bridge publishes odom -> base_footprint)
      └── base_footprint (Ground-plane projection directly below the drive axle)
           └── base_link (Drive axle midpoint: root link of the URDF model)
                ├── left_wheel_link / right_wheel_link (Continuous wheel joints: dynamic TF)
                └── chassis (3D-printed body plate: static TF)
                     ├── caster_wheel_link (Front passive ball caster)
                     ├── imu_link (6-axis IMU sensor origin)
                     ├── lidar_base_frame ──> laser_frame (2D LiDAR scan plane at z ≈ 117 mm)
                     └── camera_link ──> camera_link_optical (Camera optical axis: +Z forward)

Two rules keep this tree healthy: never break the chain, and never duplicate a parent-child publisher. Every static offset below base_link comes directly from the URDF model via robot_state_publisher on /tf_static, while esp32_bridge (or an EKF fusion node) publishes the dynamic odom → base_footprint transform on /tf.

# Export the active TF2 tree to a PDF diagram and stream live transforms between two frames
ros2 run tf2_tools view_frames
ros2 run tf2_ros tf2_echo base_link laser_frame

Launch Files and Executors: Orchestrating Multi-Node Startup and Callback Concurrency

Rather than opening six terminal tabs and running ros2 run manually every time the robot boots, engineers bundle nodes, URDF descriptions, and parameter YAML files into a Package and start them declaratively with a Python Launch file:

from launch import LaunchDescription
from launch_ros.actions import Node


def generate_launch_description():
    return LaunchDescription([
        Node(
            package='robot_state_publisher',
            executable='robot_state_publisher',
            name='robot_state_publisher',
            parameters=[{'use_sim_time': False}],
        ),
        Node(
            package='myros_sketch',
            executable='scan_relay_node',
            name='scan_relay_node',
            parameters=[{'target_frame_id': 'laser_frame', 'max_valid_range': 10.0}],
        ),
    ])

Finally, as your nodes grow to handle multiple subscriptions, timers, and services simultaneously, you must account for how the ROS 2 Executor and callback groups schedule work. By default, rclpy.spin(node) uses a SingleThreadedExecutor that runs callbacks sequentially one at a time. If an image processing callback blocks for 40 ms, incoming /cmd_vel or /imu/data callbacks sit waiting in the queue. When high-frequency and heavy-compute callbacks must live inside the same node, assign them to separate MutuallyExclusiveCallbackGroup instances and spin the node with a MultiThreadedExecutor—or split the heavy processing into its own dedicated node.

Why Fixing Communication Interfaces First Keeps the Node Graph Stable

Topic names, message types, QoS profiles, and TF2 frame_id strings are the hardest design decisions to change once a robotics project matures. As you add SLAM, Nav2, and perception packages, those interface signatures become the structural contract binding the entire system together.

In fact, building a URDF robot model is ultimately an interface definition task: the <link> and <joint> names you write in URDF (base_link, laser_frame, imu_link, camera_link_optical) flow directly into the /tf and /tf_static topics expected by every downstream algorithm. With the hardware layers, DDS discovery architecture, and communication primitives now established, the next tutorial—Installing ROS 2 Jazzy on Ubuntu 24.04 and Locking Your .bashrc Workspace Environment—shows how to set up a reproducible Linux and container development environment so every command and launch file runs reliably without environment variable collisions.

Common mistakes

  • Implementing every interaction as a Topic and inventing a second ‘ack_topic’ to simulate request-response behavior, leading to race conditions and unmatched responses.
  • Running a multi-second motion loop or heavy computation synchronously inside a Service server callback, freezing all other subscriptions and timers sharing the same executor.
  • Subscribing to a best_effort sensor driver using the default reliable QoS profile (which silently blocks DDS matching), or manually broadcasting static transforms that collide with robot_state_publisher.

Pre-flight checklist

  • Have you classified every inter-node interaction into continuous streams (Topic), sub-second triggers/configs (Service), or long-running cancellable goals (Action) before writing code?
  • Have you explicitly declared QoS profiles (Reliability, Durability, Depth) for sensor, command, and map topics and verified endpoint matching with ros2 topic info -v?
  • Have you extracted physical constants like wheel radius, max linear speed, and frame IDs into ROS 2 Parameters rather than hardcoding literals?
  • Does your TF2 transform tree form a single unbroken chain from map → odom → base_footprint → base_link → sensor frames without duplicate publishers?

Frequently asked questions

What is the decisive engineering rule for choosing an Action over a Service?
Execution duration and the need for cancellation or intermediate progress feedback. A Service is a synchronous remote procedure call—the caller waits for a single response, making it ideal for tasks completing in milliseconds such as resetting odometry or toggling motor power. If a task takes several seconds or minutes—such as navigating across a room or docking at a charger—and requires periodic progress feedback or mid-execution cancellation when an obstacle appears, it must be an Action.
Can multiple nodes publish to the same ROS 2 Topic simultaneously?
Yes, DDS and ROS 2 natively support many-to-many (N:M) topic topologies, and subscribers will receive messages from all matching publishers in arrival order. While multi-publisher aggregation is standard for /tf and /rosout logging, it is dangerous for actuator command topics like /cmd_vel. If a teleop joystick node and Nav2 publish to /cmd_vel simultaneously, the wheels will jitter between conflicting commands; use a multiplexer node such as twist_mux to arbitrate priority.
Why should I not manually calculate and publish static sensor transforms in my own Python node?
Fixed geometric offsets between rigid robot parts (such as base_link to laser_frame or imu_link) belong in the URDF model and are published on /tf_static by robot_state_publisher. If a custom node broadcasts the same parent-child frame pair independently, timestamp and floating-point differences between the two publishers cause the transform tree to jump back and forth in RViz2 and corrupt SLAM localization.

Sources & verification

  1. ROS 2 Jazzy — Understanding ROS 2 Nodes, Topics, Services, Actions
  2. ROS 2 Jazzy — About Quality of Service Settings
  3. ROS 2 Jazzy — TF2 Tutorials and Coordinate Frames
  4. ROS 2 Jazzy — About Executors and Callback Groups

Last verified: