Search code examples
botframework

When sending multiple messages using await context.PostAsync(reply), they are sometimes received out of order


When we send messages using the below code using the Directline channel, the messages are sometimes received with their order swapped.

await context.PostAsync(msg1);
await context.PostAsync(msg2);

Expected:

mgs1
msg2

But in some cases, they're coming through as

msg2
msg1

Is there any way to handle and prevent this?


Solution

  • I'm going to write this answer assuming you're using the Directline or REST API for receiving messages. I can update if that's not the case.

    This entire answer is based off of the Receive activities from the bot docs as well as doing some testing of the Directline API to confirm.

    If you're connected via WebSocket, you should always be receiving the messages in order, provided there isn't some kind of size difference in the messages (like one has an attachment) that requires additional processing.

    If you're not, messages are retrieved via a polling interval, meaning that your client likely sends a GET request every 5 or 10 seconds (varies by client) to retrieve all messages that have not already been retrieved.

    Upon doing so, the client will receive something like this:

    {
        "activities": [
            {
                "type": "message",
                "channelId": "directline",
                "conversation": {
                    "id": "abc123"
                },
                "id": "abc123|0000",
                "from": {
                    "id": "user1"
                },
                "text": "hello"
            }, 
            {
                "type": "message",
                "channelId": "directline",
                "conversation": {
                    "id": "abc123"
                },
                "id": "abc123|0001",
                "from": {
                    "id": "bot1"
                },
                "text": "Nice to see you, user1!"
            }
        ],
        "watermark": "0001a-95"
    }
    

    My guess is that your client is just running a foreach on the array of activities, which could be displaying them out of order. If you have the client order them by either timestamp or id, it should work.