Weird behavior of TLSSocket


We have an application built on top of Websocket/TLSSocket. Once in a while, we would attempt to send 3 ~ 6 messages via Websocket in quick succession. In > 99% of times, this would work just fine. But occasionally problems happen. In those times, if 6 messages are sent right after one another, the 3rd, or 4th, or 5th, 6th message is not received by server, while two copies the message ahead of it are received by server twice. When only 3 message are sent a time, sometimes (<1%) two copies of 3rd message will be received by server.

The application is built on top of Mbed-OS-5.15, with the following change:

nsapi_error_t TLSSocketWrapper::close()
    if (!_transport) {
        return NSAPI_ERROR_NO_SOCKET;

    tr_info("Closing TLS");

    int ret = 0;
    if (_handshake_completed) {
        // switched to timeout, otherwise system occasionally hangs
        ret = mbedtls_ssl_close_notify(&_ssl);
        if (ret) {
            print_mbedtls_error("mbedtls_ssl_close_notify", ret);
        _handshake_completed = false;

    if (_close_transport) {
        int ret2 = _transport->close();
        if (!ret) {
            ret = ret2;

    _transport = NULL;

    return ret;

TLSSocket is changed from blocking to timeout after 5 seconds. Otherwise system hangs occasionally.

The only possible explanation seems to be: 1) TLSSocket sometimes re-send message by itself upon perceived failure in previous attempt, because there is re-send in application layer. 2) When TLSSocket re-sends previous message, it silently discards the next message in line.

Could you anyone offer some pointers?

Thanks in advance,