A mobile robot rolls toward a doorway, its lidar detects a person crossing, its navigation system slows down, and a dashboard shows the battery level changing. None of these jobs should live in one giant program.
Instead, separate pieces of software sense the environment, make decisions, command motors, and report status. They must exchange information reliably, at the right time, without every component needing to know how the others are built.
That is the practical problem ROS 2 is designed to address. Its communication concepts can initially feel like a vocabulary test—nodes, topics, services, actions, messages—but each one maps to a familiar engineering need.
Once you can identify whether a task is a stream, a quick request, or a longer goal, ROS 2 system design becomes far less mysterious. The same choices apply whether you are simulating a small rover or integrating an industrial robot.
🤖 ROS 2 as a Robot Software Framework
ROS 2, short for Robot Operating System 2, is a set of software libraries, tools, conventions, and middleware interfaces for building robotic systems. It is not an operating system in the usual sense; ROS 2 applications typically run on Linux, Windows, or another supported operating system.
Its central contribution is a common way for independently running programs to discover one another and exchange typed data. That lets a team divide a robot into understandable components rather than creating one tightly coupled application.
ROS 2 uses a communication layer based on DDS, the Data Distribution Service standard. Developers usually work through ROS 2 client libraries and do not need to configure DDS directly, but its decentralized design helps explain many ROS 2 behaviors.
🧠 Why Robots Need Separate Components
A robot contains work with very different timing and failure characteristics. A camera pipeline may publish many images per second, while a gripper command may happen once, and a navigation request may take minutes to complete.
Keeping these jobs separate improves testability and reuse. You can replace a camera driver, run a planner in simulation, or record sensor data without rewriting the motor controller.
Separation also limits the effect of ordinary software failures. Restarting a visualization node should not necessarily stop a safety-critical controller. This is not automatic fault tolerance, but sensible component boundaries make recovery and diagnosis more achievable.
🧩 What Is a ROS 2 Node?
A node is an executable participant in a ROS 2 graph. It may publish data, subscribe to data, offer a service, call a service, provide an action, request an action, or combine several of these roles.
Think of a node as a specialist on a robot team. A lidar driver turns hardware readings into scan messages. A localization node estimates pose. A motor controller receives velocity commands and translates them into hardware-level outputs.
A node is not required to correspond to one physical device. A single camera may involve a driver node, an image-processing node, and a detector node. Conversely, a small prototype may place related tasks in one node when separating them brings little benefit.
🕸️ The ROS 2 Graph
The ROS 2 graph is the changing network of nodes and their communication endpoints. When compatible nodes run in the same ROS domain, they can generally discover one another without a central master process.
This differs from ROS 1, where a ROS master played a central role in name registration. ROS 2 discovery is normally distributed through its middleware, which can suit systems where a single registration point would be undesirable.
Discovery is not magic across every network boundary. Firewalls, multicast restrictions, virtual networks, and differing domain IDs can prevent nodes from seeing each other. When two apparently correct programs cannot communicate, network configuration is often the first practical place to investigate.
🏷️ Names, Namespaces, and Remapping
ROS 2 identifies nodes and interfaces with names. A topic might be named /scan, a service /reset_odometry, and an action /navigate_to_pose. Clear names describe an interface’s purpose rather than its current implementation.
Namespaces organize repeated subsystems. In a fleet or multi-robot simulation, one robot might use /robot_1/scan and another /robot_2/scan. This avoids collisions while allowing identical software to be launched for both robots.
Remapping changes a name at launch time without editing source code. A reusable node can publish to image_raw internally, while a launch configuration maps it to the actual camera topic. Remapping is powerful, but excessive or undocumented remapping can make a running system difficult to trace.
📦 Messages Give Data a Shape
ROS 2 communication uses message types: defined data structures with named fields. For example, a velocity command commonly uses a message containing linear and angular velocity values; a laser scan includes ranges, angle information, and timing details.
Both ends of a connection must agree on the message type. A subscriber expecting a pose message cannot safely interpret an image message simply because both arrived on a similarly named topic.
Message definitions are interfaces, not casual implementation details. Changing a field, unit, coordinate convention, or meaning can break downstream nodes even when code still compiles. Document frames, units, expected ranges, and timestamps alongside the type.
📣 Topics for Continuous Data Streams
A topic is a named channel for publish-subscribe communication. A publisher sends messages without targeting a particular receiver, and one or more subscribers receive messages when their topic, type, and quality-of-service settings are compatible.
Topics fit information that is continually updated: camera images, wheel encoder readings, pose estimates, battery state, and velocity commands. The publisher does not wait for each subscriber to finish processing before publishing again.
This loose coupling is a major advantage. A recorder, visualizer, and perception algorithm can all subscribe to the same camera stream without requiring the camera driver to know they exist.
📡 Publishers and Subscribers in Practice
Consider a hypothetical indoor delivery robot. Its lidar node publishes scans on /scan. A mapping node subscribes to those scans, while a visualization tool subscribes too. Neither consumer needs direct access to the lidar hardware.
Likewise, a planner can publish desired velocity on /cmd_vel, and a base controller can subscribe. In a real robot, that controller should still enforce limits and safety checks; publishing a command is not permission to bypass hardware protection.
A topic does not guarantee that a subscriber will act correctly or quickly. It simply provides a data path under the selected communication policy. System behavior depends on each node’s logic, timing, and validation.
⏱️ Topic Timing, Rate, and Freshness
Many topic bugs are really timing bugs. A localization node might publish at one rate, a controller might run at another, and a slow perception algorithm might process images that are already old by the time it produces a result.
Include timestamps where time matters, and decide what “fresh enough” means for the consumer. A controller may reject an old velocity command, while a map viewer can still display an older map update without harm.
Do not assume that a higher publish rate automatically improves a robot. It can increase CPU use, network traffic, queue pressure, and latency. Choose rates based on physical dynamics, sensor capabilities, computation time, and the consequence of stale data.
🛡️ Quality of Service Controls Delivery Behavior
Quality of Service, often shortened to QoS, describes how communication should behave. ROS 2 lets publishers and subscribers request policies for reliability, message history, durability, and related timing behavior.
These settings matter because sensor streams and critical commands have different needs. A high-bandwidth camera stream may reasonably drop an occasional old frame rather than delay everything. A configuration update may be better sent reliably because missing it could leave components inconsistent.
| QoS idea | Practical question | Typical trade-off |
|---|---|---|
| Reliability | Must the transport try to deliver every message? | Reliability may add retries and delay. |
| History and depth | How many unread messages should be retained? | Larger queues use more memory and can increase staleness. |
| Durability | Should late joiners receive the most recent retained data? | Useful for static state, unnecessary for many live streams. |
QoS is negotiated through compatible endpoint settings. If a publisher and subscriber appear to be on the same topic but exchange nothing, incompatible QoS is a common explanation.
🔄 Best-Effort Versus Reliable Delivery
With best-effort delivery, the middleware attempts to send messages but may drop them when the network or receiver cannot keep up. This can be appropriate for rapidly replaced sensor readings: the next scan may be more useful than an old delayed scan.
With reliable delivery, the system attempts to ensure messages reach compatible subscribers. It is valuable when each update matters, but it does not eliminate application-level failures, invalid data, or a consumer that processes messages too slowly.
The correct choice depends on consequence and freshness. There is no universal “strongest” profile. A reliable camera feed can be a poor choice if it causes a robot to make decisions from delayed imagery.
🧾 Durable Topics and Late-Joining Nodes
Durability addresses a different problem: what happens when a subscriber starts after a publisher has already sent data? With an appropriate durable policy, a publisher can retain recent information for late-joining subscribers.
This is useful for slowly changing state such as a static map, a current mode, or a configuration-like announcement. A visualization node launched later can receive useful context instead of waiting indefinitely for a rare update.
Durability does not turn a topic into a database. Retention is controlled by QoS policy and available resources. For long-term history, use a recorder, a dedicated storage system, or another explicit persistence approach.
☎️ Services for Short Request-Response Work
A service provides request-response communication. A client sends one request, and a server returns one response. It resembles calling a function across processes or machines, although the call can fail or take time.
Services fit discrete operations such as resetting odometry, asking a node to save a map, requesting a calibration step, or querying a current configuration value. The requester usually wants an answer before choosing its next step.
A service should represent a bounded operation. If the request starts work that may take a long time, needs progress updates, or may need cancellation, an action is usually the better model.
🧮 Service Types and Service Contracts
A service type defines two structures: a request and a response. A reset service may have an empty request and a response stating whether reset succeeded. A service that changes a parameter may include the requested value and a result message.
Design responses that provide actionable information. A bare Boolean can signal success or failure, but a short status field or error code can make debugging and recovery far easier.
Service calls should validate input at the server. A caller may send an out-of-range value, a request may arrive in an unsuitable robot state, or hardware may be unavailable. Returning a clear failure is safer than silently accepting an operation that cannot be completed correctly.
⏳ Service Timeouts and Blocking Risks
A service client can wait for a response, but blocking an important execution path while it waits is risky. A control loop that stops to wait for a slow service can miss timing deadlines and create unstable behavior.
Use asynchronous calls, callbacks, or separate execution paths when a response may be delayed. Set sensible timeouts and decide what the robot should do if the service server is unavailable or never responds.
Do not use a service as a substitute for continuous feedback. Repeatedly calling a “what is your pose?” service can be less efficient and less expressive than subscribing to a pose topic with timestamps.
🎯 Actions for Goals That Take Time
An action manages a goal-oriented task that can run for an extended period. It combines three communication needs: sending a goal, receiving feedback while work continues, and receiving a final result.
Actions are well suited to commands such as “navigate to this pose,” “move the arm to this joint configuration,” or “perform this inspection route.” These tasks are neither one-off data streams nor instant request-response operations.
An action client can also request cancellation. That capability is essential when a task becomes irrelevant: a robot should be able to abandon a navigation goal if a higher-priority safety or operator instruction changes the plan.
📍 The Goal, Feedback, Result, and Cancel Cycle
An action definition includes a goal, feedback, and result. A navigation goal might contain a target pose; feedback might report remaining distance or current state; the result reports completion, failure, or cancellation.
The server first decides whether to accept or reject a goal. Acceptance is not a promise of success. A route can later fail because the target is unreachable, localization is lost, or an obstacle persists.
Cancellation is cooperative rather than instantaneous. A well-designed action server checks for cancel requests at sensible points, brings hardware to a safe state, and returns an accurate terminal result. Clients should handle all terminal outcomes rather than assuming success.
⚖️ Topics, Services, and Actions Compared
The three communication patterns are complementary. Choosing the right one makes interfaces easier to understand and prevents awkward workarounds.
| Pattern | Use it when | Example | Not ideal when |
|---|---|---|---|
| Topic | Data is updated repeatedly and consumers may come and go. | Laser scans or battery state | The caller needs a direct answer. |
| Service | A bounded request needs one response. | Reset encoders | The task needs progress or cancellation. |
| Action | A goal takes time and needs lifecycle information. | Drive to a charging dock | The data is merely a continuous stream. |
A useful test is to ask: “Am I publishing the latest state, requesting a short operation, or assigning a task?” Those answers normally point to a topic, service, or action respectively.
🧭 A Mobile Robot Example End to End
Imagine a warehouse robot operating in a simulated aisle. A lidar driver publishes /scan, wheel encoders publish motion data, and an IMU publishes orientation-related measurements. A localization node subscribes to these inputs and publishes an estimated pose.
A navigation action server receives a goal to reach a shelf location. It publishes feedback to its client while internally using the current pose, map, and obstacle information. It may publish velocity commands to a base controller through a topic.
When an operator requests a map reload, a service can handle that bounded command. Meanwhile, battery state remains a topic because many components may continuously monitor it. One robot therefore uses all three patterns without forcing them to do the same job.
🧵 Executors and Callbacks
In ROS 2 client libraries, incoming messages, service requests, action events, and timers are commonly handled by callbacks: functions run in response to an event. An executor is responsible for selecting and running those callbacks.
A single-threaded executor processes eligible callbacks one at a time. This is straightforward and can be easier to reason about, but a long callback can delay everything else assigned to that executor.
Multi-threaded execution can improve responsiveness when callbacks are independent, but it introduces concurrency hazards. Shared data needs careful synchronization, and hardware access must remain ordered where order matters.
🔒 Callback Groups and Shared-State Safety
Callback groups help control whether callbacks may run concurrently. They are useful when a node has some operations that must not overlap, while other work can safely proceed in parallel.
For example, a motor-control node may need to prevent a calibration service from running simultaneously with a command that assumes calibrated hardware. A mutually exclusive group can help serialize those operations.
Concurrency design should begin with the data and hardware being shared, not with a desire to use more threads. Locks, queues, state machines, and explicit ownership can all be appropriate, but each adds complexity that deserves testing under load.
🧭 Coordinate Frames and Transform Data
Robots constantly need to answer spatial questions: where is the camera relative to the base, where is the base in the map, and where was a detected object at a particular time? ROS 2 systems commonly use the TF2 transform library to distribute these relationships.
Transforms are often published over topics, but they represent a specialized convention for coordinate frames. Frame names such as map, odom, base_link, and sensor frames must have consistent, documented meanings.
A transform chain can be mathematically valid yet physically wrong if axes, units, or timestamps are inconsistent. Treat frame conventions as an interface contract, especially when integrating components from different teams.
🕰️ Time, Simulation, and Timestamp Discipline
ROS 2 applications may use system time, steady time for measuring durations, or simulated time. Simulation tools can publish a clock so nodes advance according to the simulated world rather than wall-clock time.
Mixing time sources carelessly produces subtle failures. A message stamped with one clock cannot always be sensibly compared with a timeout measured from another. Transform lookups are particularly sensitive to timestamp consistency.
For replayable robotics experiments, use timestamps from the appropriate ROS clock and test behavior under simulation time if the deployed system will rely on it. Time is data in robotics, not just a logging detail.
🗂️ Parameters Are Configuration, Not Streaming Data
Parameters store named configuration values associated with a node, such as a controller gain, a sensor frame name, or a maximum speed. They are appropriate for settings that change infrequently and influence node behavior.
A parameter is not a replacement for a topic. Publishing rapidly changing sensor state as parameters creates poor visibility into timing and makes consumers depend on polling-like patterns rather than event-driven data.
Validate parameters at startup and when changes are allowed at runtime. A negative safety distance or an unknown frame name should be rejected clearly. For consequential changes, consider whether a node must safely reinitialize before applying the new value.
🛠️ Launch Files Start Systems Reproducibly
A robot rarely runs only one node. Launch files describe how to start a set of nodes with their parameters, namespaces, remappings, and environment-specific choices. They reduce the error-prone practice of opening many terminals and typing commands manually.
Use launch configuration to separate portable software from deployment details. The same perception node can run with a simulated camera in one launch setup and a physical camera in another.
A launch file should make the running graph understandable, not hide it. Keep naming rules and remaps readable, provide defaults carefully, and avoid embedding secrets or machine-specific assumptions in reusable packages.
🔍 Inspecting a Running ROS 2 System
Command-line tools provide a direct view of the graph. Commands such as ros2 node list, ros2 topic list, ros2 service list, and ros2 action list show which interfaces are currently available.
You can inspect a topic’s type and endpoints, echo messages for a quick sanity check, or view node information to discover its publishers, subscriptions, clients, and servers. These tools are often faster than reading source code during integration.
ros2 node list ros2 topic info /scan -v ros2 topic echo /battery_state ros2 service list ros2 action list
Be cautious when echoing high-rate or sensitive data on a production robot. Diagnostic tools consume resources and can expose information that should not be broadly available on shared networks.
🧪 Recording and Replaying Topic Data
ROS 2 bag tools can record topic data and replay it later. Recording is valuable for reproducing a perception failure, testing a localization change against the same sensor sequence, or sharing a controlled dataset with teammates.
A replay is only as useful as the data and context captured. Record relevant inputs, transforms, and clock information where needed. Also record configuration details separately, because bags do not automatically explain every parameter, code version, or hardware condition behind an event.
Replay can reveal assumptions hidden in a node. If a component only works when messages arrive at a particular accidental rate or in a lucky order, recorded data often makes that fragility visible.
📊 Observability Makes Integration Manageable
Robots are distributed systems, so logs alone are not always enough. Good observability includes meaningful log messages, topic inspection, recorded data, timing measurements, and health information that reveals whether a component is alive and producing sensible output.
Design diagnostics around decisions an operator or engineer must make. “No valid localization estimate for a defined interval” is more useful than a vague repeating warning. Include enough context to identify the affected frame, sensor, or goal.
Do not flood logs from high-frequency callbacks. Rate-limit recurring messages, expose essential state through suitable interfaces, and preserve the events that explain transitions, failures, and safety-related decisions.
🚧 Common Interface Design Mistakes
Several mistakes recur in early ROS 2 designs:
- Using a service for a long-running task, then inventing extra services to poll progress.
- Using a topic for a command that needs explicit acceptance, result status, and cancellation.
- Publishing an overloaded message whose fields mix unrelated concepts.
- Leaving units, frames, timestamps, and error behavior undocumented.
- Assuming a message received by middleware was necessarily processed in time by the application.
The fix is usually conceptual, not syntactic. Revisit the contract: who produces information, who owns a decision, what feedback is required, and what should happen when communication or hardware fails?
🧯 Safety Boundaries Do Not Emerge Automatically
ROS 2 communication helps components coordinate, but it does not make a robot safe by itself. A topic named /cmd_vel does not verify that a velocity is safe near a person, and an action result does not prove a manipulator avoided every hazard.
Safety-relevant systems need appropriate independent protections: command limits, watchdog behavior, emergency-stop hardware, state validation, physical interlocks, and a risk assessment suited to the machine and environment.
Network loss, stale messages, duplicate requests, and restarted nodes should all have defined behavior. The correct response may be to stop, hold position, slow down, or enter a controlled fault state, depending on the robot and hazard analysis.
🌐 Domains, Networks, and Multi-Robot Separation
A ROS domain ID provides a way to separate ROS 2 graphs sharing network infrastructure. Robots on different domain IDs do not normally discover one another, which can reduce accidental cross-talk during lab work or fleet development.
Domain IDs are not a complete security boundary. Network access, middleware configuration, operating-system permissions, and deployment practices still matter. Treat a robot network as an engineering environment requiring deliberate access control.
For multi-robot systems, establish conventions early: namespaces for robot-specific interfaces, shared interfaces only where intended, and clear bridges or gateways when information must cross boundaries. Ambiguous global names become expensive to untangle later.
📈 Scaling from a Prototype to a Product
A classroom prototype can tolerate manual startup, a few hard-coded names, and direct assumptions about one computer. A deployed robot needs reproducible launches, resource monitoring, upgrade plans, failure handling, and interfaces stable enough for multiple teams.
Scale by preserving clean boundaries early. Version message packages deliberately, test nodes against recorded data, define expected rates and QoS, and write down ownership for important topics and actions.
More nodes are not automatically better. Splitting a system too finely can add latency, deployment burden, and diagnostic complexity. A good boundary separates work that changes, fails, runs, or is tested independently.
✅ A Practical Pattern for Choosing an Interface
When designing a new connection, start with the behavior rather than the ROS feature. Ask these questions:
- Is this the latest value in an ongoing stream? Use a topic.
- Does a caller need one bounded answer before continuing? Consider a service.
- Is this a goal that takes time, needs feedback, and may be cancelled? Use an action.
- Is this a relatively stable setting owned by one node? Consider a parameter.
Then define message semantics, units, frames, expected rate, QoS, timeout behavior, and failure responses. A small interface specification written before implementation prevents many integration surprises.
🧠 The Core ROS 2 Communication Principle
ROS 2 works best when communication patterns reflect the real behavior of the robot. Nodes create manageable responsibilities; topics distribute changing state; services handle short transactions; actions manage cancellable goals with feedback.
The hard part is not memorizing definitions. It is designing honest contracts about timing, ownership, data meaning, and failure. Those contracts let independently developed components cooperate without becoming one fragile, tangled program.
Choose the interface that matches the job, make its assumptions explicit, and design for delayed, missing, or invalid data from the beginning.
With that mindset, ROS 2 becomes more than a collection of commands: it becomes a practical language for organizing robot behavior, testing it in pieces, and integrating it with confidence. 🤖🔧🧩

