Skip to content
Tech Interview Prep
Technical interview guide

ROS (Robot Operating System) Fundamentals

The de facto standard middleware for robotics software: nodes, topics, and services that let components communicate.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed
Relevant for
Robotics Engineer

Scope: ROS 2 Rolling node, topic, service, action, QoS, executor, callback-group, lifecycle, tf2, parameter, security, rosbag2, and composition documentation reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-23

How do ROS 2 nodes find each other and communicate without a central master, and how would you diagnose two nodes that should be talking but never appear in each other's graph?

Answer

ROS 2 has no master. Every node is a DDS participant, and the graph is assembled by the middleware, not a broker. The stack is rclcpp/rclpy → RMW (rmw_fastrtps_cpp by default in Humble/Iron/Jazzy, rmw_cyclonedds_cpp a common swap) → a DDS/RTPS implementation. So "why can't my nodes see each other" is a DDS discovery question, and the first three things I check are domain ID, RMW implementation, and whether multicast actually reaches between the hosts.

layerresponsibilitywhat breaks it
rclcpp / rclpynodes, topics, executors, QoS API—
RMWmaps the ROS graph onto DDS entitiesRMW_IMPLEMENTATION differs per host
DDS / RTPSSPDP + SEDP discovery, transportmulticast blocked, wrong NIC, domain mismatch

Discovery runs in two phases. SPDP (Simple Participant Discovery Protocol) has each participant periodically multicast an announcement to 239.255.0.1 on a port derived from the domain ID; Fast DDS defaults are a 20 s lease with an announcement every 3 s. SEDP (Simple Endpoint Discovery Protocol) then exchanges publisher/subscriber, type and QoS details over unicast reliable built-in endpoints. Multicast is only the introduction: matching is unicast.

The port arithmetic is what ROS_DOMAIN_ID actually isolates: Fast DDS uses 7400 + 250 × domainID + offset (offset 10 for multicast discovery, 1 for unicast, 11 for user multicast). Domain 0 → 7400/7410/7411; domain 42 → 17900/17910/17911. Different domain means a different multicast group port and a disjoint participant set, so nodes never discover each other and cannot accidentally share a topic. ROS 2 keeps IDs in 0–101 because above that the derived ports collide with the OS ephemeral range.

Diagnosis splits on one symptom. If the node is missing from ros2 node list, it is the discovery layer: compare ROS_DOMAIN_ID and RMW_IMPLEMENTATION on both sides, then ROS_LOCALHOST_ONLY / ROS_AUTOMATIC_DISCOVERY_RANGE (Iron+; LOCALHOST pins everything to loopback), then multicast reachability. If the node is present but no data flows, discovery succeeded and the problem is QoS or type: ros2 topic info -v prints endpoint QoS, and a RELIABLE publisher will not match a BEST_EFFORT subscriber, nor will a VOLATILE subscriber receive a TRANSIENT_LOCAL publisher's history.

Multicast is the usual culprit. Docker's default bridge network does not forward it, corporate WiFi and VPNs often drop it, and a host with several NICs may announce on the wrong one. Fixes in order of preference: run containers with --network host; set a unicast peer list (Fast DDS XML initialPeersList, CycloneDDS <Peers>, or ROS_STATIC_PEERS for Fast DDS); or run a Fast DDS Discovery Server and point clients at it with ROS_DISCOVERY_SERVER. Peer lists and discovery servers also cut the SPDP chatter that hurts at hundreds of participants.

One trap: ros2 node list goes through the ros2 daemon, which caches the graph. After changing domain or RMW, stop the daemon before believing an empty list.

host A

ROS_DOMAIN_ID=42 ros2 run demo_nodes_cpp talker

host B

ROS_DOMAIN_ID=42 ros2 daemon stop && ros2 node list # expect /talker ROS_DOMAIN_ID=42 ros2 topic info -v /chatter # endpoint count + QoS ROS_DOMAIN_ID=42 ros2 doctor --report # RMW, domain, discovery range

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do parameters work in ROS 2 compared to the ROS 1 Parameter Server, and how can node parameters be declared, monitored, and dynamically reconfigured?

Answer

The 90-second answer

ROS 1 has one global parameter store inside roscore. Every rospy.get_param / ros::param::get is an XML-RPC call to the master, names are global (/robot/max_vel), and any node can read or write any key whether or not the owning node is alive. There is no declaration step and no type contract, so dynamic_reconfigure exists as a separate package to bolt on validation and change notification.

ROS 2 deletes the server. A parameter is a named, typed value owned by exactly one node, reachable only while that node runs. The node declares it (name, type, default, optional descriptor) and the declaration is the contract. Reconfiguration is a service call to the node (rcl_interfaces/srv/SetParameters), and every change is broadcast on /parameter_events. dynamic_reconfigure is gone; its job is add_on_set_parameters_callback.

Three consequences follow. Parameters are node-local, so two nodes can both own max_velocity without collision. A parameter file is applied as overrides at startup, not as a global store. And you cannot read a parameter from a node that isn't running.

Declaring

Types are the eight in rcl_interfaces/msg/ParameterValue: bool, int64, double, string, plus byte/bool/int64/double/string arrays. No nested structures: a real regression from ROS 1, where a param could be a dict.

C++
// C++17, rclcpp (ROS 2 Jazzy)
auto desc = rcl_interfaces::msg::ParameterDescriptor{};
desc.description = "Max linear velocity in m/s";
rcl_interfaces::msg::FloatingPointRange range;
range.from_value = 0.0;
range.to_value   = 2.5;
range.step       = 0.05;
desc.floating_point_ranges.push_back(range);

this->declare_parameter<double>("max_velocity", 1.0, desc);

declare_parameter throws rclcpp::exceptions::InvalidParameterValueException if the value, default or override, violates the descriptor, so a bad YAML file fails at startup rather than silently. read_only = true in the descriptor makes it immutable after declaration. The node options allow_undeclared_parameters and automatically_declare_parameters_from_overrides relax the rule; convenient when porting, but you give up the contract.

Reconfiguring

C++
cb_handle_ = this->add_on_set_parameters_callback(
  [this](const std::vector<rclcpp::Parameter> & params) {
    rcl_interfaces::msg::SetParametersResult r;
    r.successful = true;
    for (const auto & p : params) {
      if (p.get_name() == "max_velocity" && p.as_double() > hardware_limit_) {
        r.successful = false;
        r.reason = "Requested velocity exceeds hardware safety cap";
        return r;
      }
    }
    return r;
  });

The callback runs before the value is stored. Return successful = false and the change is rejected, with reason sent back to the caller. Atomicity has two levels: SetParameters applies each parameter independently, so a rejection on one leaves the others applied; SetParametersAtomically is all-or-nothing. Use the atomic variant when two parameters must move together, e.g. min_velocity and max_velocity.

The callback only sees changes. An initial value from a YAML override is validated by the descriptor, not by your callback, so any invariant that isn't expressible as a descriptor range has to be re-checked in the constructor.

Monitoring

Every declare, set and delete publishes a rcl_interfaces/msg/ParameterEvent on the global /parameter_events topic, split into new_parameters, changed_parameters and deleted_parameters. Subscribing raw works, but you get every node's traffic. rclcpp::ParameterEventHandler filters by node name and gives you a per-parameter callback:

C++
auto handler = std::make_shared<rclcpp::ParameterEventHandler>(this);
auto cb = [this](const rclcpp::Parameter & p) {
  RCLCPP_INFO(get_logger(), "peer set %s = %f", p.get_name().c_str(), p.as_double());
};
handler->add_parameter_callback("max_velocity", cb, "/nav_node");

CLI: ros2 param list, ros2 param describe <node> <param> (prints type, description and constraints), ros2 param get, ros2 param dump <node> to YAML, ros2 param load. Startup overrides come from --ros-args -p max_velocity:=1.5 or --params-file cfg.yaml, where the YAML is keyed by node name under ros__parameters:.

Trace: a rejected set

$ ros2 param set /nav_node max_velocity 3.0
Setting parameter failed: Requested velocity exceeds hardware safety cap
$ ros2 param set /nav_node max_velocity 1.5
Set parameter successful

The first call is a SetParameters request to /nav_node/set_parameters. The node's callback rejects it, so no ParameterEvent is published and the stored value is unchanged. The second passes, the value is written, and a ParameterEvent carrying max_velocity in changed_parameters goes out on /parameter_events.

Comparison

ROS 1 Parameter ServerROS 2 node parameters
TopologyCentral, in roscore, XML-RPCPer-node, over DDS services
LifetimeSurvives node deathDies with the node
NamesGlobal (/robot/max_vel)Node-relative
DeclarationNone; any key, any timeRequired; typed, with descriptor
ValuesNested dicts and lists allowedEight flat types, arrays only
Reconfiguredynamic_reconfigure, .cfg filesadd_on_set_parameters_callback
NotificationPoll, or hand-rolled/parameter_events, ParameterEventHandler
Startup configroslaunch <param> into the server--params-file / -p as overrides

Failure modes

  • Callback handle dropped. add_on_set_parameters_callback returns a handle; if you don't store it, the callback is unregistered and validation silently stops. Store it as a member.
  • Callback registered after declaration. Initial values bypass it. Register in the constructor, and re-validate anything the descriptor can't express.
  • Slow callback. It runs on the node's executor thread; a blocking call there stalls every other subscription. Keep it to comparisons.
  • Non-atomic multi-parameter set. A partial apply leaves an inconsistent config. Use SetParametersAtomically.
  • /parameter_events as a firehose. On a large graph, subscribe through ParameterEventHandler rather than globally.
  • Parameters as a data plane. A 100 Hz setpoint belongs on a topic; a parameter set is a service round-trip plus an event publish.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

How do ROS 2 Managed (Lifecycle) Nodes work, and what are the primary lifecycle states and transitions?

Answer

A ROS 2 managed (lifecycle) node is a rclcpp_lifecycle::LifecycleNode whose startup, shutdown and fault handling are driven by an explicit state machine rather than by the constructor. The node exposes ~/get_state, ~/change_state, ~/get_available_transitions and ~/get_available_states services. An external supervisor (a lifecycle manager, a launch file, or ros2 lifecycle set) calls change_state with a transition name, and the node runs the matching callback. The payoff is that "is this node ready?" becomes a standard, queryable property instead of a convention each team invents.

States

Four primary states: Unconfigured (1), Inactive (2), Active (3), Finalized (4). Seven transition states: Configuring (10), CleaningUp (11), ShuttingDown (12), Activating (13), Deactivating (14), ErrorProcessing (15), Finalizing (16).

  • Unconfigured: constructed, parameters declared, nothing allocated.
  • Inactive: publishers, subscribers and services exist and hardware handles are open, but LifecyclePublisher::publish() drops messages and timers are not firing.
  • Active: fully operational.
  • Finalized: resources released; only destroy remains.
                 configure            activate
  Unconfigured ──────────▶ Inactive ──────────▶ Active
       ▲                      │  ▲                 │
       └────── cleanup ───────┘  └─── deactivate ──┘
       │                      │                    │
       └──────── shutdown ────┴──── shutdown ──────┘
                            ▼
                        Finalized

Transitions

TransitionCallbackWhat it must do
configureon_configureRead static params, validate, allocate buffers, open device handles.
activateon_activateEnable actuators, call pub->on_activate(), start timers.
deactivateon_deactivateStop motion, pub->on_deactivate(), cancel timers.
cleanupon_cleanupReset state, destroy endpoints, close descriptors.
shutdownon_shutdownReachable from Unconfigured, Inactive or Active; release everything.
erroron_errorInvoked when a callback returns CallbackReturn::ERROR or throws. A successful on_error lands the node in Unconfigured (Finalized if the error came from Finalized).

CallbackReturn::FAILURE is not the same as ERROR: FAILURE aborts the transition and leaves the node in its previous state, with no on_error call. Use FAILURE for "the device isn't plugged in"; use ERROR for "something is broken and the node needs to be torn down".

Implementation

C++
#include <chrono>
#include <memory>
#include "rclcpp_lifecycle/lifecycle_node.hpp"
#include "rclcpp_lifecycle/lifecycle_publisher.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

class SensorNode : public rclcpp_lifecycle::LifecycleNode
{
public:
  SensorNode() : rclcpp_lifecycle::LifecycleNode("sensor_node") {}

  CallbackReturn on_configure(const rclcpp_lifecycle::State &) override
  {
    pub_ = create_publisher<std_msgs::msg::String>("sensor_data", 10);
    timer_ = create_wall_timer(100ms, [this]() { publish_sample(); });
    timer_->cancel();  // created but silent until Active
    return CallbackReturn::SUCCESS;
  }

  CallbackReturn on_activate(const rclcpp_lifecycle::State &) override
  {
    pub_->on_activate();
    timer_->reset();
    return CallbackReturn::SUCCESS;
  }

  CallbackReturn on_deactivate(const rclcpp_lifecycle::State &) override
  {
    timer_->cancel();
    pub_->on_deactivate();
    return CallbackReturn::SUCCESS;
  }

  CallbackReturn on_cleanup(const rclcpp_lifecycle::State &) override
  {
    timer_.reset();
    pub_.reset();
    return CallbackReturn::SUCCESS;
  }

  CallbackReturn on_shutdown(const rclcpp_lifecycle::State &) override
  {
    timer_.reset();
    pub_.reset();
    return CallbackReturn::SUCCESS;
  }

  CallbackReturn on_error(const rclcpp_lifecycle::State &) override
  {
    timer_.reset();
    pub_.reset();
    return CallbackReturn::SUCCESS;
  }

private:
  void publish_sample()
  {
    std_msgs::msg::String msg;
    msg.data = "sample";
    pub_->publish(msg);
  }

  rclcpp_lifecycle::LifecyclePublisher<std_msgs::msg::String>::SharedPtr pub_;
  rclcpp::TimerBase::SharedPtr timer_;
};

Bringup trace

StepCommandState afterID
1(process starts)unconfigured1
2ros2 lifecycle set /sensor_node configureinactive2
3ros2 lifecycle set /sensor_node activateactive3
4ros2 lifecycle set /sensor_node deactivateinactive2
5ros2 lifecycle set /sensor_node cleanupunconfigured1
6ros2 lifecycle set /sensor_node shutdownfinalized4

When the state machine earns its keep

It pays off when startup order is a correctness property, not a convenience. A mobile base must not command wheel torque until LiDAR, IMU and costmap are all publishing; a planner must not run before the map server has loaded; a supervisor must be able to stop actuation across N nodes with one call. The deciding criteria are: (a) more than one node whose readiness depends on another, (b) hardware that is unsafe to actuate before its inputs are live, (c) a supervisor that must recover a node after a crash without restarting the process.

When it is not worth it

A single node with no hardware and no downstream dependency (a pub/sub bridge, a parameter server, a visualization node) gains nothing. You write five callbacks, wrap every publisher in LifecyclePublisher, and add a manager process, to get a state machine nobody queries. The hand-rolled alternative is a plain rclcpp::Node with a bool initialized_ flag and a ~/start service: about twenty lines, no dependencies. What it loses is everything standard: no ros2 lifecycle get, no ros2 lifecycle set from a shell or launch file, no LifecycleNode launch action, no bond heartbeat, no uniform error path. Every consumer has to learn your bespoke service. That is the real trade: tool-visible orchestration versus twenty lines and no dependencies.

The standard path has its own costs. The manager is a single point of failure, if it dies, nodes stay in whatever state they were in. Transition callbacks run on the node's executor, so a blocking call inside on_configure stalls every other callback on that executor. And the lifecycle publisher is opt-in per publisher: miss one and it publishes in Inactive.

Failure modes

  • Deadlock in a transition callback. A synchronous service call to another node on the same single-threaded executor blocks the executor that must service the reply. Detected by ros2 lifecycle get hanging and the manager's bond timeout firing (Nav2's bond_timeout defaults to 4.0 s).
  • Non-lifecycle publisher. A plain rclcpp::Publisher bypasses the state machine and publishes in Inactive. Detected by ros2 topic hz showing traffic while ros2 lifecycle get reports inactive.
  • FAILURE mistaken for ERROR. Returning FAILURE leaves the node in its previous state and never calls on_error, so a failed configure silently leaves the node unconfigured. Detected by checking ros2 lifecycle get after a transition that reported failure.
  • Timer not cancelled in on_deactivate. The callback keeps firing in Inactive. Detected by log output while the node reports inactive.
  • Manager death. Nodes are stranded in their last state with no one to recover them. Detected by the bond heartbeat stopping.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Choose topic, service, or action for an interface.

Answer

I'll pin the assumptions first: ROS 2, Humble or later, one robot with one arm, and the interface is being chosen per message flow rather than once for the whole system. With that, the choice falls out of three questions asked in order.

  1. Is this a continuous flow or one discrete exchange? Continuous, many-to-many, latest-value-wins tolerated: topic.
  2. If discrete, must the caller have the answer before it does anything else, and does the work finish inside a normal call timeout, say tens of milliseconds? Service.
  3. If not - seconds to minutes, and the caller wants progress or the ability to abort: action.

The mechanical reason they differ:

  • A topic is publish/subscribe with fan-out. One publish reaches every matched subscriber and the publisher never waits on the application layer. Connection cost scales per matched subscriber, not per message.
  • A service is a request/response pair riding two DDS endpoints. The runtime correlates the reply to the request, so you do not build correlation yourself; the thread blocks only if you spin until the future completes.
  • An action is three services plus two topics - send_goal, cancel_goal, get_result, and a feedback topic and a status topic. That extra machinery is why it is the only one with a goal state machine (ACCEPTED, EXECUTING, CANCELING, then CANCELED, SUCCEEDED or ABORTED) and the only one to reach for when cancellation is a requirement.

Worked example, same arm, three interfaces:

interfacechoicewhy
joint positions, 100 Hztopic, SensorDataQoSbest-effort, volatile, keep-last 5: drop a sample rather than stall the publisher
"set tool digital output"service, timeout ~2x measured p99about 10 ms round trip on the same host
"move to pose, abort if a person enters"actiongoal runs 3-8 s, needs cancel and periodic feedback

Arithmetic for the first row: a JointState with 7 joints, positions only, is roughly 56 bytes of doubles plus seven length-prefixed names, so around 150-200 bytes serialized; at 100 Hz that is about 20 KB/s per subscriber. The same information as services would be 100 correlated request/response pairs a second, each occupying the client, and a single-threaded executor would spend its time in the client instead of servicing its own subscriptions.

QoS is where the topic decision is actually made. The default profile is reliable, volatile, keep-last 10; SensorDataQoS is best-effort, volatile, keep-last 5. Two rules cover most bugs. A best-effort publisher never matches a reliable subscriber - no data flows - which is the classic "publisher exists, subscriber exists, nothing arrives" failure; ros2 topic info -v prints both sides' profiles and ros2 topic hz prints the rate, and the subscription fires a requested-incompatible-QoS event. Second, reliable is not an application acknowledgement: it means DDS delivered the sample, not that your callback ran on it.

Failure modes and how they surface:

  • A command sent as a topic: last writer wins, silently. Two nodes publishing opposite commands to the same arm topic with no arbitration is invisible at the transport because nothing answers. Give each command an id on an event topic, or do not use a topic for it.
  • A service used for a 30 s motion: the client blocks and stops consuming its own subscriptions, so its 100 Hz watchdog input goes quiet and trips. Make the call async, or use an action.
  • Service server dies mid-call: with no timeout the client waits forever. Pass a timeout at about twice the measured p99 and handle the empty future.
  • Action cancel is cooperative. cancel_goal returns CANCELING, not CANCELED. If status sits in CANCELING past your deadline, treat the motion as still running and e-stop rather than assume it stopped.
  • Reliable topic with a slow subscriber: keep-last drops the oldest silently. ROS 2 headers carry stamp and frame_id but no sequence number, so if the consumer must see gaps, put your own counter in the message.

Where I would not use them: no service on a 100 Hz-plus control path; no action for sub-second work, because the goal handshake is an extra round trip plus acceptance; no topic when the caller must know the outcome.

Last point, and it is the one people get wrong under pressure: delivery is not authority. Whether a node is allowed to command the arm belongs in an explicit ownership check on the receiving node, or in DDS Security / SROS 2 per-node permissions - never in the fact that the message arrived.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Choose node and process boundaries for a robot subsystem.

Answer

Assumptions: ROS 2 Humble or Jazzy, one robot, one onboard computer, default rmw_fastrtps_cpp, no hard real-time requirement beyond the control loop.

Answer. A node is the unit of coherent state, lifecycle and interface. A process is the unit of fault isolation, security identity, CPU scheduling and deployment. Default to one node per process; merge nodes into a component container only when the link between them is high-bandwidth, latency-critical, and the two genuinely share fate.

Decide in this order:

  1. Fault containment. If a crash in A must not stop B, separate processes. A segfault in a perception node inside a shared container takes the camera driver down with it.
  2. Security identity. SROS2 enclaves are per-process, i.e. per DDS participant. If the planner must not be able to publish to the motor topic, it needs its own process and its own enclave.
  3. Scheduling. taskset, chrt and cgroup CPU weights are per-process. A 1 kHz control loop wants its own process pinned to a core, not sharing a thread pool with a 30 Hz camera.
  4. Copy cost. Crossing a process boundary serializes and copies. Intra-process comms hands over a pointer instead.
  5. Deployment and debugging. One process per container is the easy deploy unit; gdb attach and restart are per-process.
FactorSplitMerge
CrashMust not take peer downShared fate OK
SecurityDifferent enclaveSame trust domain
SchedulingDifferent rate/prioritySame rate/priority
DataSmall, low rateLarge, high rate
DebugPer-node restart neededRestart together anyway

Worked example. A 1280×720 RGB camera at 30 Hz is 2.76 MB/frame, ~83 MB/s. Split camera driver and detector: each frame is serialized and copied. A 2.76 MB memcpy at ~10 GB/s is ~0.3 ms; DDS serialization is the same order. Call it 0.5–1 ms per frame: 1.5–3% of a 33 ms budget: plus a second copy of in-flight frames resident in memory. That alone doesn't force a merge. If both run at 30 Hz and always live and die together, put them in one component container with intra-process comms and the copy disappears:

C++
// ROS 2 Humble, rclcpp
auto opts = rclcpp::NodeOptions().use_intra_process_comms(true);
auto cam = std::make_shared<CameraNode>(opts);
auto det = std::make_shared<DetectorNode>(opts);
rclcpp::executors::MultiThreadedExecutor exec;
exec.add_node(cam); exec.add_node(det); exec.spin();

// publisher side: move, do not copy
auto frame = std::make_unique<sensor_msgs::msg::Image>();
fill(*frame);
pub_->publish(std::move(frame));

Both nodes need the option, and intra-process delivery only reaches subscribers in the same process and context: it is not a substitute for the network path.

The motor controller is the counter-example: 1 kHz, tiny messages, but it stays in its own pinned process with its own enclave, because a planner crash must not stop the wheels.

Failure modes.

  • Duplicate node names. ros2 param is keyed by node name, so two /perception nodes make ros2 param get /perception x ambiguous. Detect with ros2 node list | sort | uniq -d.
  • Unexpected peers. A stale container or a second robot on the same ROS_DOMAIN_ID. Detect with ros2 node list and ros2 topic info /cmd_vel --verbose, which prints publisher GIDs. Fix with a per-robot domain ID or a per-robot SROS2 CA.
  • Container crash. Every component in it dies at once; ros2 component list goes empty. Mitigate with respawn=True in the launch file or an external supervisor.
  • Restart. A restarted publisher re-advertises; volatile subscribers miss the gap, transient_local ones get the last sample. Detect as a gap in ros2 topic hz.
  • Partial dependency. A node starts before its dependency. Detect with ros2 lifecycle get stuck in unconfigured; use lifecycle nodes with ordered launch, or wait_for_service with a timeout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How does rosbag2 record and replay topics, and how is simulation time handled during replay?

Answer

Core answer

rosbag2 is a recorder node plus a player node over a pluggable storage format. ros2 bag record creates one generic subscription per selected topic, receives rclcpp::SerializedMessage buffers (CDR-encoded, 4-byte encapsulation header included), and hands them to a writer plugin that appends (topic, type, receive_timestamp, payload). ros2 bag play reads those records back in timestamp order, creates one generic publisher per topic using the QoS stored in the bag's metadata.yaml, and sleeps between messages so the recorded inter-message deltas are reproduced in wall time. Simulation time is a separate, opt-in concern: the player publishes /clock only when you pass --clock, and consumers follow it only when use_sim_time:=true. Get either half wrong and the bag replays cleanly while every consumer's timers and tf lookups sit at time zero.

Recording

  • Discovery. The recorder queries the graph, resolves each topic's type name, and calls create_generic_subscription(topic, type, qos, cb) with callback signature (std::shared_ptr<rclcpp::SerializedMessage>, const rclcpp::MessageInfo&). Nothing is deserialized into C++ structs. The type's typesupport library must be installed in the recorder's environment; if it is not, the subscription fails and the topic is not recorded.
  • QoS. The recorder adapts its subscription QoS to the publishers' offered QoS (Rosbag2QoS::adapt_request_to_offers). A best_effort publisher gets a best_effort subscription; a transient_local publisher gets transient_local durability so the latched message is captured. --qos-profile-overrides-path forces a profile instead.
  • Timestamp. The stored timestamp is when the recorder received the message, not the header stamp. Replay therefore reproduces recorder-side jitter, not publisher-side.
  • Storage. sqlite3 writes one .db3 plus metadata.yaml; mcap writes a self-describing, chunked file with optional zstd/lz4 compression. MCAP is the default storage plugin since Jazzy; Humble and Iron default to sqlite3. --max-bag-size and --max-bag-duration rotate files.

Replay and simulation time

ros2 bag play bag --clock -r 1.0
  reads records in timestamp order
  publishes /clock (rosgraph_msgs/msg/Clock) with the current bag timestamp
  publishes each topic with the QoS from metadata.yaml

  /clock ─────────────► node (use_sim_time:=true)
                        clock = RCL_ROS_TIME, driven only by /clock
                        node->now(), timers, tf2 buffer, Rate all follow it
  /camera/image ──────► same node, payload stamped in sim time

Worked trace: records at bag time 0.000 s, 0.033 s, 0.100 s:

ratewall sleeps between publishes/clock values published
-r 1.033 ms, then 67 ms0.000, 0.033, 0.100
-r 0.566 ms, then 134 ms0.000, 0.033, 0.100
-r 2.016.5 ms, then 33.5 ms0.000, 0.033, 0.100

/clock always carries bag time; only the wall-clock spacing changes. Other player flags: --start-offset, --start-paused, --loop, --topics.

Failure modes

IssueMechanismFailure modeMitigation
--clock omittedNo /clock publisher existsA use_sim_time:=true node's clock is pinned at 0; timers never fire, tf buffer never fillsPass --clock to ros2 bag play
Mismatched use_sim_timePlayer drives sim time; node left on system timetf2::LookupException (extrapolation into the future/past); timers fire on wall time and outrun the bagSet use_sim_time:=true on every node in the replay graph
Latched topic not capturedRecorder subscription durability does not match the publisher's transient_localThe initial latched message is missing from the bag; replay starts with empty stateRecord with a QoS override setting durability transient_local
Replay QoS mismatchBag recorded best_effort; a subscriber requests reliableNo connection, topic silently absent downstream--qos-profile-overrides-path on ros2 bag play
Wall-clock timers in consumersNode uses steady/system clock for timeouts while data arrives on sim timeBuffers overflow or frames drop when replay is paused or rate-scaledUse node->now() (backed by RCL_ROS_TIME) for all internal timing

ros2 bag info reports message counts, duration and size per topic; ros2 bag convert rewrites a bag between storage plugins.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you achieve thread-safe shared state management between subscription callbacks and timer callbacks in a MultiThreadedExecutor?

Answer

In ROS 2 (rclcpp), assigning a subscription and a timer to a MultiThreadedExecutor means their callbacks can execute simultaneously on distinct worker threads. By default, every node entity is added to the node's default MutuallyExclusiveCallbackGroup. If both the subscription and the timer share this default group, the executor will never schedule them concurrently, making access to shared state trivially serialized but exposing the timer to latency jitter if the subscription callback blocks.

To decouple scheduling while guaranteeing thread safety, use distinct callback groups or a ReentrantCallbackGroup, paired with explicit synchronization primitives around shared state.

C++
class StateSyncNode : public rclcpp::Node {
public:
  StateSyncNode() : Node("state_sync_node") {
    sub_cb_group_ = create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
    timer_cb_group_ = create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);

    rclcpp::SubscriptionOptions sub_opts;
    sub_opts.callback_group = sub_cb_group_;
    sub_ = create_subscription<geometry_msgs::msg::Twist>(
      "cmd_vel", 10, std::bind(&StateSyncNode::on_command, this, std::placeholders::_1), sub_opts);

    // 50 Hz control loop
    timer_ = create_wall_timer(
      std::chrono::milliseconds(20),
      std::bind(&StateSyncNode::on_timer, this),
      timer_cb_group_);
  }

private:
  void on_command(const geometry_msgs::msg::Twist::SharedPtr msg) {
    std::lock_guard<std::mutex> lock(state_mutex_);
    latest_cmd_ = *msg;
    has_new_cmd_ = true;
  }

  void on_timer() {
    geometry_msgs::msg::Twist local_cmd;
    bool process_cmd = false;
    {
      std::lock_guard<std::mutex> lock(state_mutex_);
      local_cmd = latest_cmd_;
      process_cmd = has_new_cmd_;
      has_new_cmd_ = false;
    }
    if (process_cmd) {
      // Execute control computations without holding the lock
      compute_control(local_cmd);
    }
  }

  rclcpp::CallbackGroup::SharedPtr sub_cb_group_;
  rclcpp::CallbackGroup::SharedPtr timer_cb_group_;
  rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr sub_;
  rclcpp::TimerBase::SharedPtr timer_;
  std::mutex state_mutex_;
  geometry_msgs::msg::Twist latest_cmd_;
  bool has_new_cmd_{false};
};

Design Trade-offs

StrategyProsCons / Failure Modes
Shared MutuallyExclusive GroupZero synchronization code; impossible to race internally.Head-of-line blocking: slow sensor ingress immediately stalls high-rate periodic timers.
Distinct Groups + Fine-Grained std::mutexIndependent callback dispatch; timer preserves periodic deadlines.Lock contention if critical section is too wide; priority inversion under real-time scheduling.
Double Buffering / std::atomicLock-free reads in timer; zero blocking on high-frequency loops.Higher memory footprint; complex memory order semantics if state spans non-trivially copyable objects.

Failure Modes & Defenses

  1. Unintentional Serialization: Leaving callbacks in the default group causes silent serialization despite instantiating MultiThreadedExecutor(..., numberOfThreads = 4). Verify using ROS 2 trace points (ros2_tracing) by inspecting callback start/finish timestamps.
  2. Critical Section Bloat: Holding state_mutex_ during compute or I/O (e.g., logging or publishing) delays the counterpart callback. Always copy shared state locally within a scoped block and compute uninhibited.
  3. Deadlocks with Nested Service Calls: Holding state_mutex_ while calling client->async_send_request() and blocking with future.wait() starves executor threads. Never block synchronously inside a callback running under an executor.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Choose QoS for high-rate sensor data versus a safety command.

Answer

Assumptions

ROS 2 (Humble/Iron), rmw_fastrtps or CycloneDDS, publisher and subscriber on the same LAN. Sensor stream ~1 kHz IMU; command stream ~20 Hz from a planner or operator. If your transport is a lossy radio link, the numbers move but the split does not.

The 90-second answer

Use two profiles, not one.

Sensor stream: BEST_EFFORT, KEEP_LAST depth 5, VOLATILE, no deadline. This is exactly rclcpp::SensorDataQoS(). You want the newest sample, and you accept gaps.

Command: RELIABLE, KEEP_LAST depth 1, VOLATILE, plus a finite deadline, a finite lifespan, and a MANUAL_BY_TOPIC liveliness lease. On top of that, put a sequence number and an application-level ack in the message: topic receipt is not command execution.

Why depth bounds age

The writer history is a ring of depth samples. At rate R, the oldest sample a stalled reader can still receive is depth / R seconds old. At 1 kHz with depth 5 that window is 5 ms; depth 10 makes it 10 ms. BEST_EFFORT means the transport drops rather than retransmits, so a reader that stalls 50 ms loses ~45 samples and resumes at the newest one instead of replaying a 50 ms backlog. KEEP_ALL with RELIABLE does the opposite: it queues the backlog and delivers stale IMU data, which is worse than a gap for a controller.

Reliability matching is directional. A BEST_EFFORT publisher and a RELIABLE subscriber do not match: no connection, no data, no error unless you check. A RELIABLE publisher and BEST_EFFORT subscriber do match.

Why the command side is different

RELIABLE guarantees delivery to connected readers, not across a partition. If the link drops, the writer retries; the command may then arrive after it is stale. That is what lifespan is for: samples older than the lifespan are dropped before delivery. deadline fires on_deadline_missed when no sample arrives within the period, which is your trigger for a safe fallback (zero velocity, hold position). The liveliness lease fires on_liveliness_changed with not_alive when the publisher stops asserting, which is how you detect a dead planner rather than a quiet one.

Failure modes and detection

FailureBehaviourDetect
Sensor reader stallsSamples dropped, gap in streamSequence/counter field in message; on_deadline_missed if a deadline is set
Command partitionRELIABLE retries, nothing deliveredLiveliness lease expiry (not_alive), then deadline miss → fallback
Queue fullKEEP_LAST overwrites silently; KEEP_ALL+RELIABLE can block the publisher threadPublisher history depth, rmw logs
Stale command after reconnectOld command replayedlifespan drops it; sequence number lets receiver reject out-of-order
Duplicate commandSame command applied twiceIdempotency key in message; ack carries the sequence number

Worked check

1 kHz IMU, KEEP_LAST depth 5 → 5 ms window. Subscriber stalls 50 ms → 45 samples dropped, resumes at newest. Command at 20 Hz with deadline 100 ms, lifespan 200 ms, liveliness lease 300 ms: planner dies, lease expires at 300 ms, on_liveliness_changed fires, no command within 100 ms → on_deadline_missed → fallback. A command queued during a 500 ms partition is older than the 200 ms lifespan and is dropped on reconnect rather than executed late.

What changes the decision: if the sensor is a safety input rather than a control input, it moves to the command profile (RELIABLE, finite deadline, liveliness) because a gap is then a fault, not a freshness trade.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Specify and test a topic QoS contract.

Answer

Assume ROS 2 (rclcpp, Humble or Jazzy) and that "contract" means the publisher's offered QoS must be at least as strong as the subscriber's requested QoS. The middleware checks this at match time; if it fails, the endpoints never connect and, unless you registered a callback, nothing tells you.

A topic QoS is seven policies. rclcpp's defaults are KeepLast(10), RELIABLE, VOLATILE, infinite deadline, infinite lifespan, AUTOMATIC liveliness with infinite lease. You pick values by classifying the data:

datareliabilityhistorydurabilitydeadlinelifespan
100 Hz IMUBEST_EFFORTKeepLast(5)VOLATILE20 ms50 ms
actuator commandRELIABLEKeepLast(1)VOLATILE∞∞
config / last stateRELIABLEKeepLast(1)TRANSIENT_LOCAL∞∞
event logRELIABLEKeepLast(1000)TRANSIENT_LOCAL∞∞

rclcpp::SensorDataQoS() is exactly the IMU row: BEST_EFFORT, KeepLast(5), VOLATILE.

Compatibility is a partial order, not equality:

policyofferrequestmatch?
reliabilityRELIABLEBEST_EFFORTyes
reliabilityBEST_EFFORTRELIABLEno
durabilityTRANSIENT_LOCALVOLATILEyes
durabilityVOLATILETRANSIENT_LOCALno
deadline20 ms50 msyes (offer ≤ request)
deadline50 ms20 msno
livelinessMANUAL_BY_TOPICAUTOMATICyes
livelinessAUTOMATICMANUAL_BY_TOPICno

So a RELIABLE publisher serves both kinds of subscriber; a BEST_EFFORT publisher only serves BEST_EFFORT subscribers. Same shape for durability, deadline, lease duration, and liveliness kind.

Concretely, the IMU publisher:

C++
// ROS 2 Jazzy, rclcpp
auto qos = rclcpp::QoS(rclcpp::KeepLast(5))
  .best_effort()
  .durability_volatile()
  .deadline(rclcpp::Duration::from_seconds(0.02))
  .lifespan(rclcpp::Duration::from_seconds(0.05));
auto pub = create_publisher<sensor_msgs::msg::Imu>("/imu", qos);

and the subscriber that refuses to fail silently:

C++
rclcpp::SubscriptionOptions opts;
opts.event_callbacks.incompatible_qos_callback =
  [](rclcpp::QOSRequestedIncompatibleQoSInfo & info) {
    RCLCPP_ERROR(rclcpp::get_logger("qos"),
                 "QoS mismatch, policy %d", info.last_policy_kind);
  };
auto sub = create_subscription<sensor_msgs::msg::Imu>("/imu", qos, cb, opts);

Testing is a matrix, not a smoke test. For each topic: (1) loss. Kill the subscriber mid-stream and confirm the publisher keeps running; (2) burst. Publish at 10× rate and watch for dropped samples under BEST_EFFORT; (3) late join. Start the subscriber after the publisher and check TRANSIENT_LOCAL delivers the retained sample; (4) restart, bounce the publisher and confirm the subscriber reconnects; (5) partition, drop traffic with iptables and confirm deadline/liveliness events fire; (6) slow consumer, a subscriber that sleeps 100 ms per callback; (7) mixed vendor, run rmw_cyclonedds on one side and rmw_fastrtps on the other, since compatibility is enforced by the rmw, not the client library. ros2 topic info --verbose prints the actual offered and requested QoS for both sides, which is the first thing to read when a topic is silent.

Failure modes worth naming. Incompatibility is silent by default: both endpoints appear in ros2 topic list, ros2 topic info shows one publisher and one subscriber, and zero messages flow. RELIABLE + KeepAll with a slow subscriber blocks the publisher inside publish() on the default rmw, stalling the executor thread: that is why the event log above uses KeepLast(1000). TRANSIENT_LOCAL with depth 1 gives a late joiner only the newest sample; raise depth if you need history. A subscriber deadline shorter than the publisher's period fires on_requested_deadline_missed continuously and is a config bug, not a network bug.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Use transient-local durability without replaying stale control.

Answer

What I'd say first

Transient-local durability means the DataWriter keeps a history cache in memory and replays it to a DataReader that joins after the sample was written. That is exactly what you want for state, a late-joining planner needs the current map or config, and exactly what you don't want for control, because a replayed "arm" or "start" is a second execution of a command that already happened.

So the split is by topic, not by QoS tuning: state topics get TRANSIENT_LOCAL, command and event topics stay VOLATILE. Then you make the retained state safe to replay.

Assumptions: OMG DDS (same behaviour in RTI Connext and Fast DDS), reliable transport, one logical state topic per entity key.

Making the retained sample safe

Four things do the work:

  1. History KEEP_LAST, depth 1, per instance. The writer's cache holds only the newest sample per instance key, so a late joiner gets the current value, not a queue of old ones. KEEP_ALL with transient-local is how you accidentally replay a backlog.
  2. Lifespan. A sample older than its lifespan is treated as expired and is not delivered to a late joiner. Set it to the longest the state can be true without a refresh: 5 s for a heartbeat-driven pose, infinite only for genuinely static config.
  3. Version/sequence plus issue time in the payload. The reader compares against what it already applied and drops anything not newer. This is what makes replay idempotent at the application layer, where QoS can't help you.
  4. Ownership EXCLUSIVE with strength. With two publishers on the same instance (primary/backup), only the highest-strength writer's samples are delivered, and ownership transfers when the primary dies. Without it, a late joiner can get samples from both.
QoSState topicCommand topic
DurabilityTRANSIENT_LOCALVOLATILE
HistoryKEEP_LAST, depth 1KEEP_LAST, depth 1
Lifespanfinite (e.g. 5 s)n/a
ReliabilityRELIABLERELIABLE
OwnershipEXCLUSIVE + strengthSHARED
ResourceLimitsmax_samples_per_instance = depthsmall

DDS spec defaults are Durability VOLATILE, History KEEP_LAST depth 1, Reliability BEST_EFFORT, Lifespan infinite, Ownership SHARED, so every line above is a deliberate change from the default.

Trace: late join

Writer W publishes pose for instance robot-7 at t=0 (v1), t=1 (v2), t=2 (v3); lifespan 5 s, KEEP_LAST depth 1.

  • Reader R joins at t=3. W's cache holds only v3, so R receives v3. Correct.
  • R joins at t=8. v3 is 6 s old, past its 5 s lifespan, so it is expired and R receives nothing until the next write. That is the right outcome: no state beats 6-second-old state.
  • W restarts at t=4. Its cache is gone; transient-local does not survive writer restart. R gets nothing until W republishes. Surviving restart needs TRANSIENT or PERSISTENT plus a persistence service.

Failure modes

  • Stale replay. A reader applies an old command. Detected by duplicate side effects; fixed by keeping commands VOLATILE.
  • Cache growth. KEEP_ALL + transient-local + many instances grows writer memory until ResourceLimits blocks the write. Watch max_samples and the sample-rejected count.
  • Durability mismatch. A reader requesting TRANSIENT_LOCAL against a VOLATILE writer never matches: no data, and nothing louder than a QoS-incompatible match status. Check the matched-status API during discovery.
  • Ownership flap. Two writers with equal strength on one instance; readers see interleaved values. Detected by instance-state churn.

When not to use it

Commands, events, and anything where "delivered twice" is worse than "not delivered". Also anything that must survive writer restart: that is TRANSIENT/PERSISTENT, and it costs a persistence service and disk.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Specify time semantics for a ROS system that runs live and in simulation.

Answer

Core answer (first 90 seconds)

Three clocks, one rule each.

  • RCL_ROS_TIME: the node's ROS clock. With use_sim_time at its default false it mirrors system time; with true it is driven by the /clock topic (rosgraph_msgs/msg/Clock). Use it for anything that must agree with message header stamps, TF, and the simulator's notion of "now".
  • RCL_STEADY_TIME: monotonic, unaffected by wall-clock steps or a sim pause. Use it for local elapsed time and deadlines: retry backoff, watchdogs, "has this been stuck for 2 s".
  • RCL_SYSTEM_TIME: wall clock, NTP-adjustable. Use it only for calendar correlation: log dates, TLS cert expiry, external scheduling.

The deciding criterion: does the value have to be comparable with a stamp produced by another node or the simulator? Then ROS time. Does it only measure duration inside this process? Then steady time. Must it map to a human date? Then system time.

Mechanism

use_sim_time is a per-node boolean parameter, default false. rclcpp::TimeSource, attached by rclcpp::Node, subscribes to /clock when it is true and feeds the node's ROS clock, so node->get_clock()->now() returns the last /clock value rather than the OS clock. Before the first /clock message arrives, ROS time reads 0 and ros_time_is_active() is false: a node that starts before the simulator sees time 0, not a stale wall time.

Gazebo's gazebo_ros plugin publishes /clock at the physics step rate; ros2 bag play --clock republishes the bag's recorded stamps. Both make ROS time follow the source, including its pauses and rate changes.

Timers and rclcpp::Duration waits built from the ROS clock are evaluated against that clock. A forward jump fires a pending timer once, immediately; a backward jump pushes its deadline into the future, so it waits longer than the nominal period. Neither replays missed ticks.

Choosing a clock

NeedClockWhy not the others
Compare with header.stamp, TF, sensor fusionROSSteady has a different epoch; system diverges from sim
Retry backoff, watchdog, rate limitingSteadyROS time freezes when sim pauses; system can step
Log date, cert expiry, external APISystemROS epoch is 0; steady has no calendar meaning

Mixing them is a hard error, not a silent bug: subtracting an RCL_ROS_TIME time from an RCL_STEADY_TIME time throws std::runtime_error ("can't subtract times with different time sources"). That is the guardrail: keep the clock type in the type, not in a comment.

Failure modes

  • Clock jump. A seek or a use_sim_time toggle moves ROS time backward or forward. A tf2_ros::Buffer keyed on ROS time rejects lookups whose stamps fall outside its cache window (default 10 s); a filter that divides by dt spikes or produces NaN when dt is 0 or negative. Watch ros2 topic hz /clock and log now() deltas; re-seed integrators on a jump instead of letting them absorb it.
  • Startup before clock. Node comes up with use_sim_time=true, no /clock yet, ROS time is 0. A wait_for_service or TF lookup with a ROS-time deadline returns instantly or blocks forever. Guard on ros_time_is_active() before using ROS time.
  • Pause. Sim paused, /clock stops. ROS-time timers stop firing; steady-time watchdogs keep running and will declare the node stuck. Decide per timer which you want.
  • Rate change. ros2 bag play --rate 2 doubles /clock deltas. Anything assuming dt ≈ 1/rate breaks; derive dt from the clock, never a constant.
  • Live transition. Flipping use_sim_time at runtime is supported, the parameter callback re-points the clock, but it is a jump. Do it at a known point, reset state, log it.

Code

C++
// rclcpp, ROS 2 (Humble/Iron/Jazzy)
auto ros_clock = node->get_clock();          // RCL_ROS_TIME
rclcpp::Clock steady(RCL_STEADY_TIME);

// Deadline that must survive a sim pause:
auto start = steady.now();
if ((steady.now() - start) > rclcpp::Duration::from_seconds(2.0)) { /* watchdog */ }

// Stamp that must match the rest of the graph:
auto stamp = ros_clock->now();
if (!ros_clock->ros_time_is_active()) {
  RCLCPP_WARN(node->get_logger(), "ROS time not active; /clock not received");
}

Test list: pause, rate change, seek, clock loss, startup before clock, live toggle. Each against the expected behavior above, not just "it works".

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design a correct tf2 lookup and failure policy.

Answer

What a strong candidate says first

Stamp every measurement with the time it was acquired, look up the transform at that exact stamp, and treat each failure as a named condition with its own policy: never fall back to the latest transform. In ROS 2 that means tf2_ros::Buffer::transform(msg, target_frame, timeout), which reads msg.header.stamp and blocks at most timeout for the transform to become available.

Mechanism

tf2 keeps a time-indexed buffer of transforms per edge, default cache_time 10 s (tf2_ros::Buffer(clock, 10s)). A lookup interpolates between the two samples bracketing the requested stamp. Four things can go wrong, and they are distinct exceptions:

  • ConnectivityException: no chain of edges links source and target. Usually a missing static transform or a frame published by a node that is down.
  • ExtrapolationException: the stamp is outside the buffer: older than cache_time (past) or newer than the newest sample (future, e.g. data stamped ahead of the clock or a clock jump).
  • LookupException: the frame id was never seen at all.
  • InvalidArgumentException: NaN or zero stamp, empty frame id.
C++
// ROS 2 Humble, rclcpp + tf2_ros
geometry_msgs::msg::PointStamped toTarget(
    tf2_ros::Buffer & buffer,
    const geometry_msgs::msg::PointStamped & in,
    const std::string & target,
    const rclcpp::Duration & timeout)  // e.g. 50 ms
{
  try {
    return buffer.transform(in, target, timeout);  // uses in.header.stamp
  } catch (const tf2::ExtrapolationException &) {
    throw;  // stamp outside buffer window
  } catch (const tf2::ConnectivityException &) {
    throw;  // no path target <-> in.header.frame_id
  } catch (const tf2::LookupException &) {
    throw;  // frame never published
  }
}

Failure policy table

ExceptionMechanismDetectionPolicy
Connectivityno edge chainthrown at lookupfail fast, page; missing static TF
Extrapolation (past)stamp older than cache_timethrown at lookupdrop, or raise cache_time
Extrapolation (future)stamp ahead of newest samplethrown at lookupdrop; check clock sync
Lookupframe id unknownthrown at lookupfail fast; typo or node down
InvalidArgumentNaN/zero stampthrown at lookupreject at ingress

Trade-off: wait vs reject

The deciding criterion is the consumer's deadline. A control loop with a 10 ms period uses a bounded wait of one period (≤10 ms) and then degrades (hold the last command, reduce speed) because blocking longer misses the deadline anyway. A best-effort consumer (logging, mapping) waits up to the cache horizon and then drops. Never queue unboundedly: a queue that grows past the cache horizon will only ever produce extrapolation failures.

Arithmetic

Default cache_time is 10 s. A pipeline with 200 ms sensor latency plus three 50 ms retries is 350 ms worst case: comfortably inside the window. Replaying an offline log faster than real time shrinks the effective window: at 10× speed, 10 s of buffer covers 1 s of wall clock, so raise cache_time to span the replay.

Two rules that prevent most failures

One publisher authority per dynamic edge: two publishers on the same parent→child edge make the buffer flip-flop and emit TF_REPEATED_DATA / TF_OLD_DATA. And never pass rclcpp::Time(0) (latest) for a timed observation: it silently changes the semantics; reserve it for static transforms.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design an action server for robot motion.

Answer

Assumptions I'd state first: ROS 2 (Humble/Jazzy), rclcpp_action, a 7-DOF arm with a 1 kHz joint controller, feedback at 20 Hz, and one active motion goal at a time. Clients can die mid-motion; the arm can be holding a payload. If any of that is wrong, say a 6-DOF welder with no payload, the preemption policy changes, so I'd confirm it before designing.

The action server is a policy layer over the controller, not the controller itself. Three callbacks carry the design. handle_goal decides accept or reject and must return in microseconds, because it runs on the executor thread: anything slow there stalls every other callback on that executor. handle_cancel decides whether stopping now is safe. handle_accepted hands the goal to the controller and owns the result.

Accept criteria, in order: interlocks (E-stop, mode, safety PLC), frame and stamp freshness, joint position/velocity/acceleration limits, resource availability (is the gripper holding something?), then duplicate and preemption policy. Reject is cheap and correct for anything you can evaluate statically: a goal outside joint limits is a client bug, and accepting it just to abort it wastes a round trip and confuses the operator.

Trade-offs, with the deciding criterion:

ChoiceTake it whenWrong when
Preempt the active goalNew goal is a correction or a stopBatch task: queueing is fine and preemption loses work
Reject at handle_goalFailure is statically detectableInfeasibility only shows mid-trajectory; then accept and abort
Cancel = decelerate to zeroHeavy arm, payload, drive limitsEmergency stop path: that bypasses the action server entirely
Feedback at 20 HzOperator progress displayYou need an audit trail: log to a separate topic instead

Failure modes and how I'd detect them:

  • Stale goal. The goal's header stamp is older than the TF lookup it depends on. Detect by comparing the goal stamp to now; reject past ~100 ms. Without this, the arm chases a pose the world has already left.
  • Uncertain cancellation. Cancel is accepted but the controller is mid-trajectory and cannot stop instantly. The goal stays in CANCELING until joint-state velocity is below threshold; only then does the server return CANCELED. Returning CANCELED early is a lie the client will act on.
  • Client disconnect. rclcpp_action gives you no client-liveness signal, so a dead client leaves the goal running. Put a deadline in the goal or run a heartbeat topic; on expiry, decelerate and abort.
  • Server restart. Goal handles live in memory. After a restart the client's pending goal never gets a result and hangs forever unless the client applies its own timeout on the result future. On boot, refuse to accept goals until the arm is homed.

The accept path, traced:

C++
rclcpp_action::GoalResponse handle_goal(
    const rclcpp_action::GoalUUID & uuid,
    std::shared_ptr<const FollowJointTrajectory::Goal> goal)
{
  if (!interlocks_ok() || !within_limits(*goal))
    return rclcpp_action::GoalResponse::REJECT;
  if (active_goal_ && !goal->allow_preemption)
    return rclcpp_action::GoalResponse::REJECT;
  return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
}

Client sends the goal on the send_goal service → handle_goal returns ACCEPT_AND_EXECUTE → handle_accepted fires with the goal handle → the controller thread starts and publishes feedback on the feedback topic → the result goes back on the get_result service. If handle_goal returns REJECT, handle_accepted never fires and the client gets a rejected goal response immediately.

Set the feedback publisher's depth to 1 if you only need the latest pose: a slow subscriber then sees gaps, which is fine for progress and wrong for audit. Keep the executor free: never block in handle_goal, and never let the controller thread hold a lock the executor needs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design executor placement for sensing, control, and logging.

Answer

Assumptions first. ROS 2 (Humble or later), rclcpp, one machine, control loop 100 Hz–1 kHz, sensors 30–1000 Hz, logging best-effort. If your control loop is soft (10 Hz), the whole placement collapses to one executor and this answer does not apply.

The decision. Three executors, three processes:

  • Control: its own process, one SingleThreadedExecutor on one thread, SCHED_FIFO priority 80, mlockall(MCL_CURRENT|MCL_FUTURE), no allocation in the callback.
  • Sensing: its own process, MultiThreadedExecutor with 2–4 threads, SCHED_FIFO 60 for IMU-class streams, SCHED_OTHER for camera/lidar.
  • Logging: its own process, SingleThreadedExecutor, SCHED_OTHER nice 19, async sink.
StreamRatePeriodExecutorThreadsPriorityCallback group
Control100 Hz–1 kHz10–1 msown process, SingleThreadedExecutor1SCHED_FIFO 80MutuallyExclusive
IMU / joint state200–1000 Hz5–1 mssensing process, MultiThreadedExecutor2–4SCHED_FIFO 60Reentrant
Camera / lidar10–30 Hz100–33 mssame sensing executorSCHED_OTHERReentrant
Loggingevent-drivennoneown process, SingleThreadedExecutor1SCHED_OTHER nice 19MutuallyExclusive

Why this placement. A SingleThreadedExecutor has one spin thread: it waits on the wait set, then runs ready callbacks one at a time. A 50 ms logging callback therefore delays a 1 ms control callback by up to 50 ms: a deadline miss. MultiThreadedExecutor runs N callbacks concurrently (its default thread count follows hardware concurrency), but a MutuallyExclusive callback group, the default, still serializes its members, so putting control and logging in the same group reintroduces the blocking even with 8 threads. Reentrant groups allow concurrency but require thread-safe state, which is why the sensing streams that share a buffer stay in one MutuallyExclusive group instead.

Failure modes and how you detect them.

  1. Head-of-line blocking. Ready-to-start delay for the control callback grows. Detect with tracetools/ros2_tracing, or log now() - msg.header.stamp and watch p99. Cost: a 1 kHz loop missing 1% of deadlines is a controller that oscillates.
  2. Priority inversion. Control thread blocks on a mutex held by the logging thread. Detect by setting PTHREAD_PRIO_INHERIT on the mutex, or replace it with a lock-free SPSC queue. Cost: unbounded latency, not a nice average.
  3. Thread starvation. MultiThreadedExecutor with 4 threads and 5 long callbacks makes the ready queue grow monotonically. Detect: ready-to-start delay trending up over minutes, not spiking.
  4. Timer jitter. create_wall_timer fires late when the executor is busy. Detect: compare expected vs actual fire time; >10% of period is a problem.
  5. Allocation in the callback. std::vector growth or a std::string in a log message causes page faults. Detect: preallocate, then check page-fault counters with perf stat.

Trade-offs. Separate processes give the strongest isolation but lose intra-process zero-copy unless use_intra_process_comms is on, and you pay serialization. Separate executors in one process are cheaper, but std::bad_alloc or a segfault still kills everything. Priorities only help on a PREEMPT_RT kernel with SCHED_FIFO; on a stock kernel they only shift CFS nice. Core pinning (isolcpus) removes scheduler interference but costs a core.

When not to. Don't put everything in one MultiThreadedExecutor with Reentrant groups "to be safe": you get data races and no determinism. If the control loop is soft-real-time, one executor is fine.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Prevent callback-group deadlock.

Answer

Core answer (say this first)

Assume ROS 2 / rclcpp (Humble through Jazzy share this executor model). The rule: a callback must never block waiting for work the executor can only dispatch through the callback group that callback is currently occupying.

MutuallyExclusiveCallbackGroup marks itself busy for the entire duration of a callback. While busy, the executor will not take any other callback from that group, on any thread. So if callback A (group G) blocks on a future whose completion is delivered by callback B (also group G), B can never run, A never returns, and G stays busy forever. With SingleThreadedExecutor the same deadlock happens even across groups, because there is only one thread to run B.

Why it happens

Two independent resources are in play:

  • Executor threads: SingleThreadedExecutor = 1; MultiThreadedExecutor(num_threads=N) = N, and N=0 means std::thread::hardware_concurrency().
  • Group exclusivity: mutually exclusive = at most one callback from the group in flight; reentrant = no such limit.

Deadlock needs both exhausted: the thread is held by A and the group gate is held by A. Adding threads fixes a thread shortage but not the group gate, which is why "just use MultiThreadedExecutor" is the wrong fix for a mutually exclusive group.

Code and trace

C++
// rclcpp, Humble. One node, MultiThreadedExecutor(4).
auto cb_group = node->create_callback_group(
  rclcpp::CallbackGroupType::MutuallyExclusive);

auto client = node->create_client<AddTwoInts>("add_two_ints",
  rmw_qos_profile_services_default, cb_group);   // response callback -> cb_group

auto timer = node->create_wall_timer(1s, [&]() {
  auto future = client->async_send_request(req);
  if (future.wait_for(2s) != std::future_status::ready) {   // blocks here
    RCLCPP_WARN(node->get_logger(), "service call timed out");
  }
}, cb_group);   // timer callback -> same cb_group
  1. t=0: thread T1 takes the timer callback from cb_group; the group is marked busy.
  2. T1 calls async_send_request; the request goes out.
  3. The server replies; the response is queued for the client, whose callback group is cb_group.
  4. T2–T4 poll the executor, see cb_group busy, and skip the client's response callback.
  5. T1 sits in wait_for(2s). The future can only become ready when the response callback runs. It never does.
  6. t=2s: wait_for returns timeout; T1 logs the warning and returns; the group releases. The response callback then runs and sets the future: too late.

Change wait_for(2s) to future.wait() and it is a permanent deadlock: T1 never returns, cb_group never releases, and the node stops answering that service entirely.

Alternatives, and when each is wrong

OptionRight whenWrong when
Async continuation: async_send_request(req, [](future){...})Default for service/action calls made from a callback. Holds no thread and no group while waiting.You need the result to decide the rest of the current callback: restructure into a state machine instead.
Client in a separate group (reentrant, or a second mutually exclusive group)The blocking call is unavoidable and the response path is independent.The server callback shares the same group or the same single thread: you moved the deadlock, not removed it.
ReentrantCallbackGroupCallbacks are genuinely independent and the shared state is locked.Shared state is unlocked: you trade a deadlock for a data race.
More executor threadsThe blocker is thread starvation, not group exclusivity.The group is mutually exclusive: extra threads change nothing.

Decision rule: prefer async continuation; if you must block, the blocking callback and the callback that completes it must be in different groups and a thread must be free to run the second one.

Failure modes and how to detect them

  • Permanent deadlock: node goes silent; ros2 topic hz on its outputs stops, ros2 service call to it times out. Confirm with gdb -p <pid>: the backtrace shows wait_for / spin_until_future_complete inside a callback frame.
  • Timeout livelock: wait_for returns timeout every cycle, so the warning fires at exactly the timer period. Log the future status to see it.
  • Action deadlock: send_goal + async_get_result + a blocking wait in a mutually exclusive group; the result callback is in the same group. Same signature as above.
  • Shutdown hang: a callback blocked in wait_for with no timeout ignores Ctrl-C; the executor's cancel() cannot preempt it, so the process misses the shutdown timeout.
  • Reentrant data race: two callbacks in a ReentrantCallbackGroup touching the same member without a mutex. Detect with TSan (-fsanitize=thread) or valgrind --tool=helgrind.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Choose composition boundaries for a high-bandwidth perception pipeline.

Answer

Assumptions: ROS 2 Humble, rclcpp, Fast DDS, 4K (3840×2160) RGB camera at 30 FPS, 10 GbE, 8-core x86_64, end-to-end p99 budget 50 ms. A raw frame is 3840×2160×3 = 24.9 MB; at 30 FPS that is 746 MB/s, roughly 68% of a 10 GbE link's practical ~1.1 GB/s. You cannot afford to push that frame across a process boundary more than once.

Core answer. Default to one process per stage. Colocate only when profiling shows a specific stage pair burning a meaningful share of a core on serialization or copy, and those two stages already share a crash and trust domain. In ROS 2 the mechanism is composition: build the nodes as rclcpp_components, load them into one container process, and set use_intra_process_comms(true) so messages pass as unique_ptr instead of being serialized.

The trigger is payload size, not stage count. A 24.9 MB memcpy at ~10 GB/s costs ~2.5 ms and, at 30 FPS, ~7.5% of one core. That is worth removing for camera driver → rectification. Detection → tracking carries bounding boxes, a few KB; colocating it saves nothing measurable and costs you crash isolation. So the usual boundary is: colocate the big-payload front of the pipeline, keep the rest separate.

Why loans don't cross processes. rclcpp intra-process comms is a same-process path that bypasses the RMW and DDS entirely. The publisher allocates a message, hands the unique_ptr to the subscriber, and the subscriber's callback owns it: no serialization, no network. The moment the subscriber is in another process that pointer is meaningless; the memory isn't mapped there. Fast DDS's shared-memory transport does avoid the loopback network stack for same-host inter-process traffic, but it still serializes into the shared segment. That is a copy, not a loan. The RMW loan API (rmw_borrow_loaned_message) exists, but middleware support is uneven: don't design around it.

Trade-offs. Colocating removes the copy and the DDS hop and cuts per-message CPU. It also merges crash domains (one segfault takes the container), merges privilege (the camera driver may want RT priority and raw device access; detection doesn't), removes independent restart, and coarsens per-process metrics. If the two stages sit at different trust levels, don't colocate them.

Failure modes.

  • Crash coupling: a segfault in one component kills the container. Detect: exit code 139, ros2 node list loses every node in the container. Cost: whole pipeline down until container restart.
  • Silent fallback to serialization: you colocated but forgot use_intra_process_comms(true) on one node, so you pay the copy and get no benefit. Detect: compare per-node CPU before and after; ros2 topic hz looks identical. Cost: you keep the latency and lose the isolation for nothing.
  • Blocking callback on a single-threaded executor: see the trace below. Detect: ros2 topic hz rate drop, message age in ros2 topic echo. Cost: dropped frames.
  • Leak in one component: container RSS grows until the cgroup OOM killer kills every component. Detect: the oom_kill counter in the container's cgroup memory.events. Cost: all stages die together.

Topology comparison (hypothetical, 4K@30, 8-core):

HopSeparate processesColocatedDelta
driver → rectify2.5 ms serialize + 1 ms rectify0 + 1 ms−2.5 ms, −7.5% core
rectify → detect2.5 ms serialize + 8 ms detectsame0
detect → track~0 (5 KB) + 1 mssame0
p99 total~15 ms~12.5 ms−2.5 ms

Colocating driver+rectification buys 2.5 ms of p99 and ~7.5% of a core. Colocating detect+track buys nothing measurable. That is the whole decision.

The loan path:

C++
// Both nodes in the same container process, both with intra-process enabled.
rclcpp::NodeOptions opts;
opts.use_intra_process_comms(true);

auto pub = node->create_publisher<sensor_msgs::msg::Image>("image", 10);
auto msg = std::make_unique<sensor_msgs::msg::Image>();
// ... fill msg ...
pub->publish(std::move(msg));   // pointer handoff, no serialization

// A subscriber in the same process receives unique_ptr<const Image>.
// If any subscriber is in another process, rclcpp serializes for that one
// and still hands the pointer to the intra-process subscriber.

Executor trace. SingleThreadedExecutor; callback A on /heavy takes 200 ms; callback B on /control runs at 100 Hz and takes 1 ms; subscription queue depth 10 (the rclcpp default).

  • t=0: A starts.
  • t=10…100: ten B messages arrive and fill the queue.
  • t=110…200: ten more arrive, queue full, dropped.
  • t=200: A returns; the executor drains the ten queued B callbacks, 200→210 ms.

Ten of the twenty B messages that arrive during A's 200 ms are dropped, and the survivors are 100–200 ms stale. ros2 topic hz /control reads ~50 Hz instead of 100 Hz. Fix: MultiThreadedExecutor with A and B in separate callback groups, or move A off the executor.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design safe multi-parameter reconfiguration.

Answer

Assumptions I'd state first. A long-running service holds one config object that many worker threads read on every request; reconfiguration arrives through an admin API or a file reload. "Safe" means two things: no reader ever observes a mix of old and new fields, and a rejected change leaves the running config untouched. I'll assume reads outnumber writes by orders of magnitude, say 50k reads/sec against a handful of reconfigs a day, because that ratio is what decides the design.

Core answer. Model the config as an immutable snapshot carrying a version counter. A reconfiguration builds a complete candidate snapshot, validates the whole set, then swaps a single pointer. Readers load the pointer once per request and use that snapshot for the whole request, so they see version N or N+1, never a blend.

Validation runs on the set, not field by field. Cross-field rules (TLS enabled requires a cert path, max_workers >= min_workers, timeout_ms within [10, 60000]) are checked after every field parses, so a change whose fields are individually valid but jointly inconsistent is rejected before anything is published.

Alternatives and when to pick them.

approachmechanismpick whencost
in-place mutation under a lockreaders take a read lockreconfig is rare and readers are fewreaders block; a reader that skips the lock sees a torn read
immutable snapshot + atomic pointer swapbuild candidate, store pointerreads dominate (the 50k:1 case)derived state must be rebuilt on every change
two-phase staged commitstage on each node, commit once all ackthe change spans a fleetcoordinator, timeout, partial-commit handling

The deciding criteria are the read/write ratio, whether derived state is expensive to rebuild, and whether the change spans one process or many. A single-process service with cheap derived state should not pay for a coordinator.

Mechanism and rollback. The swap is one aligned pointer store, which is why readers cannot tear. Rollback is keeping the previous snapshot: if the derived-state rebuild fails, you never swap, so rollback costs nothing. Reverting after a successful swap means swapping the old pointer back: valid only while the old snapshot's derived state is still good, which is why you retain it instead of rebuilding.

Worked trace: two concurrent reconfigs.

Python
# config is an immutable snapshot; version is a monotonic int
def reconfigure(proposed, store):
    cur = store.load()                        # snapshot, version 7
    cand = build_and_validate(proposed, cur)  # raises on any bad field
    if not store.cas(cur.version, cand):      # swap only if still at 7
        raise Conflict
    return cand

Both requests start from version 7. A proposes workers=32, timeout_ms=500; build_and_validate returns candidate version 8; cas(7, cand) succeeds and the store holds version 8. B proposes workers=64, timeout_ms=500, having read version 7 before A committed; its candidate is also version 8; cas(7, cand) fails because the store is at 8. B raises Conflict, reloads version 8, re-validates against it, retries. A reader that loaded version 7 mid-flight finishes on version 7. Net result: A commits 8, B's first attempt mutates nothing, B's retry commits 9.

Failure modes and how you detect them.

  • Torn read: only possible if you mutate in place. Detect by having readers checksum the snapshot, or don't mutate in place.
  • Partial apply: some fields committed, others not. Detect by comparing requested version to committed version in the audit log; they must match.
  • Stale config after restart: the process boots on a config older than the last commit. Detect by persisting the version with the config and refusing to serve when the loaded version is behind the store's.
  • Allocation failure during derived-state rebuild: the new routing table can't be allocated. Detect via the allocation error; keep the old snapshot, return an error, no swap.
  • Concurrent reconfig: CAS conflict, as traced above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Orchestrate lifecycle for sensor, localization, planning, and control nodes.

Answer

What I'd say first

Assume ROS 2 (Humble or Jazzy), each of the four stages is a managed lifecycle node, rclcpp_lifecycle::LifecycleNode, one process per node unless we compose them. The real question is who decides when a node is allowed to touch hardware, and what happens when one dies mid-run.

My answer: build the dependency DAG first, activate in topological order, deactivate in reverse, and put a single lifecycle manager in charge with a bond to every node.

DAG for a typical stack: sensors → localization → planning → control. Control depends on planning's path and localization's TF; planning depends on localization and the map; localization depends on sensors and static TF.

Why reverse order on the way down

on_activate is where a node starts publishing and, for control, where it starts writing to actuators. on_configure must not do that: it allocates, loads params, opens the driver, validates calibration and TF, and returns TransitionCallbackReturn::SUCCESS or FAILURE. Configure can run in almost any order as long as it doesn't assume a peer is up. Activate cannot.

When localization dies, control is still holding a TF from 200 ms ago and happily commanding. So the manager deactivates control first, on_deactivate stops the command publisher, then planning, then localization, then cleanup in the same reverse order. Cleanup releases the driver and the memory; doing it before control stops means control is running against a torn-down map.

Trade-offs

Centralized manager vs. each node watching its own dependencies. Centralized gives one place to enforce order and one bond table, at the cost of a single point of failure, if the manager dies, nothing deactivates. Nav2's lifecycle_manager is the centralized version; bond_timeout defaults to 4.0 s. Distributed avoids the SPOF but you get ordering races and duplicated watchdog logic.

Bond heartbeat vs. topic-age checks. Bond catches process death fast and cheaply. It does not catch a node that's alive and publishing garbage: for that you need a watchdog on the consumer side, e.g. control rejecting a TF older than 100 ms.

Staged activation vs. all-at-once. Staged costs startup time (our budget: 5 s configure, 2 s activate per node) but guarantees control never activates against a map that isn't loaded. All-at-once is faster and wrong for anything that moves.

Fail-fast vs. degraded mode. If a rear camera fails, deactivating the whole stack is safe but stops the robot. If the mission allows it, keep control active and drop to a degraded planner. That's a product decision, not a lifecycle one, but it has to be encoded in the DAG, not discovered at runtime.

Failure modes and how you see them

Partial configure: node 3 returns FAILURE from on_configure. The manager sees success=false on the ChangeState response and must clean up nodes 1 and 2: otherwise you leak drivers and the next configure fails on a busy port.

Activation failure: control activates, localization doesn't. Symptom is a robot that doesn't move or moves on a stale pose. Detect by querying /get_state on all nodes after the batch, not by trusting the manager's own bookkeeping.

Process death: bond heartbeat stops, manager fires at bond_timeout (4 s default). Trace: localization dies at t=0, bond fires at t=4.0, manager deactivates control at t=4.05, cleanup done by t=4.3. For those 4 s control was commanding on a stale pose: at 1 m/s that's 4 m of travel. That's why the consumer-side TF watchdog matters more than the bond.

Flapping: node respawns, manager re-activates, node dies again. Detect by counting respawns in a 60 s window and refusing to re-activate past a threshold; otherwise you get startup churn that looks like a hang.

Stale goals on restart: action servers keep goal handles across a deactivate/activate cycle. Stamp goals with the activation epoch and reject anything older, or clear the goal set in on_activate.

Duplicate effects: transitions get retried after a timeout. Guard the side effect, a "start conveyor" command, with a generation counter so a retried activate doesn't send it twice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design startup readiness beyond ROS graph discovery.

Answer

Assumptions first. ROS 2 (Humble or later), a multi-node bringup where a consumer must not act until its producers are genuinely ready, and "ready" means: the peer exists, is configured, is publishing fresh data of the right type and QoS, and its transforms and interlocks are satisfied. I'll assume we can't change the producers' code, so the gate lives in the consumer or a supervisor.

Why graph discovery is not readiness. DDS discovery is endpoint-level and asynchronous. ros2 node list showing a node, or ros2 topic info -v showing a matching publisher, tells you a participant advertised a reader/writer: nothing about whether the node finished on_configure, loaded calibration, or has produced a single sample. Discovery is also delayed: the Simple Discovery Protocol exchanges participant announcements over multicast, and on a large graph or with ROS_DOMAIN_ID contention a new node can take hundreds of milliseconds to seconds to appear. A consumer that acts on the first graph event races the producer's own initialization.

The gate. Four stages, each with a bounded deadline and a distinct failure reason:

  1. Endpoint match. Wait for the expected node name, namespace and topic type, then check QoS compatibility, not just presence. A RELIABLE subscriber never connects to a BEST_EFFORT publisher: the middleware drops it silently. Compare reliability, durability and deadline from ros2 topic info -v.
  2. Lifecycle active. If the producer is an rclcpp_lifecycle::LifecycleNode, subscribe to /<node>/transition_event (reliable, transient-local) and require the ACTIVE transition. That is the authoritative "configured and activated" signal; graph presence is not.
  3. Fresh data. Require at least one sample whose header stamp is within a threshold tied to the rate: 3× the period, e.g. 300 ms for a 10 Hz sensor. A discovered-but-silent publisher fails here.
  4. Transforms and interlocks. tf2_ros::Buffer::canTransform(target, source, stamp, timeout) for each required frame, plus any security or interlock prerequisite (e-stop, mode parameter) before the consumer moves.
C++
// ROS 2 Humble, rclcpp — freshness gate for a 10 Hz sensor
const auto max_age = rclcpp::Duration::from_seconds(0.3); // 3 periods
if ((node->now() - rclcpp::Time(msg->header.stamp)) > max_age) {
  return Readiness::Stale; // reason: "lidar stale by 340 ms"
}
stagedeadlinefailure reason surfaced
endpoint match5 s"no RELIABLE publisher on /scan"
lifecycle ACTIVE10 s"controller stuck in INACTIVE"
fresh sample0.3 s"lidar stale by 340 ms"
transform0.5 s"no map->base_link at t"

Trade-offs. Event-driven (graph guard condition plus lifecycle callbacks) is lowest-latency and deterministic but more code. Polling wait_for_graph_change with a bounded deadline is simpler and fine when the bringup is a handful of nodes. A fixed sleep is the worst option: it either wastes time or fails intermittently under load, and it hides which dependency was late. Use a fixed sleep only for a single-process, known-ordering bringup where nothing downstream depends on data freshness.

Failure modes and detection. Delayed discovery → gate times out with "endpoint not found". Discovered-but-unconfigured peer → lifecycle never reaches ACTIVE. Stale publisher → freshness check fails. Wrong type or QoS → no match, reported as incompatible QoS. Duplicate authority (two publishers on a command topic) → count publishers, fail if >1. Partition → no discovery at all. Recovery → re-evaluate continuously, not once.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design graceful and forced shutdown for a robot process.

Answer

Assume a ROS 2 (rclcpp) process on a mobile base or arm, with a safety-critical stop. The core answer: on SIGTERM or shutdown request, stop accepting new goals, cancel active goals, command a safe output through an independent path, quiesce timers and subscriptions, drain only work that is still fresh, stop executors, join threads, flush crash-safe evidence, and release devices in dependency order. Use a deadline (e.g., 3 s) and escalate to forced containment (SIGKILL or hardware e-stop) if any step hangs.

Graceful versus forced is the central trade-off. Choose the deadline from robot dynamics: a base at 1 m/s with 0.5 m/s² deceleration stops in 2 s, so a 3 s deadline gives margin. For a manipulator holding a payload, the deadline may be 500 ms. Forcing costs uncontrolled motion, hardware damage, data loss, and manual recovery. Do not force if the robot is already stationary and holding a brake: forcing may drop the brake and cause a fall. Force when a callback or peer is unresponsive past the deadline, or when a second SIGTERM arrives within 1 s.

AspectGracefulForced
Deadline3 s (example)immediate after deadline
MechanismSIGTERM, cancel goals, safe output, joinSIGKILL, hardware e-stop
Costtime, may miss deadlineuncontrolled motion, data loss
Whennormal shutdown, safe state reachablecallback hang, peer unresponsive

A concrete trace for a 3 s deadline:

  • t=0 ms: SIGTERM received. Signal handler sets an atomic flag.
  • t=1 ms: Main loop sees flag. Action server stops accepting new goals (cancel_all_goals).
  • t=2 ms: Active goal handles receive cancel request. Wait for acknowledgment with 500 ms timeout.
  • t=10 ms: Safety thread commands zero velocity via an independent CAN bus.
  • t=15 ms: Verify safe output: read back encoder velocity < 0.01 m/s.
  • t=20 ms: Quiesce timers: cancel all timers. Subscriptions: stop callbacks.
  • t=25 ms: Drain fresh work: executor.spin_some() until queue empty or 100 ms.
  • t=130 ms: Stop executor: executor.cancel(). Join safety thread.
  • t=150 ms: Flush evidence: write last state to /var/log/robot/state.json, fsync.
  • t=160 ms: Release devices: close sensor and actuator file descriptors.
  • t=170 ms: rclcpp::shutdown(). Process exits.

If any step exceeds 3000 ms, escalate to forced: SIGKILL or hardware e-stop.

Failure modes and detection:

  • Blocked callback: watchdog timer expects a heartbeat every 100 ms. Missed heartbeat logs and escalates to forced. Cost: robot may continue moving, so forced stop is required.
  • Network loss: heartbeat timeout of 500 ms. Cost: lose telemetry, need local safe stop.
  • Repeated signals: signal handler counts. Second SIGTERM within 1 s escalates to forced. Cost: immediate stop, possible data loss.
  • Use-after-free: detect via ASAN or crash. Prevent by ordering: cancel goals, wait for callbacks to finish (e.g., executor work queue or barrier), then destroy publishers. Cost: undefined behavior, so prevention is mandatory.
  • Late futures: check future status after cancellation. If still pending, wait or abandon. Destroying the future's associated resources while a callback still runs causes a crash.

The independent path matters because the main control loop may be blocked by a callback or deadlock; a separate safety thread can still command zero velocity. Late futures arise when a cancel request is sent but the callback is already executing and publishes after you destroyed the publisher. The key decision point: if safe output is verified before the deadline, skip forced containment; otherwise, force immediately and log the reason.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design names and remaps for a multi-robot deployment.

Answer

Assumptions first. N robots run the same stack, one DDS domain, one shared map service, no per-robot code forks. If any of those is false the answer changes: see trade-offs.

Core answer. One namespace per robot, relative names in source, remap only at launch, shared services absolute and deliberate.

Name resolution is the whole mechanism. ROS 2 resolves a name against the node's namespace and node name:

name in codenoderesolves to
cmd_vel (relative)/robot1/lidar/robot1/cmd_vel
~rate (private)/robot1/lidar/robot1/lidar/rate
/cmd_vel (absolute)/robot1/lidar/cmd_vel

So cmd_vel written in source is safe; /cmd_vel is a bug in a multi-robot deployment, because it escapes the namespace and every robot publishes to the same topic.

Remap at launch, not in code:

Shell
ros2 run my_pkg lidar_node --ros-args -r __ns:=/robot1 -r __node:=lidar

__ns sets the namespace, __node the node name. In launch:

Python
GroupAction([
    PushRosNamespace('robot1'),
    Node(package='my_pkg', executable='lidar_node', name='lidar'),
])

Remap rules also take wildcards: -r /**:=/robot1/** rewrites every absolute name under the namespace; * matches one token, ** matches across separators. Use it to catch absolute names you cannot edit, but prefer fixing the source.

Validation. Check the resolved graph, not the intent:

Shell
ros2 node list | sort | uniq -d          # duplicate node names
ros2 topic info /robot1/scan -v          # publisher count + QoS

ros2 topic info -v prints publisher/subscriber counts and each endpoint's QoS. Expect exactly one publisher per robot topic. A plain topic defaults to RELIABLE, VOLATILE, KEEP_LAST depth 10; sensor streams usually use SensorDataQoS (BEST_EFFORT, KEEP_LAST depth 5). A BEST_EFFORT publisher and a RELIABLE subscriber are incompatible and never connect: no error at publish time, so the only detection is the zero matched count in -v or ros2 doctor.

TF: prefix frames per robot with robot_state_publisher's frame_prefix parameter (robot1/base_link). Two robots publishing an unprefixed base_link give the tree duplicate children, and lookups return whichever arrived last.

Trade-offs. Namespace keeps one graph, so a shared map or fleet topic is just an absolute name: cheap. Separate ROS_DOMAIN_ID per robot gives hard isolation and less discovery traffic but severs cross-robot topics and needs a bridge; pick it when robots must not see each other at all. Namespace is not access control: any node in the domain can publish to /robot1/cmd_vel. Authorization and encryption are SROS2 (DDS Security) with per-node permissions: do not treat a namespace as a boundary.

Failure modes and detection.

  • Absolute name in source → two publishers on /cmd_vel; ros2 topic info /cmd_vel -v shows 2.
  • Duplicate node name → ROS 2 permits it; ros2 node list | sort | uniq -d shows it, and remap rules then hit both nodes.
  • QoS mismatch → zero matched endpoints, silent.
  • TF collision → ros2 run tf2_tools view_frames shows duplicate child frames.
  • Discovery delay → nodes appear seconds after launch; validate after the graph settles, not immediately.

Test with two robots, one node using an absolute name, a wildcard remap, a duplicate node name, a wrong remap, and a partial launch.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Evolve a ROS message contract safely.

Answer

Assume ROS 2 Iron or later, and a message my_robot_msgs/msg/Odometry with float64 x, float64 y, float64 theta, consumed by three teams. You need to add a float64[9] covariance field.

Classify the change before you touch the file. Additive (a new field appended at the end, or a new constant) can be done in place if the message is @appendable. Breaking (renaming a field, changing its type, or changing its units or meaning) needs a new message type and a new topic, run in parallel with a bridge. The trap is that type compatibility is not semantic compatibility: changing theta from radians to degrees leaves the type identical, so the connection succeeds and every consumer silently gets wrong values.

Mechanism. ROS 2 computes a type hash from the message definition and uses it to decide whether two endpoints can talk. The default extensibility is final: the definitions must match exactly, so adding a field to a final message changes the hash and the endpoints do not connect. That failure is silent: no error, no data. Iron (2023) added @appendable and @mutable. Marking the message @appendable lets you append fields at the end; DDS type consistency then permits an old publisher and a new subscriber to match, with the new field taking its default on the old side. A semantic change is the dangerous case: the type hash is unchanged, the connection succeeds, and the values are wrong.

Trade-offs. In ROS 2 a topic has exactly one type, so a new type means a new topic. Run both topics in parallel during the transition and bridge with a converter node, documenting what the converter loses: a v1 consumer cannot see covariance, so it must treat it as unknown. Don't reach for @appendable when the new field is required to interpret the message correctly; that is a semantic break, and it needs a new type.

Failure modes.

  • Adding a field to a final message. The type hash changes; old and new nodes silently do not connect. Detection: a watchdog on the subscriber's expected message rate fires. Cost: silent data loss until someone notices.
  • Semantic break, units change, type unchanged. The hash is identical, so the connection succeeds and values are wrong. Detection: range checks (theta outside [-π, π]) and a cross-check against a second sensor. Cost: the robot misbehaves.
  • QoS mismatch. A BEST_EFFORT publisher and a RELIABLE subscriber are incompatible and no data flows; the reverse (RELIABLE publisher, BEST_EFFORT subscriber) is fine. Detection: ros2 topic info -v shows each endpoint's QoS profile. Cost: no data.

Artefacts.

The .msg change:

# my_robot_msgs/msg/Odometry.msg
@appendable
float64 x
float64 y
float64 theta
float64[9] covariance   # appended in v2; all-zero on v1 publishers

All-zero covariance is the ROS convention for "unknown," which is exactly what a v1 publisher means, so the default is semantically valid.

Change classification:

ChangeType hashSafe in place?Action
Append field at end, @appendablediffersyesmark @appendable, give a default
Append field at end, finaldiffersnomark @appendable, or new type
Rename a fielddiffersnonew type + new topic
Change a field's typediffersnonew type + new topic
Change units or meaning, same typeidenticalnonew field or new type

Trace: adding a field to a final message.

  • Publisher runs v1: Odometry with x, y, theta. Type hash H1.
  • Subscriber runs v2: Odometry with x, y, theta, covariance. Type hash H2, H2 ≠ H1.
  • At discovery ROS 2 compares H1 and H2. They differ, so the endpoints do not match. The subscription is created without error and no message is delivered.
  • Observable: ros2 topic info -v /odom shows the publisher and the subscription, but the subscriber's callback never fires and no error appears in either node's log.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Instrument ROS callback and graph performance.

Answer

Core answer (first 90 seconds)

Assume ROS 2 Humble or later, rclcpp, the default RMW (Fast DDS), and a concrete question: "the 1 kHz control callback misses its 10 ms budget. Why?" Instrumentation only earns its cost if it answers a specific latency question, so I'd write the budget down first, sensor → DDS → executor → callback → publish, and instrument the boundaries, not everything.

The default tool is ros2_tracing. tracetools compiles LTTng-UST tracepoints into rcl/rclcpp/rmw, and ros2 trace -s <session> records them; babeltrace converts the CTF trace to text and tracetools_analysis aggregates it. The tracepoints that carry the answer:

symptomtracepoints
callback queued behind othersros2:rclcpp_executor_get_next_ready → ros2:callback_start
executor idleros2:rclcpp_executor_wait_for_work
callback runtimeros2:callback_start → ros2:callback_end
DDS take / publish costros2:rmw_take, ros2:rclcpp_publish → ros2:rmw_publish

callback_start/callback_end carry a callback pointer that rclcpp_callback_register maps to a symbol, so you get per-callback identity, not totals.

Why executor contention shows up as ready-to-start latency

The executor blocks in wait_for_work on the wait set. When a subscription becomes ready the wait set returns, get_next_ready_executable collects ready entities, and the executor either runs the callback inline (single-threaded) or hands it to a worker thread. The gap between "sample ready" and callback_start is queueing delay. MultiThreadedExecutor defaults to hardware_concurrency() threads, but a long callback in a MutuallyExclusive group blocks every other callback in that group; a Reentrant group lets them overlap. So the trace shows either a long callback_start→end or a long ready→start on a different callback: that distinction is the diagnosis.

Why queue age reveals backpressure

A KEEP_LAST subscription of depth N holds at most N samples. If the consumer is slower than the publisher the queue stays full and every take returns an already-old sample; age grows with the deficit. When age grows then snaps back, you're seeing overwrite drops: the sequence numbers jump. ros2 topic delay gives you age without tracing.

Worked trace (hypothetical: 1 kHz publisher, KEEP_LAST depth 10, callback normally 3 ms)

  • t=100.000 ms: a 40 ms service callback in the same MutuallyExclusive group starts; the subscription callback cannot run.
  • Samples #200–#240 arrive during those 40 ms. The depth-10 queue keeps only #231–#240; #200–#230 are overwritten.
  • t=140.000 ms: callback_start: ready→start = 40 ms. Executor contention, not DDS.
  • take returns #231, header stamp 131.000 ms → 9 ms stale at take. Backpressure.
  • t=143.000 ms: callback_end. The next take returns #241, stamp 141.000 ms; the sequence gap #231→#241 is the 9 samples dropped while the callback ran.

One trace, three distinct signals: 40 ms ready→start, 9 ms queue age, a sequence gap.

Trade-offs

approachgives youcosts
ros2_tracing + LTTngfull causal chain, per-callback identityevent volume → disk and analysis; needs babeltrace/tracetools_analysis
ros2 topic hz/delay/bwend-to-end rate and age, zero setupno callback identity, no executor view
perf recordCPU attribution on any binaryno ROS semantics: you see epoll_wait, not "callback X"
hand-rolled timestampscheapest to readyou own clock, aggregation and overhead; can't see inside the executor

Pick by question: "which callback and why" → ros2_tracing; "is the topic flowing" → ros2 topic hz; "is the CPU saturated" → perf.

Failure modes and how to detect them

  • Trace loss: LTTng discards events when per-CPU sub-buffers fill. Check the session's discarded-event count first; a missing callback_end is the tell.
  • Probe overhead: enabling tracing on a 1 kHz callback adds per-event cost. Measure with tracing on and off before believing a regression.
  • QoS incompatibility: BEST_EFFORT publisher + RELIABLE subscriber never match. No data, no callback, no error. Detect with ros2 topic info -v (endpoint counts) and the incompatible-QoS callback.
  • Deadline/liveliness: deadline QoS fires the subscription's deadline-missed callback when the gap exceeds the period; liveliness lease expiry fires when a publisher stops asserting. Both are graph-level and invisible in callback traces.
  • TF: lookupTransform returns after its timeout; tf2_ros::Buffer caches 10 s by default, so an old transform means extrapolation. Detect with tf2_monitor / view_frames.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Build deterministic ROS 2 integration tests in CI.

Answer

Core answer (first 90 seconds). Determinism means the same pass/fail on every run, independent of machine load and network timing. Three levers: isolate the graph, control the clock, wait on events instead of sleeping.

Isolate. Give each CI job its own ROS_DOMAIN_ID (valid 0–232, default 0; stay ≤101 with default Fast DDS port settings) and put every node under test in a per-test namespace. Pin RMW_IMPLEMENTATION (e.g. rmw_cyclonedds_cpp) so discovery behaviour doesn't change between runs. On Humble set ROS_LOCALHOST_ONLY=1; on Jazzy set ROS_AUTOMATIC_DISCOVERY_RANGE=LOCALHOST: both stop discovery leaking to other machines on the subnet.

Control the clock. Launch nodes with use_sim_time:=true (default false) and publish rosgraph_msgs/msg/Clock on /clock from the test, stepping it explicitly. Timers then fire on simulated time, so a 100 ms timer is exactly 100 ms of test time regardless of CI load. Trap: use_sim_time:=true with no /clock publisher leaves the node's clock at 0 and its timers never fire.

Wait on events. launch_testing.actions.ReadyToTest() gates the test process on the launch description; then use Client.wait_for_service(timeout_sec=...), Client.service_is_ready(), or rclpy.spin_until_future_complete(node, future, timeout_sec=...). Never time.sleep.

I'll assume Humble or Jazzy, rmw_fastrtps_cpp default, no hardware, one test per CI job.

Python
# test/test_my_node.py — run with: launch_test test/test_my_node.py
import unittest, launch, launch_ros.actions, launch_testing
import launch_testing.actions, launch_testing.asserts, pytest, rclpy
from rclpy.node import Node
from std_srvs.srv import Empty

@pytest.mark.launch_test
def generate_test_description():
    node_under_test = launch_ros.actions.Node(
        package='my_pkg', executable='my_node', name='my_node',
        namespace='t42', output='screen',
        parameters=[{'use_sim_time': False}],
    )
    return launch.LaunchDescription([
        node_under_test,
        launch_testing.actions.ReadyToTest(),
    ]), {'node_under_test': node_under_test}

class TestMyNode(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        rclpy.init()
        cls.node = Node('test_node')

    @classmethod
    def tearDownClass(cls):
        cls.node.destroy_node()
        rclpy.shutdown()

    def test_service_responds(self):
        client = self.node.create_client(Empty, '/t42/my_service')
        self.assertTrue(client.wait_for_service(timeout_sec=10.0),
                        'service /t42/my_service never appeared')
        future = client.call_async(Empty.Request())
        rclpy.spin_until_future_complete(self.node, future, timeout_sec=10.0)
        self.assertTrue(future.done(), 'no response within 10 s')
        self.assertIsNone(future.exception())

@launch_testing.post_shutdown_test()
class TestShutdown(unittest.TestCase):
    def test_exit_code(self, proc_info):
        launch_testing.asserts.assertExitCodes(proc_info, allowable_exit_codes=[0])

Trace, passing run. ReadyToTest() fires once my_node is up. setUpClass runs rclpy.init() and creates test_node. create_client returns immediately; wait_for_service(timeout_sec=10.0) polls discovery and returns True at t≈1.2 s. call_async sends the request; spin_until_future_complete(..., timeout_sec=10.0) returns at t≈1.23 s with future.done() == True and future.exception() is None. Both asserts pass.

Trace, failing run. The node is blocked in a callback. wait_for_service still returns True at t≈1.2 s: the service is advertised before the executor stalls. call_async sends; spin_until_future_complete spins the full 10 s and returns with future.done() == False. The assert fails with no response within 10 s, so the CI log separates "never appeared" from "never answered".

QoS defaults that decide whether a wait ever completes:

ProfileValuesUsed for
qos_profile_services_defaultRELIABLE, VOLATILE, KEEP_LAST 10services, actions
qos_profile_sensor_dataBEST_EFFORT, VOLATILE, KEEP_LAST 5lidar, camera
qos_profile_system_defaultRELIABLE, VOLATILE, KEEP_LAST 10topics, parameters
/tf_staticRELIABLE, TRANSIENT_LOCAL, KEEP_LAST 100late joiners

Alternatives. Mock nodes are faster and less flaky but miss middleware and QoS bugs: keep them for unit tests, real binaries for integration. Wall clock catches real-time performance regressions but is flaky in CI; use simulated time for functional tests, wall clock only for performance tests. Fast DDS is the default and best-tested; Cyclone DDS has different discovery and can be steadier under load: test with the RMW you ship.

Failure modes and detection. Service never appears: wait_for_service returns False after 10 s. Check ros2 node list and ros2 service list -t; a missing node means a launch or crash bug. Service appears but never answers: future.done() == False. Run ros2 service call /t42/my_service std_srvs/srv/Empty by hand; if that returns, the test client's QoS is incompatible (a BEST_EFFORT client never matches a RELIABLE service). Topic message lost: compare ros2 topic hz /topic against the expected rate and read ros2 topic info /topic -v; a RELIABLE subscriber on a BEST_EFFORT publisher never matches. Sim-time hang: ros2 param get /my_node use_sim_time returns true while ros2 topic hz /clock shows nothing. Teardown leak: ros2 node list must be empty on that domain after shutdown.

Run colcon test --packages-select my_pkg --retest-until-fail 10: ten consecutive passes is the actual determinism check, and colcon test-result --verbose shows which run failed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Review and validate a ROS 2 robot release end to end.

Answer

What I'd say first

Assume ROS 2 Jazzy on Ubuntu 24.04, default RMW rmw_fastrtps_cpp, one robot, one DDS domain. "Validate a release" means: freeze an exact artifact set, then prove the running graph meets stated numeric contracts under the conditions the robot will actually meet, and have a gate that fails the release when it doesn't. A green build plus one ros2 topic echo proves nothing.

Freeze first. Record the git SHA of every package, ros2 param dump for every node, the RMW and its version, the SROS2 keystore, the map, and the calibration file. If any of those can change between the test run and the field, the result isn't about the release.

Then check the four things that actually break a robot.

QoS compatibility. A subscriber can only be weaker than its publisher, never stronger. Reliable publisher + best-effort subscriber connects; best-effort publisher + reliable subscriber silently never connects: no error, just an empty topic. Same rule for durability.

PublisherSubscriberConnects?
reliablebest effortyes
best effortreliableno
transient localvolatileyes
volatiletransient localno

Defaults matter: rclcpp::SystemDefaultsQoS() is reliable, volatile, keep-last 10; SensorDataQoS() is best-effort, keep-last 5. /tf_static, /map and /robot_description must be transient-local or late joiners get nothing. Check every pair with ros2 topic info -v, which prints both endpoints' QoS and whether they matched.

Time and frames. Every node runs with use_sim_time set consistently; replay with ros2 bag play --clock. tf2's buffer defaults to a 10 s cache: a lookup older than that throws. Run ros2 run tf2_tools view_frames and confirm one root, no orphan frames.

Concurrency. Callback groups decide what runs in parallel. A 200 ms callback in a MutuallyExclusive group blocks every other callback in that group. Worked trace: a 30 Hz camera (33 ms period) on SensorDataQoS (keep-last 5) holds 5 × 33 ms ≈ 167 ms of buffer. If the perception callback takes 200 ms, the queue overflows every cycle and frames drop: ros2 topic hz shows the publisher at 30 Hz while the subscriber's own counter shows ~5 Hz. That gap is the symptom; the fix is a Reentrant group plus a MultiThreadedExecutor with an explicit thread count, or a shorter callback.

Lifecycle and security. Drive nodes unconfigured → inactive → active and back; a deactivate that leaves a publisher alive is a bug. With SROS2, run the graph against the keystore and confirm an unauthorized node is rejected, not merely warned.

Trade-offs that decide the plan. Bag replay is deterministic and cheap but only exercises the graph you recorded; HIL is the only place a physical stop is real. So replay for regression, HIL for the safety gate. Best-effort QoS buys throughput and drops under load; reliable buys delivery and can back-pressure a publisher into missing its own deadline. Pick per topic, not per robot.

Gate. Release only if: no QoS mismatch, no missed deadline (set deadline QoS and count on_requested_deadline_missed), all tf lookups resolve, action goals reach a terminal state, and the HIL run ends in a physical stop that recovers. Canary on one robot for a shift before fleet rollout; rollback is the frozen SHA set, so it must redeploy without a rebuild.

Curated: · Written: · Reviewed:

Difficulty: Hard