nodejs mysql query blocking event loop

1.6k views Asked by At

I have had this issue cause blocking problems in a full blown application, I've managed to reduce it to this code:

"use strict";
var mysql = require('mysql');
var blocked = require('blocked');

blocked(function(ms) {
  console.warn('event loop blocked for', ms, 'ms');
});

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : '****',
  password : '****'
});

connection.connect(function(err) {
  console.time('query');
  connection.query('SELECT * FROM db.table', function(err, rows, fields) {
    console.log('rows:', rows.length);
    console.timeEnd('query');
    connection.end();
  });
});

I get this output :

event loop blocked for 445 ms
event loop blocked for 399 ms
event loop blocked for 496 ms
event loop blocked for 388 ms
event loop blocked for 356 ms
event loop blocked for 345 ms
event loop blocked for 354 ms
event loop blocked for 346 ms
event loop blocked for 333 ms
event loop blocked for 344 ms
rows: 115194
query: 4856ms

This of course has pretty harsh implications on my server since incoming requests have to wait out these times, and as each incoming connection runs a query that causes more blocking, it means concurrency blows up my response times. Besides that I really don't understand the cause of it since I thought IO in node.js should be non-blocking. BTW you can also see my table is not that big.

I'd really appreciate any help and even if you don't have a solution I'd appreciate an explanation.

Thanks

0

There are 0 answers