node-mssql icon indicating copy to clipboard operation
node-mssql copied to clipboard

Random Slowness with Parameterized Queries

Open Raxvis opened this issue 9 years ago • 9 comments

Found this issue https://github.com/patriksimek/node-mssql/issues/108 which was closed, but led me down far enough to believe this is an issue.

Essentially, when I use input(name, type, value), the query (randomly) slows way down.

Random is best way I can describe it. Some calls are quick, and then suddenly they take an extremely long time (2-300 ms to 10,000 ms)

When I change to putting the parameter in the sql query itself, no issue.

Am I missing something? I changed the input type (It's a GUID) back and forth from VarChar and UniqueIdentifier with no luck.

Slow Query:

await pool.request()
.input('GUID', sql.UniqueIdentifier, '00000000-0000-0000-0000-000000000000')
.input('String', sql.VarChar, 'test')
.query('SELECT * FROM TABLE WHERE GUID = @GUID AND String = @String);

Fast Query

const GUID = '00000000-0000-0000-0000-000000000000';
const String = 'test';
await pool.request()
.query(`SELECT * FROM TABLE WHERE GUID = '${GUID}' AND String = '${String}'`);

Raxvis avatar Apr 11 '17 22:04 Raxvis

I'd try bypassing this library and testing in SQL Management studio to compare execution time and review the execution plan.

I recall running into a similar issue with a date parameter vs a literal string.

If the guid is not user supplied data, you can use dynamic SQL without fear of SQL injection. That's what I wound up doing for my date parameter/speed issue, and that had nothing to do with this library.

priedthirdeye avatar Apr 12 '17 14:04 priedthirdeye

It is not user supplied so I am using the dynamic SQL.

I will test against the database directly. I did early, but didn't declare the variables, so that may have been the difference. Will report back

Raxvis avatar Apr 12 '17 19:04 Raxvis

Okay, back again.

Running the SQL against the database directly (SQLPro Studio), I didn't have any issues.

Both as declared variables and as inline variables, no issue. This still begs to question, why is node-mssql taking 30 times longer when I use an input versus not?

Raxvis avatar Apr 12 '17 19:04 Raxvis

I've experienced a similar problem most notably when we migrated our DB from SQL Sever to Azure. Ultimately, both DBs are identical and use the exact same logic and handling with respect to mssql. The only thing that's changed in our application is the config file that points to our new Azure instance and setting encrypt to true.

A simple query such as the one below would take ms on SQL Sever 2017 and anywhere from 6-20 seconds on Azure. As a whole, our DB is incredibly small - no more than a few thousand records within a given table - with each record having like 15 fields.

let v = 'someStringVariable';
let input = ['someVal', sql.VarChar(50), v];
let query = 'SELECT * FROM someTable WHERE someField = @someVal';

_selectWithInput(pool, input, query, function(err, data) {
    if (err) {
        return res.json(err);
    }
    res.json(data);
});

function _selectWithInput(p, i, q, cb) {
    return p.then((pool) => {
        pool.request()
        .input(i[0], i[1], i[2])
        .query(q)
        .then(function(recordset) {
                cb(null, recordset.recordset)
            }).catch(function(err) {
                cb(err)
            })
    });
}

I've alleviated some of the "slowness" by removing the length constraint to the following:

let input = ['someVal', sql.VarChar, v];

dnseminara avatar Nov 13 '18 17:11 dnseminara

What does your pool configuration look like? Min, max, etc? Have you ticketed Azure support?

I've alleviated some of the "slowness" by removing the length constraint to the following:

How much did this affect things?

willmorgan avatar Nov 14 '18 09:11 willmorgan

Thanks for the prompt reply @willmorgan

What does your pool configuration look like? Min, max, etc?


let config = {options:{}};

config.user = "someUser";
config.password = "somePassword";
config.server = "someAzureThingy.database.windows.net";
config.database = "someDB";
config.options.encrypt = true;

module.exports = config;

------

const pool = new sql.ConnectionPool(config).connect()
    .then(p => {
        return p
    })


Initially (and currently), it's set to the default parameters for min and max. However, I've modified it to variety of combinations when the aforementioned lag arose - such as:

  • min of 5, max of 30
  • min of 1, max of 100

Have you ticketed Azure support?

I have not, will look into this

How much did this affect things?

It's down to 1-2 seconds. Obviously, it's still not on the order of hundreds of ms like it was with SQL Sever 2017, but for now our clients won't be able to tell the difference (granted we're only returning 200 or so records - with only 12-15 fields on a table that probably has 8,000 records in its entirety)

dnseminara avatar Nov 14 '18 17:11 dnseminara

On the pool front, the minimum is set to 0 by default. While this probably won't do much to solve your intermittent slow request problem, I'd consider increasing that to 5, but at least 1, so you don't fall foul of occasionally slow connection time-to-acquires should a connection be held on an unusually slow request like the events we're describing in this ticket. FWIW, Azure support recommends a 30 second connection acquire timeout, which is huge, but you can sort of mitigate this.

Having looked at the VarChar type inside the library, I can't see anything that would suggest that removing the length option would have any change in performance. It might be something inside the Tedious driver itself (assuming you're using this, and not msnodesql8):

https://github.com/tediousjs/tedious/blob/234cf6c26d3b7d06e4c1f25b7b2ef5b00ff87729/src/value-parser.js#L178-L185 https://github.com/tediousjs/tedious/blob/234cf6c26d3b7d06e4c1f25b7b2ef5b00ff87729/src/value-parser.js#L366-L378

What sort of data are you dealing with in your columns? Any amount of really big text, JSON, binary data?

It might be worth having a chat with Azure support, or looking at your own database instrumentation tooling, as they might identify a problem with the SQL Server instance. I imagine they'd want to first look at any slow requests. The other thing would be to try and connect a profiler and see if it's an issue on the JS side where the data is being decoded.

As the OP reports this as happening completely randomly, for such a simple query I'm surprised this hasn't been raised more often if it's an issue with the library. Is the slowness still random for you, or is it constant?

willmorgan avatar Nov 15 '18 10:11 willmorgan

I'd consider increasing that to 5, but at least 1, so you don't fall foul of occasionally slow connection time-to-acquires should a connection be held on an unusually slow request like the events we're describing in this ticket

Good to know. Will adjust accordingly.

Having looked at the VarChar type inside the library, I can't see anything that would suggest that removing the length option would have any change in performance.

If I have the bandwidth to create a simple example comparing the two (with data length and no data length) and the problem is still intermittently noticeable, I create a new/separate issue.

What sort of data are you dealing with in your columns? Any amount of really big text, JSON, binary data?

The parameters themselves are very, very simple strings. One or two word strings. Effectively the queries are as simple as SELECT * FROM cityInformationView WHERE City = 'New York'. I should note that these queries are hitting a view with subqueries rather than a table and while that may add some latency - the time difference between querying against the view in SQL Sever and Azure was astronomically drastic when a data length was supplied. Perhaps there's something that I missing or a larger issue with views and sub queries in Azure as it relates to using tedious, mssql, etc. Running this query straight in SQL Server still returns on the order of ms - as it should.

As far as the remaining columns, they're pretty basic. Here's an example of a JSON response

{
Address1: "some address"
BuildUse: null
BuildingID: 1456
BuildingName: null
BuildingOwnership: "Private"
City: "Some City"
County: "Some County"
DateConstructed: 1919
Historic: null
LegislativeDistrict: null
Material: "2"
State: "XX"
Stories: null
}

As the OP reports this as happening completely randomly

It is random and seemingly intermittent. It's often hard to replicate, but once I removed the explicit data length, I have not experienced the same issue since then - so I figured I'd share my experience.

for such a simple query I'm surprised this hasn't been raised more often if it's an issue with the library.

You're absolutely correct! The query and the serialization is as basic as it gets. So I'm also surprised that I couldn't find a similar issue.

Thanks for your help diving into this - as mentioned, if I have some free time to create a simple application/demo - I'll open a new ticket. Figured by noting the data length removal (at least on my end) helped resolved most of the random slowness that I was experiencing.

dnseminara avatar Nov 15 '18 19:11 dnseminara

I'm going to close this as there hasn't been much progress nor others reporting the problem. If I guessed I'd think it was a connection depletion issue, but it's hard to tell as I don't know how the randomness is distributed.

dhensby avatar Feb 13 '19 17:02 dhensby