Publish: what is correct application of this call?

I am new to Mosquitto. I started with example in this page at its bottom. There’s a hint on how to use subscribe. But after some consideration I see that there are no examples on how to use publish.

I created this topic in Stackoverflow.

I am asking for the proper software architecture to use mosquitto_publish().

While the call itself may look very simple and straightforward, under specific circumstances, which seem not possible to detect in the application, calling mosquitto_publish() may cause memory overflow and machine (IoT device with not-so-much memory) malfunction.

  • application must be able to stop publishing its telemetry data in time to prevent memory overflow due to mosquitto_publish() memory allocations (and optionally start logging messages into another storage than main memory);
  • application must be able to remove messages it deems as “expired” from the unsent stream, replacing them with up-to-date messages.

I admit may not understand something or miss basics, would be very glad for any information on the matter.

There is an example publishing application at this link:

It isn’t possible for the library to know ahead of time whether an allocation will fail. When you call mosquitto_publish the library will attempt to queue that message - if the allocation fails it will tell you. For QoS 0 message, queue of messages will only grow if the client is connected and is attempting to publish at a faster rate than than is able to be delivered. For QoS 1 and 2 publishes, the messages will be queued regardless of whether the client is connected or not and the queue will grow as long as the client is publishing faster than can be delivered.

It isn’t possible to remove messages from the internal queue and in most circumstances I would expect the message delivery to be near instant anyway. If this is a concern for you, I would suggest maintaining your own queue of messages ready for publishing, which you can gradually give to mosquitto_publish when the on_publish callback is called. That also has the benefit of ensuring that you are in control of memory usage.

Does that help?

1 Like

Roger, thank you vey much. Implemented as you said - both queue management and memory allocation (data size) management externally to mosquitto. Therefore now I can accumulate messages in the buffer file while mosquitto is trying to restore the connection.