title: Azure Function execution speed is extremely slow and inconsistent
body: <p>I am writing few Azure Functions script that reads and write from/to an internal database and display relevant information into a webpage.</p>
  
  <p>I noticed extreme slowness or even timeout in the web UI when loading the web page which calls the Azure Function script. After further investigation, I realized that the following:</p>
  
  <ol>
  <li>Azure Function scripts sometimes takes anywhere between 10 seconds to more than 1 minutes to connect to SQL database.</li>
  <li>Sometimes the scripts will run in few millisecond and sometimes it will take more than 3 minutes to completely run the script.  </li>
  </ol>
  
  <p>Here is my Azure Function script:</p>
  
  <pre><code>module.exports = function(context, req) {
  
  context.log("Function Started: " + new Date());
  
  // Import package
  const sql = require('mssql');
  var _ = require('underscore-node');
  var moment = require('moment');
  var Promise = require('promise');
  // Create a configuration object for our Azure SQL connection parameters
  var config = {
      server: "***", // Use your SQL server name
      database: "***", // Database to connect to
      user: "***", // Use your username
      password: "***", // Use your password
      port: ***,
      // Since we're on Windows Azure, we need to set the following options
      options: {
          encrypt: true
      },
      multipleStatements: true,
      parseJSON: true
  };
  var flagDefinitionId = null;
  
  if (req.query.Id == null || req.query.Id == "" || req.query.Id.length == 0) {
      context.res = {
          // status: 200, /* Defaults to 200 */
          body: "No have flagDefinitionId "
      };
      context.done();
      // return;
  }
  
  var listTicketsFlag = [];
  
  flagDefinitionId = req.query.Id;
  sql.close();
  var DBSchema = "b8akjsms2_st.";
  sql.connect(config).then(function() {
      context.log("SQL Connected: " + new Date());
  
      var getAllEventTicketGoToMarket = new Promise(function(resolve, reject) {
          var queryGetEvent = ";WITH EventLog1 AS(" +
              " SELECT MD1, max([DateTime]) as LTime from " + DBSchema + "EventLog" +
              " where ([Event] = 'Ticket_Go_To_Market' OR [Event] = 'Acknowledge_Timeout')" +
              " group by MD1 )" +
              " SELECT * from ( SELECT EV.MD1 , EV.MD2," +
              " (SELECT COUNT(*) from " + DBSchema + "EventLog where MD1 = EV.MD1 and [Event] = 'Market_Ticket_Clear') as TotalClear" +
              " FROM " + DBSchema + "[Ticket] T" +
              " JOIN (SELECT E.* from " + DBSchema + "EventLog E join EventLog1 E1 on E.MD1 = E1.MD1 and E.[DateTime] = E1.LTime) EV ON T.Id = EV.MD1" +
              " WHERE T.IsInMarket = 1 and EV.MD2 &lt;&gt; ''" +
              " AND T.Id NOT IN (Select TicketId from " + DBSchema + "TicketFlag where FlagDefinitionId = " + flagDefinitionId + ")" +
              " ) R where R.TotalClear &gt; 0";
          context.log("get event log - Ticket_Go_To_Market" + queryGetEvent);
          new sql.Request().query(queryGetEvent, (err, result) =&gt; {
              context.log("this is --------&gt; EventLog " + result.recordset.length);
              resolve(result.recordset);
          });
      });
  
      Promise.all([getAllEventTicketGoToMarket]).then(function(values) {
          var ticketGoToMarket = values[0];
          context.log("this is --------&gt; values: " + values[0].length + " ==+++++==== " + JSON.stringify(values[0], null, 2));
  
          if (ticketGoToMarket.length != 0) {
              listTicketsFlag = _.filter(ticketGoToMarket, function(num) {
                  var countSP = num.MD2.split(',');
                  // context.log("countSP =====&gt; " + countSP.length + "num.TotalClear ==&gt;" + num.TotalClear)
                  if (num.TotalClear &gt; countSP.length) {
                      return num.MD1;
                  }
              });
              // context.log("listTicketsFlag =====&gt; " + JSON.stringify(listTicketsFlag, null, 2));
          }
          insertTicketFlag();
  
      });
  
      function insertTicketFlag() {
          context.log("this is ----- ===&gt; Insert:  " + listTicketsFlag);
          // insert
          var insertTicketFlagPromise = new Promise(function(resolve, reject) {
  
              context.log("listTicketFlag ----- ===&gt; " + listTicketsFlag.length);
  
              if (listTicketsFlag.length == 0) {
                  context.log(" -------------------- No have ticket need FLAG");
                  resolve();
  
              } else {
  
                  // insert new data to TicketFlag FlagTickets
                  var listTicketInsert = ""; //convertArrayToSQLString(listTicketsFlag, true, flagDefinitionId);
                  var len = listTicketsFlag.length - 1;
                  for (var j = 0; j &lt;= len; j++) {
                      listTicketInsert += '(\'' + listTicketsFlag[j] + '\', \'' + flagDefinitionId + '\')';
                      if (j != len) {
                          listTicketInsert += ",";
                      }
                  }
                  context.log("HERE : " + listTicketInsert);
  
                  var insertQuery = 'Insert into  ' + DBSchema + '[TicketFlag] (TicketId, FlagDefinitionId) values ' + listTicketInsert + '';
  
                  context.log("this is --------&gt; InsertQuery" + insertQuery);
  
                  // return;
  
                  context.log("read data of FlagRule");
                  new sql.Request().query(insertQuery, (err, result) =&gt; {
                      context.log("this is --------&gt; insertQuery");
                      resolve(result);
  
                  });
              }
          });
  
          Promise.all([insertTicketFlagPromise]).then(function(values) {
              context.log("DONE ALL");
              sql.close();
              context.done();
          })
      }
  
  }).catch(function(err) {
      console.log(err);
      context.done();
  });
  </code></pre>
  
  <p>};</p>
  
  <p><a href="https://i.stack.imgur.com/tgjKa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tgjKa.png" alt="enter image description here"></a></p>
  
  <p><a href="https://i.stack.imgur.com/fexhu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fexhu.png" alt="enter image description here"></a></p>
  
  <p>How can resolve this slowness issue?</p>