Stage 10 · Lesson 14/16

ROS 2 & Robot Software Architecture (Fundamentals) · Lesson 14

QoS & Reliable Robot Communication

Est. 55–75 min

Why

Why this lesson matters

Think about how you send things in India. A legal document goes by registered post: it must reach, even if it is late. A cricket score on a live radio commentary is different: if you miss one ball, you do not want it repeated — you want the current ball. And the college notice board keeps the latest notice pinned, so a student who arrives late can still read it. These are three different “qualities of service”, and ROS 2 has a setting for each.

By the end of this lesson you will be able to: name the QoS policies (history, depth, reliability, durability, deadline, lifespan, liveliness); state the default profile and the sensor-data profile; predict whether a publisher and a subscription will connect using the “request vs offered” rule; choose QoS for joint states, commands and status; set QoS in rclpy and on the command line; and use QoS events to notice silence or mismatches.

A red India Post letter box on a pole outside a post office
An India Post letter box at Anand Head Office, Gujarat. Some messages must arrive (reliable); others only matter if they are fresh (best effort).Photo: Niraj Hitesh Chauhan · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

Quality of Service policies and profiles

The policies (Jazzy concepts page)

PolicyOptionsMeaning
HistoryKeep last / Keep allStore only the newest N samples, or all (within middleware limits)
DepthQueue size NOnly used with keep last
ReliabilityBest effort / ReliableMay lose samples / guaranteed delivery, may retry
DurabilityVolatile / Transient localNo saving / publisher keeps samples for late-joining subscriptions
DeadlineDurationExpected maximum time between messages
LifespanDurationAfter this, a message is stale and silently dropped
Liveliness + lease durationAutomatic / Manual by topicHow a publisher shows it is still alive

Profiles you get for free

  • Default for publishers and subscriptions: keep last, depth 10, reliable, volatile, liveliness system default; deadline, lifespan and lease “default”. (That is why we always wrote create_publisher(..., 10).)
  • Sensor data: “the latest samples as soon as they are captured, at the expense of maybe losing some” — best effort with a smaller queue (in rmw’s qos_profiles.h: keep last 5, volatile). In rclpy: qos_profile_sensor_data.
  • Services are reliable and volatile; parameters are like services with a much larger depth.
  • System default uses whatever the middleware chooses.

Request vs Offered — the compatibility rule

A subscription requests the minimum quality it accepts. A publisher offers the maximum quality it can give. They connect only if no requested policy is stricter than what is offered. If even one policy does not match, there is no connection and no messages — and unlike ROS 1, the topic still shows up in ros2 topic list.

From the docs’ compatibility tables
Publisher offersSubscription requestsConnected?
Best effortBest effortYes
Best effortReliableNo
ReliableBest effortYes
VolatileTransient localNo
Transient localVolatileYes (new messages only)
Transient localTransient localYes (new and old messages)
Deadline xDeadline y > xYes
Deadline xDeadline y < xNo

QoS events

Publishers and subscriptions can register callbacks for events: deadline missed (offered / requested), liveliness lost / changed, and incompatible QoS (offered / requested). There are also matched events when a connection is made or dropped. Events turn silent problems into log lines and safe behaviour.

A handheld two-way radio transceiver with an antenna
A walkie-talkie: you hear the voice live or you miss it — nobody repeats old words. That is best effort, and for live sensor data it is often the right choice.Photo: Варвара Каминская · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Visual

Visualise it: which publishers and subscribers can talk

Nodes and topics in a robot system — each connection also has QoS settings that decide whether and how messages flow.

Interactive · Robot software architecture explorer

ROS 2 stack / QoS simulator — educational only (not a live DDS session)

Robot software architecture layers
Trajectory gen plugs into the ROS 2 graph with named topics/services/actions and TF frames — swap the module, keep the contracts. Ties Stages 6–9 into one software architecture.

Code lab

Code lab: predict connections, then lose packets on purpose

qos_sim.py (plain Python, no ROS needed) checks eight publisher/subscription pairs with the request-vs-offered rule, sends 100 joint readings over a lossy link with best effort and reliable, shows what queue depth does to a slow subscriber, shows a late-joining dashboard with volatile vs transient local, and fires a deadline event. Run python3 qos_sim.py.

qos_sim.py · Python
"""qos_sim.py - a toy model of ROS 2 QoS (plain Python, no ROS 2 needed).

Follows the rules on the Jazzy "Quality of Service settings" concepts page:
  - Request vs Offered: a subscription REQUESTS a minimum, a publisher OFFERS a maximum;
    they connect only if no requested policy is more stringent than the offered one
  - reliable: delivery guaranteed, may retry; best effort: may lose samples
  - keep last N: only the newest N samples are kept
  - transient local: the publisher keeps samples for late-joining subscriptions
  - deadline: expected maximum time between messages
This is a teaching model (simple retry/latency maths), not DDS.
"""
import random

random.seed(7)
STRICT = {"reliability": ["best_effort", "reliable"], "durability": ["volatile", "transient_local"]}


def compatible(offered, requested):
    reasons = []
    for policy, order in STRICT.items():
        if order.index(requested[policy]) > order.index(offered[policy]):
            reasons.append(f"{policy}: requested {requested[policy]} > offered {offered[policy]}")
    o, r = offered.get("deadline"), requested.get("deadline")
    if r is not None and (o is None or o > r):
        reasons.append(f"deadline: requested {r}s but offered {o or 'default (none)'}")
    return reasons


DEFAULT = {"reliability": "reliable", "durability": "volatile"}
SENSOR = {"reliability": "best_effort", "durability": "volatile"}
LATCHED = {"reliability": "reliable", "durability": "transient_local"}

print("Part 1: Request vs Offered (publisher -> subscription)")
pairs = [
    ("default   -> default", DEFAULT, DEFAULT),
    ("sensor    -> sensor ", SENSOR, SENSOR),
    ("default   -> sensor ", DEFAULT, SENSOR),
    ("sensor    -> default", SENSOR, DEFAULT),
    ("volatile  -> latched", DEFAULT, LATCHED),
    ("latched   -> default", LATCHED, DEFAULT),
    ("10 Hz pub (0.1 s) -> sub wants 0.2 s", dict(DEFAULT, deadline=0.1), dict(DEFAULT, deadline=0.2)),
    ("pub 0.5 s -> sub wants 0.2 s       ", dict(DEFAULT, deadline=0.5), dict(DEFAULT, deadline=0.2)),
]
for name, pub, sub in pairs:
    why = compatible(pub, sub)
    print(f"  {name}: {'connected' if not why else 'NO CONNECTION - ' + '; '.join(why)}")

print("\nPart 2: 100 joint_states at 20 Hz over Wi-Fi with 10% packet loss")
lost = [random.random() < 0.10 for _ in range(100)]
be_got = lost.count(False)
retries = sum(lost)
print(f"  best effort: received {be_got}/100, every received one on time")
worst = max(len(s) for s in "".join("x" if l else "." for l in lost).split(".")) if any(lost) else 0
print(f"  reliable   : received 100/100, but {retries} needed a resend (+1 round trip each);")
print(f"               longest run of back-to-back losses = {worst}, so some readings arrive late")
print("  -> for a stream where only the newest value matters, a late value is worse than a missing one")

print("\nPart 3: keep last depth - a slow subscriber reads every 0.2 s, publisher sends at 20 Hz")
for depth in (1, 5, 10):
    queue, dropped, ages = [], 0, []
    for tick in range(40):                 # 2 s of publishing
        queue.append(tick)
        if len(queue) > depth:
            queue.pop(0)
            dropped += 1
        if tick % 4 == 3:                  # subscriber wakes up
            ages.append(tick - queue[0])
            queue.pop(0)
    print(f"  depth {depth:>2}: dropped {dropped:>2} old samples, oldest sample handed over was "
          f"{max(ages) * 50} ms old")
print("  -> small depth = always fresh; big depth = old data piles up")

print("\nPart 4: durability - a dashboard starts 5 s after the robot description was published once")
for name, pub, sub in [("volatile/volatile", DEFAULT, DEFAULT), ("transient_local both", LATCHED, LATCHED)]:
    got = "gets the description" if pub["durability"] == sub["durability"] == "transient_local" else "gets NOTHING (it was sent before it joined)"
    print(f"  {name:<20}: late dashboard {got}")

print("\nPart 5: deadline 0.1 s on /arm1/target_deg - the planner freezes for 0.35 s")
stamps = [0.0, 0.05, 0.10, 0.15, 0.50, 0.55]
for a, b in zip(stamps, stamps[1:]):
    gap = b - a
    if gap > 0.1:
        print(f"  gap {gap:.2f}s after t={a:.2f}: 'requested deadline missed' event -> controller holds position")
print("  -> the event lets the arm react to silence instead of moving on old commands")

Output (run with python3 qos_sim.py)

Part 1: Request vs Offered (publisher -> subscription)
  default   -> default: connected
  sensor    -> sensor : connected
  default   -> sensor : connected
  sensor    -> default: NO CONNECTION - reliability: requested reliable > offered best_effort
  volatile  -> latched: NO CONNECTION - durability: requested transient_local > offered volatile
  latched   -> default: connected
  10 Hz pub (0.1 s) -> sub wants 0.2 s: connected
  pub 0.5 s -> sub wants 0.2 s       : NO CONNECTION - deadline: requested 0.2s but offered 0.5

Part 2: 100 joint_states at 20 Hz over Wi-Fi with 10% packet loss
  best effort: received 87/100, every received one on time
  reliable   : received 100/100, but 13 needed a resend (+1 round trip each);
               longest run of back-to-back losses = 2, so some readings arrive late
  -> for a stream where only the newest value matters, a late value is worse than a missing one

Part 3: keep last depth - a slow subscriber reads every 0.2 s, publisher sends at 20 Hz
  depth  1: dropped 30 old samples, oldest sample handed over was 0 ms old
  depth  5: dropped 26 old samples, oldest sample handed over was 200 ms old
  depth 10: dropped 21 old samples, oldest sample handed over was 450 ms old
  -> small depth = always fresh; big depth = old data piles up

Part 4: durability - a dashboard starts 5 s after the robot description was published once
  volatile/volatile   : late dashboard gets NOTHING (it was sent before it joined)
  transient_local both: late dashboard gets the description

Part 5: deadline 0.1 s on /arm1/target_deg - the planner freezes for 0.35 s
  gap 0.35s after t=0.15: 'requested deadline missed' event -> controller holds position
  -> the event lets the arm react to silence instead of moving on old commands

Try it: see how nodes, topics and their settings connect in a robot software system.

Interactive · Robot software architecture explorer

ROS 2 stack / QoS simulator — educational only (not a live DDS session)

Robot software architecture layers
Trajectory gen plugs into the ROS 2 graph with named topics/services/actions and TF frames — swap the module, keep the contracts. Ties Stages 6–9 into one software architecture.

arm_qos_node.py — the right QoS for each job

Three topics, three choices. Joint states: sensor data (newest wins). Commands: reliable, depth 1, with a 0.2 s deadline — if the planner goes quiet, the deadline event puts the arm in HOLD. Status: transient local, so a dashboard started later still sees the current state.

arm_qos_node.py (rclpy, ROS 2 Jazzy) · Python
"""arm_qos_node.py - one node, three QoS choices (rclpy, ROS 2 Jazzy).

  joint_states  (subscribe) : qos_profile_sensor_data  -> best effort, keep last 5: newest reading, fast
  target_deg    (subscribe) : reliable, keep last 1, deadline 0.2 s -> every command, and we notice silence
  arm_status    (publish)   : reliable, transient local, keep last 1 -> late dashboards still get the status

QoS events (Jazzy rclpy.event_handler): 'requested deadline missed' puts the arm in HOLD;
'requested incompatible QoS' logs which policy did not match.

ros2 run arm_control arm_qos_node --ros-args -r __ns:=/arm1
ros2 topic pub -r 10 /arm1/target_deg std_msgs/msg/Float64 "{data: 90.0}"     # stop it -> HOLD
ros2 topic echo /arm1/arm_status --qos-durability transient_local --qos-reliability reliable
"""
import rclpy
from rclpy.duration import Duration
from rclpy.event_handler import SubscriptionEventCallbacks
from rclpy.node import Node
from rclpy.qos import (DurabilityPolicy, HistoryPolicy, QoSProfile, ReliabilityPolicy,
                       qos_profile_sensor_data)
from sensor_msgs.msg import JointState
from std_msgs.msg import Float64, String


class ArmQosNode(Node):
    def __init__(self):
        super().__init__('arm_qos_node')
        self.state = 'WAITING'

        status_qos = QoSProfile(history=HistoryPolicy.KEEP_LAST, depth=1,
                                reliability=ReliabilityPolicy.RELIABLE,
                                durability=DurabilityPolicy.TRANSIENT_LOCAL)
        self.status_pub = self.create_publisher(String, 'arm_status', status_qos)

        command_qos = QoSProfile(history=HistoryPolicy.KEEP_LAST, depth=1,
                                 reliability=ReliabilityPolicy.RELIABLE,
                                 deadline=Duration(seconds=0.2))
        events = SubscriptionEventCallbacks(deadline=self.on_deadline_missed,
                                            incompatible_qos=self.on_incompatible)
        self.create_subscription(Float64, 'target_deg', self.on_target, command_qos,
                                 event_callbacks=events)

        self.create_subscription(JointState, 'joint_states', self.on_joints,
                                 qos_profile_sensor_data)
        self.set_state('WAITING')

    def set_state(self, state, detail=''):
        if state != self.state or detail:
            self.get_logger().info(f'{self.state} -> {state} {detail}'.strip())
        self.state = state
        self.status_pub.publish(String(data=f'{state} {detail}'.strip()))

    def on_target(self, msg):
        if self.state != 'MOVING':
            self.set_state('MOVING', f'target {msg.data:.1f} deg')

    def on_deadline_missed(self, info):
        if self.state == 'MOVING':
            self.get_logger().warn(f'no command for 0.2 s (missed {info.total_count} total) - holding')
            self.set_state('HOLD')

    def on_incompatible(self, info):
        self.get_logger().error(f'incompatible QoS on target_deg: last policy id {info.last_policy_kind}')

    def on_joints(self, msg):
        self.get_logger().debug(f'{len(msg.name)} joints')


def main():
    rclpy.init()
    node = ArmQosNode()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.try_shutdown()


if __name__ == '__main__':
    main()
QoS on the command line · Shell
# see each endpoint's QoS (reliability, durability, deadline …)
ros2 topic info /arm1/joint_states --verbose

# with no --qos flags, ros2 topic echo starts from the sensor_data profile and then matches the
# reliability/durability of the publishers it finds; ros2 topic pub uses the default profile.
# Override with --qos-profile / --qos-reliability / --qos-durability / --qos-depth / --qos-history
ros2 topic echo /arm1/arm_status --qos-reliability reliable --qos-durability transient_local
ros2 topic pub -r 10 /arm1/target_deg std_msgs/msg/Float64 "{data: 90.0}" --qos-reliability reliable

# official QoS demo: simulate 5% packet loss on loopback (Linux), then remove it
sudo tc qdisc add dev lo root netem loss 5%
sudo tc qdisc delete dev lo root netem loss 5%

Real world

QoS in the real world

  • Official QoS demo: cam2image and showimage over a loopback with 5% loss — reliable makes the video slow down, best effort keeps it moving with skipped frames.
  • robot_state_publisher (Lesson 13): publishes /tf_static and robot_description with transient local, so nodes that start later still get them.
  • Lossy wireless: the docs say ROS 2 can be “as reliable as TCP or as best-effort as UDP” — field robots use best effort for big sensor streams and reliable for commands.
  • Your 6DOF arm: joint states best effort, commands reliable with a deadline, status transient local.
A college campus circle with a large notice board beside the road
A notice board at Fergusson College, Pune. The latest notice stays pinned for whoever comes later — like a transient-local topic.Photo: Deepak Patil · CC BY-SA 3.0 · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: knobs over a bad network

Use the two-pot board (two_pot_stream.ino, Lesson 4) and joint_state_node.py (Lesson 5). Make the network bad on purpose, the same way the official QoS demo does, and compare best effort with reliable.

Wiring (same as Lesson 4)
FromToNote
Pot 1 / Pot 2 outer legsArduino 5V and GND10 kΩ pots
WipersA0 (shoulder), A1 (elbow)—
Arduino USBROS 2 computer115200 baud, 20 Hz
  1. Baseline

    Run joint_state_node.py in /arm1, then ros2 topic hz /arm1/joint_states (about 20 Hz).

  2. Add loss

    sudo tc qdisc add dev lo root netem loss 5% (loopback only; use one PC). Note: nodes on the same host may use shared memory, so the effect can be small — try two PCs on Wi-Fi if you have them.

  3. Compare

    Echo with --qos-reliability reliable, then best_effort. Turn a knob quickly and watch which one lags and which one skips.

  4. Deadline

    Run arm_qos_node.py and publish targets at 10 Hz, then stop publishing. The node logs “holding”.

  5. Mismatch

    Publish target_deg with --qos-reliability best_effort. The reliable subscription logs an incompatible-QoS error and gets nothing.

  6. Clean up

    sudo tc qdisc delete dev lo root netem loss 5% — do not forget, or your whole PC stays lossy.

A Wi-Fi router with a home-made Yagi-Uda antenna attached
Wi-Fi drops packets — more with distance, walls and crowded channels. QoS decides whether ROS 2 resends them or moves on to the newest data.Photo: LordOider · CC0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging QoS

SymptomLikely causeFix
Topic listed, subscriber gets nothingIncompatible QoS (best-effort pub, reliable sub; volatile pub, transient-local sub)ros2 topic info -v; match or relax the subscription
Late node never gets the map / descriptionVolatile durabilityTransient local on both sides
Data lags then jumps on Wi-FiReliable + deep queue on a lossy linkSensor-data profile for streams
Old commands executed after a freezeBig depth on a command topicDepth 1 and a deadline
ros2 topic echo started before the publisher misses the latched messageWith no publishers yet, echo uses its sensor_data default (best effort, volatile)Start echo after the publisher, or pass --qos-durability transient_local --qos-reliability reliable
Rate lower on one PC onlyNetwork loss, not codeCheck with topic hz; test with tc netem to reproduce

Think

Think about it

Think

For each topic, choose reliability, durability and depth: (a) camera images at 30 Hz, (b) “go to home position” command, (c) the robot’s URDF, (d) emergency-stop state, (e) battery voltage at 1 Hz.

Experiment

Try it in the lab

About 40 minutes with Python; the ROS 2 steps need ROS 2 Jazzy on Linux (for tc); the bench step needs the two-pot board.

Experiment

Break the connection, then fix it

You will need

  • `qos_sim.py` and Python 3
  • Robot software architecture explorer (in your browser)
  • Optional: ROS 2 Jazzy, `image_tools` demo, `arm_qos_node.py`, Arduino UNO with two 10 kΩ pots

Steps

  1. Run `qos_sim.py`. Add a pair: transient-local best-effort publisher, volatile reliable subscription. Predict, then run.
  2. Change the loss to 30% in Part 2. What happens to the longest run of losses?
  3. With ROS 2: run the official QoS demo with and without `-p reliability:=best_effort` under 5% loss.
  4. With ROS 2: publish `/demo` with `--qos-reliability best_effort` and echo with `reliable`. Then check `ros2 topic info /demo -v`.
  5. With ROS 2: run `arm_qos_node.py`, start a dashboard (`ros2 topic echo … arm_status` with transient local) 10 s later — does it get the status?
  6. Bench: compare knob lag with reliable and best effort under loss.

Interactive · Robot software architecture explorer

ROS 2 stack / QoS simulator — educational only (not a live DDS session)

Robot software architecture layers
Trajectory gen plugs into the ROS 2 graph with named topics/services/actions and TF frames — swap the module, keep the contracts. Ties Stages 6–9 into one software architecture.

QoS is a contract. Streams want freshness, commands want delivery, and state wants to be remembered. Mismatched contracts give silence, not errors — unless you listen for QoS events.

Knowledge check

Check your understanding

Knowledge check

1. The default QoS for publishers and subscriptions is…

2. A best-effort publisher and a reliable subscription…

3. A reliable publisher and a best-effort subscription…

4. Which durability lets a node that starts later get the last message?

5. The sensor-data profile uses…

6. Which QoS event tells a subscription that messages stopped arriving in time?

7. Why use depth 1 on a command topic?

Mini assignment

Hands-on assignment

Mini assignment

A QoS plan for your 6DOF arm

Choose QoS for every topic of your arm, prove the risky ones with tests, and handle silence safely.

Deliverables

  • A table: topic, publisher QoS, subscriber QoS, why, and what happens on loss.
  • Output of `qos_sim.py` with your extra pair and 30% loss.
  • Optional (ROS 2): `ros2 topic info -v` for two topics and a log line from an incompatible-QoS event.
  • Optional (bench): notes on lag vs skip with reliable and best effort under `tc netem` loss.

Do this, step by step

  1. Run python3 qos_sim.py and add the transient-local best-effort publisher with a volatile reliable subscription; predict first.
  2. Change the loss to 30% in Part 2 and note the longest run of losses.
  3. Make a QoS table for your arm: topic, publisher QoS, subscriber QoS, why, and what happens on loss.
  4. Optional with ROS 2: publish best_effort and echo reliable, then read ros2 topic info -v.
  5. Decide what each control node does if its input goes silent (stop, hold, or warn) and write it in the table.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. A reliable subscriber cannot match a best-effort publisher — the publisher must offer at least what the subscriber asks.
  2. Use best effort for fast sensor streams and reliable for commands and status.
  3. Transient local lets a late joiner get the last message — useful for status and the robot description.

Challenges (pick by level)

  • 🟢 Easy: Change joint_state_node.py to publish with qos_profile_sensor_data and check who can still subscribe.
  • 🟡 Medium: Add a publisher-side deadline to the planner and log “offered deadline missed”.
  • 🟠 Hard-ish: Add an emergency-stop topic with reliable + transient local and make arm_qos_node.py refuse to move until it reads “released”.
  • 🔴 Hard: Run the arm stack on two computers over Wi-Fi, measure topic hz and worst gaps for both profiles, and graph them.
  • ⚫ Research: Read the matched-event demos linked from the QoS concepts page and use a matched event to log when a dashboard connects or leaves.

Next step

You now have topics, services, actions, launch, parameters, tools, TF and QoS. In Lesson 15 — Connecting Sensors, Controllers & Planners you will join them into one working pipeline for the arm.

Look back: Lesson 13: Robot State & TF Trees. Next: Lesson 15: Connecting Sensors, Controllers & Planners. Related: Stage 12 — Simulation.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in