mqttnats.io

In NATS MQTT, how do I publish a retained message?


MQTT has retained messages: i.e. when someone subscribes to a topic — they immediately receive a message "pinned" to this topic.

I'm using NATS as MQTT server, and my app connects to it as a NATS client. How do I "pin" a retained message?


Solution

  • In short: you need to add a message to the $MQTT_rmsgs jetstream:

    $ nats pub '$MQTT.rmsgs.topic.to.pin.message.to' \
      -H 'Nmqtt-RTopic: topic/to/pin/message/to' \
      -H 'Nmqtt-RFlags: 1' \
      -H 'Nmqtt-ROrigin: fmB75D1M' \
      -H 'Nmqtt-RSource: username' \
      -J message-body
    

    I discovered this by running nats sub '>' while publishing a retained message with an MQTT client.

    It revealed a stream of retained messages and a bunch of headers:

    $ nats sub '>'
    [#7] Received on "$MQTT.rmsgs.topic.to.pin.message.to" with reply "$MQTT.JSA.fmB75D1K.MS.ixCNAR8K06mZh3lnNPegV1"
    Nmqtt-RTopic: topic/to/pin/message/to
    Nmqtt-RFlags: 1
    Nmqtt-ROrigin: fmB75D1K
    Nmqtt-RSource: username
    
    message-body
    
    
    [#10] Received JetStream message: consumer: $MQTT_rmsgs > $MQTT_rmsgs_sfgG3wpEFNySpmlDwqaGGn / subject: $MQTT.rmsgs.device.007.to.retain / delivered: 1 / consumer seq: 12 / stream seq: 28
    Nmqtt-RTopic: topic/to/pin/message/to
    Nmqtt-RFlags: 1
    Nmqtt-ROrigin: fmB75D1K
    Nmqtt-RSource: username
    
    message-body
    
    

    What you see here is someone publishing a message to $MQTT.rmsgs.topic.to.pin.message.to which becomes a pinned message for the topic.to.pin.message.to MQTT topic.

    More details of how it works:

    P.S. I noticed some lag when I manually pin a message. Maybe this "undocumented" approach has some quirks; not sure yet