Toooooo slow interacting with MS sql server under Ubuntu 16.04 (both using EF or SQLDataReader)
@gorsand commented on Fri Aug 11 2017
Issue Title
Toooooo slow interacting with MS sql server under Ubuntu 16.04 (either by EF or SQLDataReader)
General
I have a web API application on dotnet under Core 2.0, Ubuntu 16.04, and an MS SQL server as data storage (totally < 1Gb of data there). Core i5 with 8 GB memory laptop, SSD 120 GB. Both the app and the server run on same machine (localhost).
Under windows the same code requires about 2 sec (provided that the server is also running under windows).
When loading a table of about 150 000 rows (about 10 columns) from sql server I get about 300 sec time! Smaller tables also loaded in such a big time (proportionally to the number of rows). All requests are sync (async versions never used).
This happens for both the EF approach or with direct using of SQLDataReader, so the problem is NOT in the EF.
As a workaround I simply run sqlcmd tool with the sql request as a separate process and parse its output as a cvs file. This takes about 2 sec (not 300 sec) for the same tables.
MS SQL server was installed in a pretty "normal" way following the official instructions (https://docs.microsoft.com/en-us/sql/linux/quickstart-install-connect-ubuntu).
I use typical code for DB reading in C# by EF where-style request or just with SQLDataReader:
using (var connection = new SqlConnection(DataConString)) { var command = new SqlCommand(query, connection); command.Connection.Open(); var reader = command.ExecuteReader(); while (reader.Read()) parse_the_line(reader); }
My gues is that Core 2.0 handles the connection in some bad manner (eg. disconnects and connects on each row of table) or there's something in deserialization (though I think just any kind of deserialization woldn't be that bad) or maybe Core 2.0 switches to async methods under the hood (which in turn set a kind of timer and wakes on receiving each piece of data) or so on, but these are only my guesses.
Maybe it's somehow connected with the well known MS SQL server bug (feature?) under linux: sqlcmd tool becomes toooo slow when the output is redirected to a file by '>' in the command line. (Note: I don't redirect the output when using sqlcmd tool as a workaround, just read the process output line by line.) So maybe Core 2.0 works with MS SQL server the same bad way as sqlcmd tool does when redirected to a file. But again these are only my guesses.
Upd:
The problem is on Core side, not with the SQL server. I just tried connecting to Windows-hosted server, the problem still remains (about 300 sec for 150K rows). Though the same code under Windows works fine (about 2-3 sec).
@Ataden commented on Sat Aug 12 2017
I confirm such an issue. On Windows EF Core and SQL library work great but on Linux they are way too slow. It is almost imposible to use them on Linux at all.
@ayurjev commented on Sat Aug 12 2017
I noticed the same slow performance while I was trying to use Core 2.0 on MacOS... It had been taking 40-50 seconds to execute simple query....
@geleems PTAL
Might be related with https://github.com/dotnet/corefx/issues/21530. I am working on it to repro.
I may also possibly be experiencing the same issue. I have a Ubuntu 16.04 server with SQL Server 2017 on it. When running the application directly on the server, it seems to slow down by as much as 10-15x compared to running it on Windows (remotely too).
It seems to be some sort of issue with .net core and sql running on the same machine. Running the same application from a ubuntu machine at my house is almost as fast as windows (and the sql data is still being accessed remotely)
Here is an example: On my local windows machine, I load about 500 records in 174ms (remote sql access) On my local linux machine, I load those 500 records in about 390ms (remote sql access) - the speed is likely due to the linux machine having a way older cpu than my windows machinbe On the remote linux machine - It loads those 500 records in 1100 ms (accessing sql locally)
Using a larger table (10k records), my local windows/linux machine were able to load it in 8 seconds, where as the remote machine took 43 seconds. The CPU usage on the remote machine was low, so it wasnt anything CPU bound.
As for the code, it was just doing a .ToList() on the entity without any joins or additional model mapping
var items = _database.Table.ToList();
edit: seems like the .net core application is just REALLY slow at receiving/materializing the data (the send queue is very slowly going down). Here is are 3 different netstats, ran about 0.5 seconds apart
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 1642533 127.0.0.1:1433 127.0.0.1:53005 ESTABLISHED
tcp 0 1601957 127.0.0.1:1433 127.0.0.1:53005 ESTABLISHED
tcp 0 1577637 127.0.0.1:1433 127.0.0.1:53005 ESTABLISHED
edit: I just tested running the application on the remote linux machine with a database on azure and it runs perfectly fine. There is DEFINITELY something going on when running .net core app and SQL 2017 on same linux machine.
I was trying to reproduce the issue in my Linux environment, but was not able to make it. Selecting 150,000 rows took about 250~300ms in my observation.
Test Environment
- OS: Ubuntu 16.04 LTS x64 in VM
- .NET Core version: dotnet-sdk-2.0.0 (https://www.microsoft.com/net/core#linuxubuntu)
- SQL Server 2016 is located other VM.
- Scheme of the table used for testing:
CREATE TABLE MyAmazingTest
(
id INT,
name VARCHAR(10),
address CHAR(32)
)
- Number of the rows in the test table: 150,000 rows
- Test Query:
SELECT TOP (15000) * FROM MyAmazingTest - Number of Tests Performed: 300 times.
Test Result
- 1st iteration (selecting 150,000 rows 100 times):
- Average Time Elapsed for Selecting 150,000 Rows:
229.97 ms - Average Time Elapsed for Selecting Single Row:
0.001533133 ms - Log: log1.txt
- Average Time Elapsed for Selecting 150,000 Rows:
- 2nd iteration (selecting 150,000 rows 100 times):
- Average Time Elapsed for Selecting 150,000 Rows:
283.94 ms - Average Time Elapsed for Selecting Single Row:
0.001892933 ms - Log: log2.txt
- Average Time Elapsed for Selecting 150,000 Rows:
- 3rd iteration (selecting 150,000 rows 100 times):
- Average Time Elapsed for Selecting 150000 Rows:
301.36 ms - Average Time Elapsed for Selecting Single Row:
0.002009067 ms - Log: log3.txt
- Average Time Elapsed for Selecting 150000 Rows:
Test Code for Repro
class Program
{
public static void Main(string[] args)
{
string sqlHowManyRowsExists = $"SELECT COUNT(*) FROM {testTableName}";
List<object[]> rows = RunQuery(connString, sqlHowManyRowsExists);
// Make sure we have 150,000 rows in the test table.
Console.WriteLine(sqlHowManyRowsExists + " --> " + (rows.Count > 0 ? rows[0][0] : "0"));
RunSelectTableTests(100, 150000);
}
private static string connString = @"Data Source=tcp:mySuperHost;uid=superman;pwd=secret;";
private static string testTableName = "MyAmazingTest";
private static void RunSelectTableTests(int numOfTestRun, int numOfRows)
{
long timeConsumedAllTests = 0;
for (int i = 0; i < numOfTestRun; ++i)
{
long timeConsumedSingleTest = SelectTableTest(numOfRows);
timeConsumedAllTests += timeConsumedSingleTest;
Console.WriteLine($"Test {i} -- Time Elapsed for Selecting {numOfRows} Rows: " +
$"{timeConsumedSingleTest} ms");
}
float timeConsumedSingleTestAvg = ((float)timeConsumedAllTests) / ((float)numOfTestRun);
float timeConsumedEachRowAvg = timeConsumedSingleTestAvg / ((float)numOfRows);
Console.WriteLine($"Average Time Elapsed for Selecting {numOfRows} Rows: " +
$"{timeConsumedSingleTestAvg} ms");
Console.WriteLine($"Average Time Elapsed for Selecting Single Row: " +
$"{timeConsumedEachRowAvg} ms");
}
private static long SelectTableTest(int count)
{
Console.WriteLine("SelectTableTest started....");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
string connectionString = builder.ConnectionString;
Stopwatch stopwatch = new Stopwatch();
long totalTimeConsumed = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = $"select TOP ({count}) * from {testTableName}";
stopwatch.Start();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string id = reader[0].ToString();
string name = reader[1].ToString();
string address = reader[2].ToString();
}
}
stopwatch.Stop();
totalTimeConsumed = stopwatch.ElapsedMilliseconds;
}
}
return totalTimeConsumed;
}
private static List<object[]> RunQuery(string connectionString, string sql)
{
List<object[]> result = new List<object[]>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = sql;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
int numOfColumns = reader.FieldCount;
object[] row = null;
while (reader.Read())
{
row = new object[numOfColumns];
for (int i = 0; i < numOfColumns; ++i)
{
row[i] = reader[i];
}
result.Add(row);
}
}
}
}
}
return result;
}
}
@geleems I recommend investigating this with the application and Sql Server 2017 running on the same Ubuntu machine / VM.
I can confirm this issue as well. .Net core 2.0 and SQL server 2017 express on Ubuntu 16.04. The query returns about 5000 records in about 10s comparing about 1s on windows 10. The query itself joins 3 tables and about 10 fields
@aussieweever Thanks for the information. If possible, can you provide your sample code to reproduce the issue? It will be very helpful.
Tested against SQL Server 2017 with the sample test code. It tested select query for 150,000 rows 500 times. Here is the result:
Average Time Elapsed for Selecting 150000 Rows: 302.152 ms
Average Time Elapsed for Selecting Single Row: 0.002014347 ms
It seems there is gap in the measure of performance. I would really appreciate if anyone experiencing this issue provides a sample code for reproducing the issue.
@aussieweever So I was able to repro the issue. It happens when I run SqlClient in Ubuntu against SQL Server 2017 that resides in the same Ubuntu machine. It took almost 200s for fetching 150,000 rows for which Windows took about 300ms. I am currently working on debugging to find the cause.
Hi Geleems, thanks for the update. Yes, the SQL server is in the same Ubuntu machine. Following is my code doing the query, which should be quite normal.
public async Task<IEnumerable<CallRecord>> GetRecordsByConditions(CallRecordQueryParameters param)
{
var ret = _context.CallRecords
.Include(x => x.Agent)
.ThenInclude(a => a.Team)
.Include(x => x.InspectionTasks)
.AsQueryable();
if (param.startDateTime.HasValue)
{
var startDate = param.startDateTime.Value.Date;
ret = ret.Where(x => x.RecordStartTime >= startDate);
}
if (param.endDateTime.HasValue)
{
var endDate = param.endDateTime.Value.Date.AddDays(1);
ret = ret.Where(x => x.RecordEndTime < endDate);
}
if (param.agents != null && param.agents.Any())
ret = ret.Where(x => param.agents.Any(y=>y == x.AgentId));
if (param.callDirection.HasValue)
ret = ret.Where(x => x.Direction == param.callDirection);
if (param.callDisconnectionType.HasValue)
ret = ret.Where(x => x.DisconnectType == param.callDisconnectionType);
if (!string.IsNullOrWhiteSpace(param.calleeNumber))
ret = ret.Where(x => x.CalleePhoneNumber.Equals(param.calleeNumber));
if (!string.IsNullOrWhiteSpace(param.callerNumber))
ret = ret.Where(x => x.CallerPhoneNumber.Equals(param.callerNumber));
if (!string.IsNullOrWhiteSpace(param.extensionNumber))
ret = ret.Where(x => x.ExtensionNumber.Equals(param.extensionNumber));
if (param.minCallDurationInMinutes.HasValue)
ret = ret.Where(x =>
(x.RecordEndTime - x.RecordStartTime).TotalMinutes >= param.minCallDurationInMinutes);
//ret = ret.Where(x => DbFunctions.DiffMinutes(x.RecordStartTime, x.RecordEndTime) >= param.minCallDurationInMinutes);
if (param.maxCallDurationInMinutes.HasValue)
ret = ret.Where(x =>
(x.RecordEndTime - x.RecordStartTime).TotalMinutes <= param.maxCallDurationInMinutes);
//ret = ret.Where(x => DbFunctions.DiffMinutes(x.RecordStartTime, x.RecordEndTime) <= param.maxCallDurationInMinutes);
if (param.teams != null && param.teams.Any())
ret = ret.Where(x => param.teams.Any(y=>y == x.Agent.TeamId));
if (!param.includeInspected)
ret = ret.Where(x => !x.InspectionTasks.Any());
ret = ret.OrderBy(x => x.RecordStartTime);
if (param.totalRecords.HasValue)
ret = ret.Take(param.totalRecords.Value);
return await ret.ToListAsync();
}
Let me share one thing I found.
I tested again by select 8,000 rows against local SQL Server 2017 in Ubuntu 16.04 LTS. During testing, I could see there were lots of packets piled up in Send-Q of SQL Server, which implies SqlClient does not read the query result out of the queue fast enough.
gelee@GELEE-VM-UBU16A:~$ netstat --tcp
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 gelee-vm-ubu16a.g:49758 40.84.189.107:https TIME_WAIT
tcp 0 0 gelee-vm-ubu16a.g:33422 104.45.136.42:https TIME_WAIT
tcp 0 0 gelee-vm-ubu16a.gu:4000 10.135.11.23:53765 ESTABLISHED
tcp 0 2091520 GELEE-VM-UBU16:ms-sql-s localhost:46945 ESTABLISHED
tcp 0 0 localhost:36689 GELEE-VM-UBU16:ms-sql-s TIME_WAIT
Fetching 8,000 rows took 10,107 ms in total in my test. I drilled down to see which line consumed how much time, and I found this line consumed 9,456 ms in total in my test. https://github.com/dotnet/corefx/blob/5ac0f9aeaf02bac726e8c8067e835549e0148621/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParserStateObjectManaged.cs#L140
And that line eventually reaches to this line to read server response from Stream, which seems to be our biggest enemy.
https://github.com/dotnet/corefx/blob/3ccdcb103c83a056fb6f7cd4d4a161b028cba9aa/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNIPacket.cs#L280
This line of reading from the Stream took 9,456 ms, which tells the ReadSyncOverAsync() delay was mainly caused from this spot.
This delay does not happen when the same SqlCient is targeting remote SQL Server in Windows machine. (That is why I could not repro the issue at first time.) The line of reading Stream took 277 ms when targeting remote SQL Server in Windows, which means there is something wrong on local network stream in Linux.
@Petermarcu @karelz @danmosemsft It seems network team needs to be involved. Anyone of you knows whom I need to contact in network team?
@stephentoub can you help take a look at this?
@davidsh @DavidGoll as well.
@Petermarcu The best people to investigate this would be the owners of the SqlClient layer.
I believe that is @geleems who is asking for help :)
@davidsh Do you have any idea why reading stream from local server is so slow in Linux environment?
@davidsh Do you have any idea why reading stream from local server is so slow in Linux environment?
@stephentoub or @Priya91 are the Linux experts. They would be best to help answer those questions.
Also @wfurt is a Linux expert as well. cc: @karelz
@geleems, what is the actual type of stream here used in the stream.Read(_data, 0, _capacity); call? How was it constructed?
@stephentoub
It is System.Net.Sockets.NetworkStream
It is constructed when SNITcpHandle is constructed:
https://github.com/dotnet/corefx/blob/5ac0f9aeaf02bac726e8c8067e835549e0148621/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNITcpHandle.cs#L165-L181
It is System.Net.Sockets.NetworkStream
So SSL isn't enabled on this connection?
It seems network team needs to be involved.
While that could be true, I'm not yet convinced of it. Have you tried, for example, having SQL Server running and active on two different VMs, and then run the client on one of them to connect to the other? I'm wondering if potentially SQL Server does something to the machine that might cause other processes to suffer in a particular way, e.g. if what it saw for processor count was limited, that could impact thread availability, and I get very suspicious when I see a method name like "ReadSyncOverAsync".
Have you taken a wireshark trace or other form of network trace to see when/how/what packets are being sent between the client and server?