botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

[Direct Line] Timeout 500: ECONNECTION timeout with some load with new state API implemented

Open droidpl opened this issue 8 years ago • 14 comments

Bot Info

  • SDK Platform: Node.js (8.9.0)
  • SDK Version: 1.13.1
  • Azure SDK Version (for table storage): 3.0.4
  • Active Channels: Direct Line
  • Deployment Environment: Auzure Bot Service (only channel registration and web app)
  • Bot id: a71cd44f-daf0-4b69-be5f-2ba5273df740
  • All servers published on EU West

Issue Description

Since the moment we started using the bot framework we have had random issues where the messages and the conversation requests returns 500 errors. We are about to go to production with the current bot and we did a load test to see how good or bad the bot can behave in different loads.

Here I will comment the findings to see if they can help to understand where the bottleneck is. Basically our setup is:

  • We have an azure server with the bot built with botbuilder in nodejs
  • The storage we are using is tablestorage. It works properly as I checked the messages with Storage Explorer

Code Example

To build our clients, we have created in our server requests to send info to directline. Those requests to the bot are:

  • /bot/messages -> The bot runs under this url
  • /bot/message -> Sends a certain message to the bot. Attached the code.
BotHttpRequest.use(BOT_URL)
            .url(`/conversations/${message.conversationId}/activities`)
            .method('POST')
            .headers({
                Authorization: `Bearer ${directLineToken}`
            })
            .body({
                text: message.message,
                type: message.messageType,
                from: {
                    id: currentUser.registrationId,
                    name: currentUser.name
                }
            })
            .retries(3)
            .send()
            .then(function (response) {
                return response.data
            })
  • /bot/convesation -> Starts a new conversation with the bot. The code is as follows:
BotHttpRequest.use(BOT_URL)
            .url('/conversations')
            .method('POST')
            .headers({
                Authorization: `Bearer ${directLineAuth}`
            })
            .send()
            .then(function (response) {
                return response.data
            })
            .then((data) => {
              // Send empty message so the conversationUpdate is triggered on the bot and adds the current user.
              // Otherwise, the current user will not be in the conversation and the greetings will not be triggered.
              const message = new BotMessageRequest({
                message: "",
                conversationId: data.conversationId,
                messageType: "message"
              })
              return this.sendMessage(message, currentUser, `BotConnector ${data.token}`).then(() => {
                return data
              })
            })

All this code works for small amount of requests but as long as it grows a bit (not too much), it just gets broken.

Issues

With this setup we did a test with a middle size machine from azure and this are the findings (test done with jmeter, 300 users, 5 requests per user):

  • 64.81% of requests OK vs 35.19% KO
  • 100% of the errors where error 500
  • The response time per message is around 16s
  • Most of the errors are ECONNECTION Timeout 15000ms (we also tried to increase the timeout with the same result, which means this error is sent internally from your backend)
  • The total amount of requests done where 4262

Some errors we have seen in the server: Error 1

ActivityId: 47bb6c41-0000-0000-0000-000000000000, Request URI: /apps/63e70998-1c00-470e-8093-b4ef0dac16b1/services/be412ef7-0aa4-462c-90cc-2ae92aeb435e/partitions/7b23a94a-4102-4a9e-9333-ee80a73e77fe/replicas/131556435222707878p/, RequestStats: , SDK: Microsoft.Azure.Documents.Common/1.19.162.2
    at Function.MongoError.create (D:\home\site\wwwroot\future-street\node_modules\mongodb-core\lib\error.js:31:11)
    at D:\home\site\wwwroot\future-street\node_modules\mongodb-core\lib\connection\pool.js:497:72
    at authenticateStragglers (D:\home\site\wwwroot\future-street\node_modules\mongodb-core\lib\connection\pool.js:443:16)
    at Connection.messageHandler (D:\home\site\wwwroot\future-street\node_modules\mongodb-core\lib\connection\pool.js:477:5)
    at TLSSocket.<anonymous> (D:\home\site\wwwroot\future-street\node_modules\mongodb-core\lib\connection\connection.js:331:22)
    at ZoneDelegate.invokeTask (D:\home\site\wwwroot\future-street\node_modules\zone.js\dist\zone-node.js:275:35)
    at Zone.runTask (D:\home\site\wwwroot\future-street\node_modules\zone.js\dist\zone-node.js:151:47)
    at TLSSocket.ZoneTask.invoke (D:\home\site\wwwroot\future-street\node_modules\zone.js\dist\zone-node.js:345:33)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at TLSSocket.Readable.push (_stream_readable.js:208:10)
    at TLSWrap.onread (net.js:594:20)

Error 2

Error: connect ETIMEDOUT 40.127.139.252:443
    at AppInsightsAsyncCorrelatedErrorWrapper.ZoneAwareError (D:\home\site\wwwroot\future-street\node_modules\zone.js\dist\zone-node.js:811:33)
    at new AppInsightsAsyncCorrelatedErrorWrapper (D:\home\site\wwwroot\future-street\node_modules\applicationinsights\out\AutoCollection\CorrelationContextManager.js:172:18)
    at Object._errnoException (util.js:1024:11)
    at _exceptionWithHostPort (util.js:1046:20)

(We also did a test disabling the bot insights correlation with no change on this)

In the report attached you will also see create anonymous and login, those are calls for our and those doesn't have any impact on the test.

Please let us know a way to reduce those numbers since those are not acceptable for a production ready bot.

Thanks for the support and best regards. Bot performance test results.zip

droidpl avatar Jan 19 '18 08:01 droidpl

This is getting worse and worse everyday with directline

droidpl avatar Jan 23 '18 15:01 droidpl

To check it, we've done the same test with a really simple bot uploaded with the following conditions:

  • SDK Platform: Node.js (8.9.0)
  • SDK Version: 1.13.1
  • Azure SDK Version (for table storage): 3.0.4
  • Active Channels: Direct Line
  • Deployment Environment: Auzure Bot Service (only channel registration and web app) and azure web apps
  • All servers published on EU West

We created a simple bot from the tutorials. The results are as bad as the ones we are having with our bot, so I believe the issue is on the service layer. See attached the results in that case. results_BotPoc_160x5_24-01-2018.zip

droidpl avatar Jan 24 '18 09:01 droidpl

More info on this, when I increase the CPU on the machine on azure it seems to reduce in a huge way the number of errors on performance tests. However there is always at least 1 ECONNECT timeout.

droidpl avatar Jan 24 '18 17:01 droidpl

More logs of what happens in the server with load:

Error: connect ETIMEDOUT 13.95.93.152:443
    at Object._errnoException (util.js:1024:11)
    at _exceptionWithHostPort (util.js:1046:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1182:14)
---------------------------------------------
    at TLSSocket.Readable.on (_stream_readable.js:772:35)
    at tickOnSocket (_http_client.js:640:10)
    at onSocketNT (_http_client.js:670:5)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)
---------------------------------------------
    at ClientRequest.onSocket (_http_client.js:658:11)
    at handleSocketCreation_Inner (_http_agent.js:340:15)
    at oncreate (_http_agent.js:240:5)
    at Agent.createSocket (_http_agent.js:226:5)
    at Agent.addRequest (_http_agent.js:192:10)
    at new ClientRequest (_http_client.js:258:16)
    at Object.request (https.js:240:10)
    at Request.start (D:\home\site\wwwroot\future-street\node_modules\request\request.js:748:32)
    at Request.write (D:\home\site\wwwroot\future-street\node_modules\request\request.js:1498:10)
    at end (D:\home\site\wwwroot\future-street\node_modules\request\request.js:546:18)
    at Immediate._onImmediate (D:\home\site\wwwroot\future-street\node_modules\request\request.js:575:7)
    at runCallback (timers.js:789:20)
    at tryOnImmediate (timers.js:751:5)
    at processImmediate [as _immediateCallback] (timers.js:722:5)

with a lot of requests this appears in the logs, followed I see:

2018-02-01T09:51:01.773Z - error: Send POST https://directline.botframework.com/v3/directline/conversations/B8ccwE73neT8Jz5M9Dv5Ei/activities:
                     Data sent: {"text":"","type":"message","from":{"id":"5a72e2ba44dd633d780fc368"}}
                     Response status: null
                     Response message: timeout of 1ms exceeded
                     Response data: null 
                     Retries: {"retryCount":3,"lastRequestTime":1517478661773}

and this what the user receives:

2018-02-01T09:51:01.805Z - error: On /api/bot/conversation: InternalServerError --> 
      User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_74)
      Registration ID: 5a72e2ba44dd633d780fc368 Anonymous
      Request: undefined
      Response: {"code":"InternalServer","message":"timeout of 1ms exceeded"}

droidpl avatar Feb 01 '18 09:02 droidpl

2 observations about the data in the last post:

  1. Direct Line received a message for conversation B8ccwE73neT8Jz5M9Dv5Ei from the client at 2018-02-01T09:50:18.255, tried to post it to the bot and got an HTTP 500.

You mentioned that increasing the CPU on the bot server helped. It may be that the server is still overloaded and cannot process the requests. Traffic to the bot is very bursty.

  1. The InternalServerError for the 2018-02-01T09:51:01.773Z post. Direct Line received that post and processed it fine. It was not Direct Line that returned the "timeout of 1ms exceeded" error. 1ms?! That's a bit optimistic.

Both cases look to be issues on the bot side. I suggest looking at scaling up or our your bot and tracking down who's setting that 1ms timeout.

You're right about the 15 second timeout: that is the time allowed for bot to respond to a message. If the bot is busy and cannot respond then Direct Line will time out the request.

vincec-msft avatar Feb 01 '18 17:02 vincec-msft

We are experiencing exactly the same Connect ETIMEDOUT 13.95.93.152:443 error under high load. Bot is running in Web App Bot/App service environment. Interesting thing regarding @vincec-msft last post is that CPU load is constantly under 10%, so it seems like a problem on side of directline.botframework.com service. What logs should we provide to support the solution?

dvorakjan avatar Feb 26 '18 14:02 dvorakjan

Are you on the latest BotBuilder release? (v3.14 https://www.npmjs.com/package/botbuilder)

We have the following recommendations:

  1. Use the AgentKeepAlive NPM package https://www.npmjs.com/package/agentkeepalive to ensure re-use of the SSL Connections.
  2. Tune the MaxSockets parameter of the AgentKeepAlive to be at least 160 to match the number of SNAT port.

Note: If you have set IISNode nodeProcessCountPerApplication="0" to use all CPU’s for the Node Process then you will need to adjust the MaxSockets accordingly.

So on a 4 CPU instance size (P4) you will have 4 Node Processes so MaxSockets will need to be set to 40 . References https://docs.microsoft.com/en-us/azure/load-balancer/load-balancer-outbound-connections https://blogs.msdn.microsoft.com/mast/2015/07/13/azure-snat/

Please let us know if this resolves the issue for you?

EricDahlvang avatar Feb 26 '18 16:02 EricDahlvang

Thank you very much for these clues, Eric. We will try them out as soon as possible and let you know it it resolved the issue.

dvorakjan avatar Feb 27 '18 18:02 dvorakjan

We did some performance testing with agentkeepalive set into https.globalAgent (because lack of way to inject custom agent into the ChatConnector class of botbuilder package responsible for failed requests) with MaxSocket set regarding your recommendation.

And it looks it helped! No ETIMEDOUT errors anymore even during double request per second rate than before. I just hope that the reason is not just some error in performance testing process. Thank you very much for your help, @EricDahlvang .

dvorakjan avatar Mar 05 '18 09:03 dvorakjan

I actually just provided the code @vincec-msft gave me, so he deserves your thanks.

We've also provided a blog post describing the workaround: https://blog.botframework.com/2018/03/05/fix-snat-exhaustion-node-js-bots/

I'm glad this has been resolved. Closing the issue.

EricDahlvang avatar Mar 06 '18 00:03 EricDahlvang

We are also testing the global agent thing. Maybe using the global helps.

droidpl avatar Mar 07 '18 11:03 droidpl

@dvorakjan Could you please share the code snippet you used to configure the keepaliveagent module with the botframework. I'm using restify to create the nodejs server. Not sure if we have to pass the keepaliveagent as argument when creating the restify server or we should tweak the chat connector's send method to use it.

vamzz1 avatar Apr 20 '18 12:04 vamzz1

@vamzz1 Of course, here you are.

const HttpAgent = require('agentkeepalive')
const HttpsAgent = require('agentkeepalive').HttpsAgent

// enable request keepalive to reuse connections and set sockets count to match the number of SNAT port
const nodeProcesses = process.env.NodeProcesses || 1
const maxSockets = 160 / nodeProcesses
http.globalAgent = new HttpAgent({ maxSockets })
https.globalAgent = new HttpsAgent({ maxSockets })

dvorakjan avatar Apr 24 '18 09:04 dvorakjan

Thank you @dvorakjan .

vamzz1 avatar Apr 26 '18 09:04 vamzz1