Keep alive for MQTT vs TCP

I am trying to reduce the data consumed by the device which is connected to my private MQTT server with a keep alive value of 300secs.

I am analyzing the packets from the device to server with wireshark and I see MQTT ping requests every 300 seconds but I also see TCP keep alive packets at 60 sec intervals.

Is this the expected behavior or should the TCP keep alive and MQTT keep alive needs to be same? Is it possible to change the keep alive interval for TCP?

1 Like

TCP keep-alive and MQTT or Websocket pings are completely independent. The main reason for the top-level pings is to survive proxies.
It is possible to change everything - my understanding is that you’d like to get rid of pings or make them rare?

I would like to make tcp keep-alive packets rare. Where can I make this change?

setsockopt SO_KEEPALIVE and friends on a MQTT socket.
If you’re using Mongoose library, struct mg_connection *c; .... c->sock is the socket in question.

where can I find definition for setsockopt function?

I don’t generally like reviving old topics, but I’m trying to do exactly this and having no joy. Calling setsockopt on c->sock is returning EBADF (bad file descriptor).

struct mg_connection *c = mgos_mqtt_get_global_conn();
int on = 0;
sock_read = setsockopt(c->sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on));
LOG(LL_ERROR, ("Socket %d Keepalive set: %d", sock_read, errno));

Returns “Socket -1 Keepalive set: 9”

Where is the struct definition for mg_connection? It’s definitely different than the one in Cesanta’s net.h, which contains fd instead of sock.

Can we get a compile-time option to disable keepalive, and/or some sort of config option to set TCP_KEEPIDLE to something higher than 60 seconds? The default for this on linux is 2 HOURS, so having it fire 120x more than normal is very wasteful, especially on bandwidth-constrained environments like MTM cell networks. Given that there is already a keepalive in MQTT itself, I’d personally just prefer turning it off altogether to save the 114B per minute, which ends up eating through 160KB per day in useless chatter.

For anyone looking to deal with this in the future, the function you’re looking for is
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle, int interval, int count);
found at https://github.com/cesanta/mjs/blob/master/src/common/platforms/lwip/mg_lwip_net_if.c#L117

If you set any of the int variables to zero it will disable keepalive entirely.

1 Like