New

Introducing Free Tier: Get Started with Cedalo MQTT Platform |Get Started

Back to Blog

MQTT Request Response Pattern with MQTT 5.0 and Python Code

Vitalii Tutevych
Vitalii Tutevych Published November 30, 2026 16 min read
MQTT basics
MQTT Request Response Pattern with MQTT 5.0 and Python Code

MQTT request response is a messaging pattern in which a client publishes a request and receives a targeted answer from another client on a separate topic. MQTT 5.0 defines two properties for it, Response Topic and Correlation Data, which put the reply path into the protocol itself.

MQTT Request Response: Key Takeaways

  • MQTT 5.0 request response uses Response Topic and Correlation Data to name the reply topic and to link each answer to its request.
  • The MQTT request response pattern is asynchronous, so one requester keeps many requests open and matches each reply by its Correlation Data.
  • Secure MQTT response topics with one ACL-protected reply branch per client and a responder that rejects Response Topics outside the reply/ tree.
  • Pro Mosquitto from Cedalo, the company behind Eclipse Mosquitto, adds central administration of reply-branch permissions across several brokers.

What Does Request Response Mean in MQTT?

In MQTT, request response adds a return channel to publish/subscribe. The requester names a reply topic with its message and a second client publishes the result of the triggered action there. The broker treats both as ordinary publications, so the clients themselves link each response to its request.

The reason lies in the pub sub model. Publishers and subscribers only share topics. A sensor publishing to a topic never learns who reads it, so any answer requires a second channel that both sides agree on.

Typical use cases for the MQTT request response pattern:

  • Device commands with confirmation: A control system tells a filling machine to switch recipes and waits for the machine’s status code.
  • Configuration queries: A service asks a gateway for its firmware version or polling interval.
  • Status requests: A dashboard asks one PLC for its counter values right now instead of waiting for the next publishing cycle.
  • Service calls: One backend service asks another to look up or compute data, comparable to a remote procedure call.

Telemetry stays pure publish/subscribe. A temperature sensor that reports every five seconds needs no answer from its consumers. A reply channel would only add traffic there.

How Does MQTT 5.0 Request Response Compare to HTTP and MQTT 3.1.1 Workarounds?

MQTT 5.0 request response runs asynchronously over a persistent connection and carries the reply path as protocol metadata. HTTP blocks the caller until the server answers on the same connection. MQTT 3.1.1 has no reply properties, so teams encode the reply path in topic names or payloads.

CriterionMQTT 5.0 request responseHTTP request responseMQTT 3.1.1 workaround
SynchronyAsynchronous, requester keeps workingSynchronous, caller waits per requestAsynchronous
Matching request and replyCorrelation Data propertyImplicit through the open connectionRequest ID inside the payload
Reply pathResponse Topic propertySame TCP connectionTopic convention agreed in advance
Protocol overheadFixed header from 2 bytes plus propertiesText headers, often several hundred bytesFixed header from 2 bytes plus payload fields
Connection modelOne persistent connection for all trafficPersistent by default since HTTP/1.1, one request-response cycle per callOne persistent connection
Unreliable networksQoS 1/2, persistent sessions, message expiryClient repeats the full requestQoS 1/2, persistent sessions
IIoT fitDevices behind NAT receive commands over their outgoing connectionDevice needs a reachable endpoint for incoming callsWorks if every party knows the convention

How Did Teams Build Request Response before MQTT 5.0?

Before MQTT 5.0, teams built the pattern on two conventions:

  • Client ID in the topic path: The requester added its ID to the reply topic, for example devices/press-07/cmd/reply/client-42.
  • Request ID in the payload: A JSON field linked each answer to its request.

Every responder had to parse that payload format. One team using a different field name was enough to break the flow.

MQTT 5.0 moves both pieces into the packet header. A responder reads Response Topic and Correlation Data from the properties and knows where to reply before it opens the payload.

When Does an MQTT REST API Still Make Sense?

An MQTT REST API is a gateway that translates HTTP calls into MQTT requests. It pays off for bulk queries on historical data and for partners who only speak HTTP.

Outside request response, the choice of MQTT vs HTTP depends on connection model, payload size and whether devices receive pushed data.

Which MQTT 5.0 Properties Make Request Response Possible?

Two MQTT 5.0 properties carry the pattern. Response Topic names the topic for the answer and Correlation Data links the answer to its request. Content Type, Payload Format Indicator and User Properties describe the payload.

How Do You Set the Response Topic in an MQTT 5.0 Request?

The requester sets the Response Topic as a property of the PUBLISH packet. The responder reads the value from the incoming message and publishes its answer to exactly that topic. According to the MQTT 5.0 specification, the broker forwards the property unchanged to every subscriber.

Three schemas for reply topics are in use:

  1. Per client ID (reply/<client-id>): One ACL pattern secures it. The requester subscribes once at startup.
  2. Per session (reply/<client-id>/<session-id>): With Clean Start, a restarted client does not receive late answers meant for its previous session. The price is a new subscription after every reconnect.
  3. Per request (reply/<client-id>/<request-id>): The topic name itself identifies the request. The price is one SUBSCRIBE and UNSUBSCRIBE per request.

A Response Topic must not contain the wildcards + or #. A compliant broker treats such a PUBLISH as a protocol error and closes the connection.

If the broker supports it, a client sets Request Response Information to 1 in CONNECT and receives a reply prefix as Response Information in CONNACK. Operators then assign reply branches from the broker side.

How Does Correlation Data Match a Response to Its Request?

Correlation Data is a binary property that the requester attaches to the request and the responder copies unchanged into its answer. The broker forwards the bytes without interpreting them, so the application decides what goes in.

The requester keeps a table of open requests keyed by Correlation Data. For each incoming answer it looks up the key, hands the result to the waiting task and deletes the entry. One unique value per request keeps the matching unambiguous.

Which Supporting Properties Help the Responder Parse a Request?

Content Type carries a MIME string such as application/json or application/x-protobuf. The responder picks the right parser from it before it touches the payload. Payload Format Indicator set to 1 marks the payload as UTF-8 text, which the receiver may validate.

User Properties are key-value pairs for metadata. Order numbers, tenant IDs or the name of the calling service travel there and keep routing data out of the payload.

What Does the MQTT Request Response Flow Look Like Step by Step?

A complete MQTT request response flow runs through six steps. It starts with the subscription to the reply topic and ends with the requester deleting the matched request from its table.

  1. The requester connects with MQTT 5.0, subscribes to reply/scada-01 and waits for the SUBACK.
  2. The responder subscribes to its command topic, for example factory/line-2/press-07/cmd.
  3. The requester publishes the command with Response Topic reply/scada-01, a fresh Correlation Data value and Content Type application/json. It stores the request in its table.
  4. The broker forwards the PUBLISH with all properties to the responder.
  5. The responder runs the command and publishes the result to reply/scada-01 with the same Correlation Data.
  6. The requester receives the answer, finds the open request by its Correlation Data and deletes the entry.
Sequence diagram of an MQTT 5.0 request and response between requester scada-01, the broker, and responder press-07
Figure 1: The requester subscribes to its reply topic first. Response Topic and Correlation Data travel as properties and come back unchanged.

Step 1 has to finish before step 3 starts. If the order flips and the responder answers within milliseconds, the broker finds no subscriber on the reply topic and drops the answer. For a topic without a matching subscription, the broker only keeps the latest message that carries the retain flag.

QoS 1 fits most commands and replies. It delivers at least once, so after a reconnect a responder occasionally receives the same request twice. Commands with side effects, like starting a motor, need a check against recently processed Correlation Data values. The MQTT QoS levels differ in exactly this delivery guarantee.

How Do You Build an MQTT Request Response Example in Python?

The MQTT request response example below uses Paho MQTT 2.x for Python with MQTT 5.0. It shows the code that handles Response Topic and Correlation Data on both sides. Connection setup, TLS and reconnect handling follow the standard client configuration for Paho MQTT.

How Do You Write the Requester with Paho MQTT?

The requester subscribes to its response topic, sends each request with its own Correlation Data and waits for the matching answer or a timeout.

import json
import threading
import uuid

import paho.mqtt.client as mqtt
from paho.mqtt.packettypes import PacketTypes
from paho.mqtt.properties import Properties

CLIENT_ID = "scada-01"
REPLY_TOPIC = f"reply/{CLIENT_ID}"

pending = {}  # correlation bytes -> {"event": Event, "result": ...}
lock = threading.Lock()
subscribed = threading.Event()

def on_connect(client, userdata, flags, reason_code, properties):
    client.subscribe(REPLY_TOPIC, qos=1)

def on_subscribe(client, userdata, mid, reason_codes, properties):
    if reason_codes[0].is_failure:
        print(f"Subscription to {REPLY_TOPIC} rejected: {reason_codes[0]}")
        return
    subscribed.set()

def on_message(client, userdata, msg):
    corr = getattr(msg.properties, "CorrelationData", None)
    with lock:
        entry = pending.get(corr)
    if entry is None:
        print(f"Unknown or late reply on {msg.topic}")
        return
    entry["result"] = json.loads(msg.payload)
    entry["event"].set()

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,
                     client_id=CLIENT_ID, protocol=mqtt.MQTTv5)
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect("broker.example.com", 1883)  # use 8883 with TLS in production
client.loop_start()

if not subscribed.wait(5):  # reply topic must be active first
    raise SystemExit(f"No active subscription on {REPLY_TOPIC}, check the ACL")

def request(topic, payload, timeout=5.0):
    corr = uuid.uuid4().bytes
    entry = {"event": threading.Event(), "result": None}
    with lock:
        pending[corr] = entry
    props = Properties(PacketTypes.PUBLISH)
    props.ResponseTopic = REPLY_TOPIC
    props.CorrelationData = corr
    props.ContentType = "application/json"
    client.publish(topic, json.dumps(payload), qos=1, properties=props)
    try:
        if not entry["event"].wait(timeout):
            raise TimeoutError(f"No reply on {topic} within {timeout}s")
        return entry["result"]
    finally:
        with lock:
            pending.pop(corr, None)

print(request("factory/line-2/press-07/cmd", {"action": "set_recipe", "recipe": "R-114"}))

The finally block deletes the entry in both cases, after an answer and after a timeout. Without it, the table grows with every lost reply. An answer that arrives after its timeout finds no entry and ends up in the log as an unknown reply.

How Do You Write the Responder with Paho MQTT?

The responder reads both properties from the request, validates the target topic and answers with the same Correlation Data.

import json

import paho.mqtt.client as mqtt
from paho.mqtt.packettypes import PacketTypes
from paho.mqtt.properties import Properties

CMD_TOPIC = "factory/line-2/press-07/cmd"
ALLOWED_PREFIX = "reply/"
MAX_TOPIC_LEN = 128

def handle(command):
    # device logic goes here
    return {"status": "ok", "recipe": command.get("recipe")}

def on_connect(client, userdata, flags, reason_code, properties):
    client.subscribe(CMD_TOPIC, qos=1)

def on_message(client, userdata, msg):
    reply_topic = getattr(msg.properties, "ResponseTopic", None)
    corr = getattr(msg.properties, "CorrelationData", None)
    if reply_topic is None:
        print(f"Request on {msg.topic} has no Response Topic, no reply possible")
        return
    if not reply_topic.startswith(ALLOWED_PREFIX) or len(reply_topic) > MAX_TOPIC_LEN:
        print(f"Rejected Response Topic {reply_topic!r} from request on {msg.topic}")
        return
    if corr is None:
        result = {"status": "error", "reason": "missing correlation data"}
    else:
        try:
            result = handle(json.loads(msg.payload))
        except Exception as exc:
            result = {"status": "error", "reason": str(exc)}
    props = Properties(PacketTypes.PUBLISH)
    if corr is not None:
        props.CorrelationData = corr
    props.ContentType = "application/json"
    client.publish(reply_topic, json.dumps(result), qos=1, properties=props)

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,
                     client_id="press-07", protocol=mqtt.MQTTv5)
client.username_pw_set("press-service", "YOUR_PASSWORD")  # user from the ACL file
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.example.com", 1883)
client.loop_forever()

The status field separates two failure cases for the requester. A reply with “status”: “error” means a response arrived. In the sample that is a rejected command, a payload that is not JSON, or missing Correlation Data. No reply before the timeout means no matching response arrived in time: the request may not have reached the machine, the machine may be offline, or the reply may have been dropped or delayed.

How Do You Keep Responses Apart When Hundreds of Requests Run in Parallel?

Parallel requests stay apart when every request carries its own Correlation Data value and the requester matches answers by that value alone. Arrival order, topic and timing play no part in the matching.

A service in a SCADA system polls 300 presses every minute. Since request() blocks, it runs the calls in a thread pool and publishes all 300 within one second to the presses’ command topics, with the Response Topic property set to reply/scada-01. The answers arrive in random order, and the table of open requests maps each one to its press by Correlation Data.

CriterionShared reply topic per clientReply topic per request
SubscriptionsOne at startupOne SUBSCRIBE and UNSUBSCRIBE per request
Broker load at 300 requests1 subscription300 short-lived subscriptions
ACL rulesOne pattern rule per clientSame pattern rule, one topic level deeper
MatchingCorrelation DataTopic name, Correlation Data optional
Typical failureOpen entries lost on requester restartReplies lost if the SUBACK arrives late
Three parallel MQTT requests from scada-01 to different presses, with replies returning out of order on one reply topic
Figure 2: Answers arrive in any order. Correlation Data maps each one to its open request.

Four rules keep timeouts under control:

  1. Timeout per device class: A PLC on the shop floor answers within milliseconds. A battery-powered sensor with a sleep cycle sometimes takes minutes.
  2. Cleanup on timeout: Delete the entry when the timeout fires and log the Correlation Data for troubleshooting.
  3. Limited retries: Retry two or three times at most and give every retry new Correlation Data, so a late answer to the first attempt stays distinguishable. A command ID in the User Properties stays the same across all retries, so the responder skips commands it has already executed.
  4. Expiry on the request: Set a Message Expiry Interval that matches the timeout. The broker then drops requests that sit in the queue of an offline responder longer than the requester waits.

Under load, three symptoms point to problems in the pattern. Growing memory on the requester shows entries that never get deleted. Full queues on the broker show responders that consume slower than requests arrive. Many unknown replies in the log show timeouts that are shorter than the real response time of the devices.

How Do You Secure Response Topics against Unauthorized Access?

You secure response topics with two controls. The broker limits every client to subscribing on its own reply branch. The responder checks each incoming Response Topic before it publishes.

The first risk is reading. A client allowed to subscribe to reply/# receives every answer in the system. The second risk is writing. A request with the Response Topic factory/line-2/press-08/cmd makes the responder publish into another machine’s command topic with its own permissions. In Eclipse Mosquitto, an ACL file covers both rules.

# Every client reads only its own reply branch
pattern read reply/%c/#

# The press service reads commands and writes replies
user press-service
topic read factory/+/+/cmd
topic write reply/#

Everything the file does not list is denied. Even a manipulated Response Topic outside reply/ therefore fails at the broker. Requesters additionally need write access to the command topics they use. In Pro Mosquitto, you maintain these rules as roles for clients and groups in the Management Center.

Topic tree with locked reply branches for each client and separate read and write rights for command topics
Figure 3: Each requester reads only its own branch under reply/. The responder writes replies and reads commands.

On the responder side, three checks close the remaining gaps:

  1. Prefix check: Answer only to topics under reply/.
  2. Length limit: Reject Response Topics above a fixed length, for example 128 characters.
  3. Logging: Record rejected topics together with the request topic to spot misconfigured or hostile clients.

Both controls depend on the broker knowing who is connected. mTLS binds the connection to a client certificate. The Authentication Method property in CONNECT starts an extended authentication exchange such as SCRAM. TLS, certificates and audit trails belong to the broader topic of MQTT security.

What Must Your MQTT Broker Support for Production-Ready Request Response?

A broker is ready for request response in production when it forwards all MQTT 5.0 properties unchanged and enforces topic permissions per client. It also has to show which clients connect and which topics carry traffic.

Use this checklist to rate your broker:

  • Full MQTT 5.0 support: Response Topic, Correlation Data, Content Type and User Properties reach the subscriber byte for byte.
  • Configurable reply branches: You define the topic tree for responses yourself.
  • Topic-level permissions: Separate read and write rights per client, user or role, with client ID patterns.
  • Visibility: A live view of connections and topic traffic reveals an unexpected reply/# subscriber early.

Request response setups break at three points in practice. A hard-coded reply prefix forces every team into one topic tree. Authorization by topic alone leaves reply branches readable for every client. Without visibility into subscriptions, a misconfigured ACL only shows up after data has leaked.

Pro Mosquitto, the enterprise MQTT broker from the team behind Eclipse Mosquitto, addresses these points. RBAC separates read and write rights per reply branch and the Management Center monitors connections and topic traffic for troubleshooting. Multi-Broker Management lets you administer several brokers from one place, from the edge broker in the plant to the main broker in the data center.

Turn MQTT Request Response into a Reliable Command Channel for Your Devices

MQTT request response gives devices and services a confirmed command channel on the connection they already use. The pattern holds up when you combine a reply topic schema with one branch per client, Correlation Data plus timeouts on every request and ACLs that keep each branch private. Your broker decides whether these rules still hold when hundreds of devices send requests at the same moment.

Pro Mosquitto adds the broker-side controls for this setup.

Your benefits with Cedalo:

  • Pro Mosquitto builds on Eclipse Mosquitto, the broker you and your engineers know. Existing configurations can carry over.
  • RBAC defines who reads and writes which part of your topic tree, and audit trails record changes to these permissions.
  • In the Management Center, you check whether a responder is connected and publishes to its reply branch when a reply goes missing.
  • Enterprise support comes from the people who develop Eclipse Mosquitto.

Test Pro Mosquitto with Your Request Response Setup

Test your requester and responder on Pro Mosquitto before rollout. Your engineers keep their Eclipse Mosquitto know-how, so confirmed device commands reach production with little retraining.

MQTT Request Response – Frequently Asked Questions

Can Multiple Responders Answer the Same MQTT Request?

Yes, every client subscribed to the request topic receives the request and can reply with the same Correlation Data. For exactly one responder per request, subscribe all responder instances through a shared subscription such as $share/press-service/factory/+/+/cmd.

Can an MQTT Broker Act as the Responder?

In standard MQTT, the broker only routes requests and replies. A service connected to the broker or a broker plugin takes the responder part, for example to answer queries on behalf of an offline gateway.

What Happens to an MQTT Request If the Responder Is Offline?

With a persistent session and QoS 1, the broker queues the request until the responder reconnects. It then delivers the queued requests in the order they arrived, and without a Message Expiry Interval a request stays queued as long as the session exists.

How Large Should Correlation Data Be?

16 bytes from a binary UUID cover most systems and keep every message small. A counter combined with the client ID works as well, as long as the value stays unique across restarts. Keep tokens and user names out of it, because every responder reads the value.

Can You Expose an MQTT Request Response Flow through a REST API?

Yes, a gateway service accepts the HTTP call, publishes an MQTT request with its own reply topic and Correlation Data and holds the HTTP connection open. When the reply arrives, the gateway returns it as the HTTP response or sends a 504 after its timeout.

Does Pro Mosquitto Support MQTT 5.0 Request Response?

Yes, Pro Mosquitto supports MQTT 5.0 and passes Response Topic and Correlation Data to subscribers unchanged. MQTT 3.1.1 clients connect to the same broker, so you move device groups to the MQTT 5.0 pattern one at a time.

Where Can You Run Pro Mosquitto for Request Response Flows?

Pro Mosquitto runs in cloud, on-premises, container and edge environments, for example with Docker, Kubernetes or OpenShift. Requester, responder and reply topic schema stay the same in every environment, so you test the flow locally and roll it out to the plant with the same topics.

About the author

Vitalii Tutevych
Vitalii Tutevych

Software Engineer at Cedalo

Vitalii is a software engineer at Cedalo GmbH. He holds a background in computer engineering and is currently completing an M.Sc. in Computer Science at Universität Bonn, where his work has focused on computer vision, data annotation, and robot perception.

Prior to Cedalo, Vitalii worked as a research assistant on the NimbRo@Home and NimbRo Soccer robotics teams, contributing to award-winning RoboCup competition entries, and taught university courses on robotics and machine learning topics for several years.

View all articles by Vitalii Tutevych