Bird
Raised Fist0
ROSframework~15 mins

Publish-subscribe communication model in ROS - Deep Dive

Choose your learning style10 modes available
Overview - Publish-subscribe communication model
What is it?
The publish-subscribe communication model is a way for different parts of a system to talk without knowing about each other directly. In this model, some parts called publishers send messages on topics, and other parts called subscribers listen to those topics to get the messages. This lets many parts share information easily and independently. It is widely used in robotics systems like ROS to connect sensors, controllers, and other components.
Why it matters
Without this model, every part would need to know exactly where to send messages and who to talk to, making the system complex and fragile. The publish-subscribe model solves this by decoupling senders and receivers, so they can work independently and scale easily. This means robots can add new sensors or modules without breaking existing communication, making development faster and more reliable.
Where it fits
Before learning this, you should understand basic programming concepts like functions and data flow. After this, you can learn about ROS nodes, services, and actions which build on this communication style to create complex robot behaviors.
Mental Model
Core Idea
Publishers send messages to topics without knowing who listens, and subscribers receive messages from topics without knowing who sends them.
Think of it like...
It's like a radio station broadcasting music on a frequency (topic). Anyone with a radio tuned to that frequency (subscriber) can listen, but the station (publisher) doesn't know who is listening or how many people are tuned in.
Publisher(s) ──▶ Topic (Channel) ──▶ Subscriber(s)

Multiple publishers can send to the same topic, and multiple subscribers can listen to it independently.
Build-Up - 7 Steps
1
FoundationUnderstanding basic message flow
🤔
Concept: Learn how messages move from one part to another using topics.
In ROS, a topic is like a named channel where messages are sent. A publisher sends messages to a topic, and a subscriber listens to that topic to receive messages. For example, a sensor node publishes temperature data to a 'temperature' topic, and a display node subscribes to that topic to show the temperature.
Result
You see that messages flow through topics, connecting publishers and subscribers without direct links.
Understanding that topics act as middlemen helps grasp how components stay independent and flexible.
2
FoundationRoles of publishers and subscribers
🤔
Concept: Identify the responsibilities of publishers and subscribers in communication.
Publishers create and send messages on a topic. Subscribers register interest in a topic and receive messages when published. Neither needs to know about the other’s existence. This separation allows parts to be added or removed without changing others.
Result
You can design systems where components only focus on sending or receiving data, simplifying development.
Knowing these roles clarifies how decoupling reduces dependencies and improves modularity.
3
IntermediateMessage types and serialization
🤔Before reading on: do you think publishers and subscribers must use the exact same message format to communicate? Commit to your answer.
Concept: Messages have defined types that both publishers and subscribers must agree on to understand data correctly.
In ROS, messages are structured data types like integers, floats, or arrays grouped in a message definition. When a publisher sends a message, it is serialized (converted to a stream of bytes) and sent over the network. Subscribers deserialize the message back to the original structure. Both sides must use the same message type to avoid errors.
Result
Communication works smoothly with consistent message formats, preventing misunderstandings.
Understanding message types and serialization explains why mismatched message definitions cause communication failures.
4
IntermediateMultiple publishers and subscribers per topic
🤔Before reading on: do you think a topic can have only one publisher and one subscriber? Commit to your answer.
Concept: Topics can have many publishers and subscribers simultaneously, enabling flexible data sharing.
ROS allows multiple nodes to publish to the same topic and multiple nodes to subscribe to it. For example, several sensors might publish to a 'laser_scan' topic, and multiple processing nodes subscribe to it for different purposes. ROS handles merging and distributing messages automatically.
Result
You can build complex systems where data flows freely between many components without manual wiring.
Knowing this helps design scalable systems where components can be added or removed without reconfiguring communication.
5
IntermediateTopic naming and namespaces
🤔
Concept: Learn how topics are named and organized to avoid conflicts and improve clarity.
Topics have names like '/camera/image' or '/robot1/odom'. Namespaces group topics logically, like folders on a computer. This helps avoid name clashes when multiple robots or modules run together. ROS tools use these names to connect publishers and subscribers correctly.
Result
You can organize topics clearly, making large systems easier to manage and debug.
Understanding naming conventions prevents confusion and communication errors in multi-robot or multi-module setups.
6
AdvancedQuality of Service and message reliability
🤔Before reading on: do you think all messages sent on a topic are guaranteed to arrive? Commit to your answer.
Concept: ROS supports settings that control how messages are delivered, balancing speed and reliability.
Quality of Service (QoS) policies let you choose if messages should be reliable (guaranteed delivery) or best-effort (faster but may lose messages). For example, sensor data might use best-effort for speed, while commands use reliable delivery. These settings affect how ROS manages message queues and retries.
Result
You can tune communication to fit your robot’s needs, improving performance or safety.
Knowing QoS options helps prevent unexpected data loss or delays in critical robot functions.
7
ExpertInternal ROS middleware and message routing
🤔Before reading on: do you think ROS nodes communicate directly or through an intermediary? Commit to your answer.
Concept: ROS uses a middleware layer to manage message routing between publishers and subscribers dynamically.
Under the hood, ROS nodes register with a central master that tracks topic publishers and subscribers. When a subscriber starts, the master tells it where to find publishers. Nodes then establish peer-to-peer connections to exchange messages directly. This design reduces bottlenecks and allows dynamic discovery of nodes at runtime.
Result
Communication is efficient, scalable, and flexible, adapting as nodes join or leave the system.
Understanding this mechanism explains how ROS supports dynamic, distributed robot systems without hard-coded connections.
Under the Hood
ROS nodes register their publishers and subscribers with a central master node. The master keeps track of which nodes publish or subscribe to which topics. When a subscriber starts, it queries the master to find publishers for its topics. Then, nodes establish direct peer-to-peer TCP or UDP connections to exchange serialized messages. This avoids a central bottleneck and allows dynamic discovery and connection management.
Why designed this way?
This design balances flexibility and performance. The master node simplifies discovery but does not handle message passing, preventing overload. Direct peer connections reduce latency and bandwidth use. Alternatives like centralized brokers were rejected because they create single points of failure and bottlenecks, which are problematic in robotics where real-time data is critical.
┌─────────────┐       ┌─────────────┐       ┌─────────────┐
│ Publisher A │──────▶│             │       │ Subscriber  │
│             │       │   ROS Master│◀──────│     B       │
└─────────────┘       │             │       └─────────────┘
                      └─────────────┘
                            ▲  ▲
┌─────────────┐             │  │             ┌─────────────┐
│ Publisher C │─────────────┘  └────────────▶│ Subscriber D │
└─────────────┘                            └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think a subscriber can send messages back to a publisher on the same topic? Commit to yes or no.
Common Belief:Subscribers can reply or send messages back to publishers on the same topic.
Tap to reveal reality
Reality:Publish-subscribe is one-way communication; subscribers only receive messages and cannot send replies on the same topic.
Why it matters:Expecting two-way communication on a topic leads to design errors; for two-way, services or actions should be used.
Quick: Do you think messages are always delivered in the order they were sent? Commit to yes or no.
Common Belief:Messages on a topic always arrive in the exact order they were published.
Tap to reveal reality
Reality:Message order is not guaranteed, especially with multiple publishers or unreliable QoS settings.
Why it matters:Assuming order can cause bugs in processing data streams that depend on sequence.
Quick: Do you think topics store messages for late subscribers by default? Commit to yes or no.
Common Belief:Topics keep all past messages so new subscribers can receive old data automatically.
Tap to reveal reality
Reality:Topics do not store messages; subscribers only get messages published after they start listening unless special features like latched topics are used.
Why it matters:Relying on past messages without latched topics causes subscribers to miss important data.
Quick: Do you think the ROS master handles all message passing between nodes? Commit to yes or no.
Common Belief:The ROS master routes all messages between publishers and subscribers centrally.
Tap to reveal reality
Reality:The master only manages registration and discovery; actual messages flow directly between nodes.
Why it matters:Misunderstanding this can lead to incorrect assumptions about network load and failure points.
Expert Zone
1
ROS topics can be remapped at runtime, allowing flexible reuse of nodes without code changes.
2
The underlying middleware (DDS in ROS2) supports advanced QoS policies like deadline, lifespan, and liveliness that affect real-time behavior.
3
Message serialization format impacts performance; custom serialization can optimize bandwidth and latency in constrained systems.
When NOT to use
Publish-subscribe is not suitable for request-response interactions needing immediate replies; use ROS services or actions instead. For very high-frequency data with strict timing, consider real-time communication protocols or shared memory.
Production Patterns
In real robots, topics are used for sensor data streaming, status updates, and command broadcasting. Services handle configuration or commands needing confirmation. Actions manage long-running tasks with feedback. Developers use topic namespaces to separate multiple robots or subsystems cleanly.
Connections
Event-driven programming
Publish-subscribe is a form of event-driven communication where events (messages) trigger reactions.
Understanding event-driven design helps grasp how decoupled components respond asynchronously to data changes.
Message queues in distributed systems
Publish-subscribe is a messaging pattern used in distributed systems to decouple producers and consumers.
Knowing message queue concepts clarifies how ROS topics enable scalable, fault-tolerant communication.
Radio broadcasting
Publish-subscribe mirrors radio broadcasting where stations send signals and listeners tune in independently.
This connection shows how one-to-many communication can be efficient and flexible without direct links.
Common Pitfalls
#1Assuming subscribers receive messages sent before they start listening.
Wrong approach:Subscriber node starts and expects to get the last sensor reading published before it launched.
Correct approach:Use latched topics or publish the current state again after subscriber connects to ensure it receives important data.
Root cause:Misunderstanding that topics do not store or replay past messages by default.
#2Using the same topic name for unrelated data causing confusion.
Wrong approach:Publishing camera images and laser scans on a topic named '/sensor_data'.
Correct approach:Use separate topics like '/camera/image' and '/laser/scan' to clearly separate data types.
Root cause:Ignoring topic naming conventions and the importance of clear organization.
#3Expecting guaranteed message delivery without configuring QoS.
Wrong approach:Assuming all messages arrive reliably on a best-effort QoS setting.
Correct approach:Set QoS policies to reliable when message loss is unacceptable, such as for commands.
Root cause:Not understanding the impact of QoS settings on message reliability.
Key Takeaways
The publish-subscribe model decouples senders and receivers by using named topics for message exchange.
Publishers send messages without knowing who listens; subscribers receive messages without knowing who sends them.
Message types must match on both sides to ensure correct communication and avoid errors.
ROS uses a master node for discovery but messages flow directly between nodes for efficiency.
Understanding QoS and topic naming is essential for building reliable and scalable robotic systems.

Practice

(1/5)
1. What is the main role of a publisher in the ROS publish-subscribe model?
easy
A. To create new topics dynamically
B. To receive messages from a topic
C. To store messages in a database
D. To send messages to a topic

Solution

  1. Step 1: Understand the publish-subscribe roles

    In ROS, publishers send messages to topics, while subscribers receive messages from topics.
  2. Step 2: Identify the publisher's function

    The publisher's job is to send data to a topic so subscribers can receive it.
  3. Final Answer:

    To send messages to a topic -> Option D
  4. Quick Check:

    Publisher = sends messages [OK]
Hint: Publisher sends, subscriber receives messages [OK]
Common Mistakes:
  • Confusing publisher with subscriber
  • Thinking publisher stores messages
  • Assuming publisher creates topics
2. Which of the following is the correct way to create a ROS publisher in Python?
easy
A. pub = rospy.Publisher('topic_name', callback, queue_size=10)
B. pub = rospy.Subscriber('topic_name', String, callback)
C. pub = rospy.Publisher('topic_name', String, queue_size=10)
D. pub = rospy.Subscriber('topic_name', String)

Solution

  1. Step 1: Recall publisher syntax in ROS Python

    The correct syntax uses rospy.Publisher with topic name, message type, and queue size.
  2. Step 2: Check each option

    pub = rospy.Publisher('topic_name', String, queue_size=10) matches the correct syntax. Using Subscriber instead of Publisher is incorrect. pub = rospy.Publisher('topic_name', callback, queue_size=10) incorrectly uses callback instead of message type.
  3. Final Answer:

    pub = rospy.Publisher('topic_name', String, queue_size=10) -> Option C
  4. Quick Check:

    Publisher syntax = rospy.Publisher(topic, type, queue_size) [OK]
Hint: Publisher uses rospy.Publisher(topic, type, queue_size) [OK]
Common Mistakes:
  • Using Subscriber instead of Publisher
  • Passing callback instead of message type
  • Omitting queue_size parameter
3. Given the following ROS Python code snippet, what will be printed when a message with data 'Hello' is published?
import rospy
from std_msgs.msg import String

def callback(msg):
    print(f'Received: {msg.data}')

rospy.init_node('listener')
sub = rospy.Subscriber('chatter', String, callback)
rospy.spin()
medium
A. Received: Hello
B. Hello
C. Received: msg
D. No output

Solution

  1. Step 1: Understand the callback function

    The callback prints 'Received: ' followed by the message's data field.
  2. Step 2: Analyze the message content

    The message data is 'Hello', so the print statement outputs 'Received: Hello'.
  3. Final Answer:

    Received: Hello -> Option A
  4. Quick Check:

    Callback prints 'Received: ' + msg.data [OK]
Hint: Callback prints 'Received: ' plus message data [OK]
Common Mistakes:
  • Printing message object instead of data
  • Expecting just the message data without prefix
  • Thinking no output occurs without explicit print
4. Identify the error in this ROS Python subscriber code:
import rospy
from std_msgs.msg import String

def callback(msg):
    print(msg.data)

rospy.init_node('listener')
sub = rospy.Subscriber('chatter', String)
rospy.spin()
medium
A. Incorrect message type used
B. Missing callback function in Subscriber
C. Node not initialized
D. No import for rospy

Solution

  1. Step 1: Review Subscriber syntax

    Subscriber requires three arguments: topic name, message type, and callback function.
  2. Step 2: Check the given code

    The Subscriber call misses the callback argument, causing an error.
  3. Final Answer:

    Missing callback function in Subscriber -> Option B
  4. Quick Check:

    Subscriber needs callback argument [OK]
Hint: Subscriber must include callback function [OK]
Common Mistakes:
  • Omitting callback in Subscriber
  • Confusing Publisher and Subscriber arguments
  • Forgetting to initialize node
5. You want to create a ROS system where multiple nodes publish sensor data to the same topic, and one node subscribes to process all data. Which feature of the publish-subscribe model makes this possible?
hard
A. Topics allow multiple publishers and subscribers to communicate independently
B. Each topic can have only one publisher and one subscriber
C. Publishers must know all subscribers to send messages
D. Subscribers can only listen to one topic at a time

Solution

  1. Step 1: Understand topic communication in ROS

    Topics support multiple publishers and subscribers simultaneously, enabling flexible communication.
  2. Step 2: Analyze the scenario

    Multiple nodes publishing to the same topic and one subscriber processing all data is possible because topics allow many publishers and subscribers.
  3. Final Answer:

    Topics allow multiple publishers and subscribers to communicate independently -> Option A
  4. Quick Check:

    Topics support many-to-many communication [OK]
Hint: Topics support many publishers and subscribers [OK]
Common Mistakes:
  • Thinking topics allow only one publisher or subscriber
  • Believing publishers must know subscribers
  • Assuming subscribers can listen to only one topic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard