Ошибка на транспортном уровне при отправке запроса серверу sql

Removing Connections

The connection pooler removes a connection from the pool after it has
been idle for a long time, or if the pooler detects that the
connection with the server has been severed.

Note that a severed connection can be detected only after attempting
to communicate with the server. If a connection is found that is no
longer connected to the server, it is marked as invalid.

Invalid connections are removed from the connection pool only when
they are closed or reclaimed.

If a connection exists to a server that has disappeared, this
connection can be drawn from the pool even if the connection pooler
has not detected the severed connection and marked it as invalid.

This is the case because the overhead of checking that the connection
is still valid would eliminate the benefits of having a pooler by
causing another round trip to the server to occur.

When this occurs, the first attempt to use the connection will detect
that the connection has been severed, and an exception is thrown.

Basically what you are seeing is that exception in the last sentence.

A connection is taken from the connection pool, the application does
not know that the physical connection is gone, an attempt to use it is
done under the assumption that the physical connection is still there.

And you get your exception.

There are a few common reasons for this.

  1. The server has been restarted, this will close the existing connections.

In this case, have a look at the SQL Server log, usually found at:
C:Program FilesMicrosoft SQL Server\MSSQLLOG

If the timestamp for startup is very recent, then we can suspect that
this is what caused the error. Try to correlate this timestamp with
the time of exception.

2009-04-16 11:32:15.62 Server Logging SQL Server messages in file
‘C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLLOGERRORLOG’.

  1. Someone or something has killed the SPID that is being used.

Again, take a look in the SQL Server log. If you find a kill, try to
correlate this timestamp with the time of exception.

2009-04-16 11:34:09.57 spidXX Process ID XX was killed by
hostname xxxxx, host process ID XXXX.

  1. There is a failover (in a mirror setup for example) again, take a look in the SQL Server log.

If there is a failover, try to correlate this timestamp with the time
of exception.

2009-04-16 11:35:12.93 spidXX The mirrored database “” is changing roles from “PRINCIPAL” to “MIRROR” due to
Failover.

Every now and then in a high volume .NET application, you might see this exception when you try to execute a query:

System.Data.SqlClient.SqlException: A transport-level error has
occurred when sending the request to the server.

According to my research, this is something that «just happens» and not much can be done to prevent it. It does not happen as a result of a bad query, and generally cannot be duplicated. It just crops up maybe once every few days in a busy OLTP system when the TCP connection to the database goes bad for some reason.

I am forced to detect this error by parsing the exception message, and then retrying the entire operation from scratch, to include using a new connection. None of that is pretty.

Anybody have any alternate solutions?

nobody's user avatar

nobody

10.9k8 gold badges43 silver badges63 bronze badges

asked Aug 19, 2008 at 17:36

Eric Z Beard's user avatar

Eric Z BeardEric Z Beard

37.6k27 gold badges99 silver badges145 bronze badges

5

I posted an answer on another question on another topic that might have some use here. That answer involved SMB connections, not SQL. However it was identical in that it involved a low-level transport error.

What we found was that in a heavy load situation, it was fairly easy for the remote server to time out connections at the TCP layer simply because the server was busy. Part of the reason was the defaults for how many times TCP will retransmit data on Windows weren’t appropriate for our situation.

Take a look at the registry settings for tuning TCP/IP on Windows. In particular you want to look at TcpMaxDataRetransmissions and maybe TcpMaxConnectRetransmissions. These default to 5 and 2 respectively, try upping them a little bit on the client system and duplicate the load situation.

Don’t go crazy! TCP doubles the timeout with each successive retransmission, so the timeout behavior for bad connections can go exponential on you if you increase these too much. As I recall upping TcpMaxDataRetransmissions to 6 or 7 solved our problem in the vast majority of cases.

Community's user avatar

answered Oct 16, 2008 at 7:50

Tim Farley's user avatar

This blog post by Michael Aspengren explains the error message «A transport-level error has occurred when sending the request to the server.»

answered Jan 29, 2010 at 7:20

Magnus Lindhe's user avatar

Magnus LindheMagnus Lindhe

7,1275 gold badges47 silver badges60 bronze badges

1

To answer your original question:

A more elegant way to detect this particular error, without parsing the error message, is to inspect the Number property of the SqlException.

(This actually returns the error number from the first SqlError in the Errors collection, but in your case the transport error should be the only one in the collection.)

answered Oct 1, 2008 at 5:57

Daniel Fortunov's user avatar

Daniel FortunovDaniel Fortunov

43.1k26 gold badges80 silver badges106 bronze badges

0

I had the same problem albeit it was with service requests to a SQL DB.

This is what I had in my service error log:


System.Data.SqlClient.SqlException: A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 — An existing connection was forcibly closed by the remote host.)


I have a C# test suite that tests a service. The service and DB were both on external servers so I thought that might be the issue. So I deployed the service and DB locally to no avail. The issue continued. The test suite isn’t even a hard pressing performance test at all, so I had no idea what was happening. The same test was failing each time, but when I disabled that test, another one would fail continuously.

I tried other methods suggested on the Internet that didn’t work either:

  • Increase the registry values of TcpMaxDataRetransmissions and TcpMaxConnectRetransmissions.
  • Disable the «Shared Memory» option within SQL Server Configuration Manager under «Client Protocols» and sort TCP/IP to 1st in the list.
  • This might occur when you are testing scalability with a large number of client connection attempts. To resolve this issue, use the regedit.exe utility to add a new DWORD value named SynAttackProtect to the registry key HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters with value data of 00000000.

My last resort was to use the old age saying «Try and try again». So I have nested try-catch statements to ensure that if the TCP/IP connection is lost in the lower communications protocol that it does’t just give up there but tries again. This is now working for me, however it’s not a very elegant solution.

answered Jul 23, 2010 at 15:19

Martin's user avatar

MartinMartin

10.3k11 gold badges63 silver badges83 bronze badges

1

use Enterprise Services with transactional components

answered Jul 23, 2010 at 15:24

Jon Black's user avatar

Jon BlackJon Black

16.2k5 gold badges43 silver badges42 bronze badges

I have seen this happen in my own environment a number of times. The client application in this case is installed on many machines. Some of those machines happen to be laptops people were leaving the application open disconnecting it and then plugging it back in and attempting to use it. This will then cause the error you have mentioned.

My first point would be to look at the network and ensure that servers aren’t on DHCP and renewing IP Addresses causing this error. If that isn’t the case then you have to start trawlling through your event logs looking for other network related.

Unfortunately it is as stated above a network error. The main thing you can do is just monitor the connections using a tool like netmon and work back from there.

Good Luck.

Bill the Lizard's user avatar

answered Oct 31, 2008 at 6:30

Dale Wright's user avatar

Dale WrightDale Wright

1192 silver badges8 bronze badges

I’m using reliability layer around my DB commands (abstracted away in the repository interfaece). Basically that’s just code that intercepts any expected exception (DbException and also InvalidOperationException, that happens to get thrown on connectivity issues), logs it, captures statistics and retries everything again.

With that reliability layer present, the service has been able to survive stress-testing gracefully (constant dead-locks, network failures etc). Production is far less hostile than that.

PS: There is more on that here (along with a simple way to define reliability with the interception DSL)

answered Oct 1, 2008 at 4:53

Rinat Abdullin's user avatar

Rinat AbdullinRinat Abdullin

23k8 gold badges57 silver badges80 bronze badges

I had the same problem. I asked my network geek friends, and all said what people have replied here: Its the connection between the computer and the database server. In my case it was my Internet Service Provider, or there router that was the problem. After a Router update, the problem went away. But do you have any other drop-outs of internet connection from you’re computer or server? I had…

answered Oct 1, 2008 at 6:05

Jesper Blad Jensen's user avatar

I experienced the transport error this morning in SSMS while connected to SQL 2008 R2 Express.

I was trying to import a CSV with rn. I coded my row terminator for 0x0d0x0a. When I changed it to 0x0a, the error stopped. I can change it back and forth and watch it happen/not happen.

 BULK INSERT #t1 FROM 'C:123Import123.csv' WITH 
      ( FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0d0x0a' )

I suspect I am not writing my row terminator correctly because SQL parses one character at a time right while I’m trying to pass two characters.

Anyhow, this error is 4 years old now, but it may provide a bit of information for the next user.

answered Mar 13, 2014 at 20:02

Phillip Deneka's user avatar

Phillip DenekaPhillip Deneka

2211 gold badge3 silver badges12 bronze badges

2

I just wanted to post a fix here that worked for our company on new software we’ve installed. We were getting the following error since day 1 on the client log file: Server was unable to process request. —> A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 — The semaphore timeout period has expired.) —> The semaphore timeout period has expired.

What completely fixed the problem was to set up a link aggregate (LAG) on our switch. Our Dell FX1 server has redundant fiber lines coming out of the back of it. We did not realize that the switch they’re plugged into needed to have a LAG configured on those two ports. See details here: https://docs.meraki.com/display/MS/Switch+Ports#SwitchPorts-LinkAggregation

naivists's user avatar

naivists

32.6k5 gold badges61 silver badges85 bronze badges

answered Dec 3, 2015 at 16:10

J. J.'s user avatar

Removing Connections

The connection pooler removes a connection from the pool after it has
been idle for a long time, or if the pooler detects that the
connection with the server has been severed.

Note that a severed connection can be detected only after attempting
to communicate with the server. If a connection is found that is no
longer connected to the server, it is marked as invalid.

Invalid connections are removed from the connection pool only when
they are closed or reclaimed.

If a connection exists to a server that has disappeared, this
connection can be drawn from the pool even if the connection pooler
has not detected the severed connection and marked it as invalid.

This is the case because the overhead of checking that the connection
is still valid would eliminate the benefits of having a pooler by
causing another round trip to the server to occur.

When this occurs, the first attempt to use the connection will detect
that the connection has been severed, and an exception is thrown.

Basically what you are seeing is that exception in the last sentence.

A connection is taken from the connection pool, the application does
not know that the physical connection is gone, an attempt to use it is
done under the assumption that the physical connection is still there.

And you get your exception.

There are a few common reasons for this.

  1. The server has been restarted, this will close the existing connections.

In this case, have a look at the SQL Server log, usually found at:
C:Program FilesMicrosoft SQL Server\MSSQLLOG

If the timestamp for startup is very recent, then we can suspect that
this is what caused the error. Try to correlate this timestamp with
the time of exception.

2009-04-16 11:32:15.62 Server Logging SQL Server messages in file
‘C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLLOGERRORLOG’.

  1. Someone or something has killed the SPID that is being used.

Again, take a look in the SQL Server log. If you find a kill, try to
correlate this timestamp with the time of exception.

2009-04-16 11:34:09.57 spidXX Process ID XX was killed by
hostname xxxxx, host process ID XXXX.

  1. There is a failover (in a mirror setup for example) again, take a look in the SQL Server log.

If there is a failover, try to correlate this timestamp with the time
of exception.

2009-04-16 11:35:12.93 spidXX The mirrored database “” is changing roles from “PRINCIPAL” to “MIRROR” due to
Failover.

У меня была та же проблема, хотя это было с запросами на обслуживание к SQL DB.

Вот что было в моем сервисном журнале ошибок:


System.Data.SqlClient.SqlException: при отправке запроса на сервер произошла ошибка транспортного уровня. (provider: TCP Provider, error: 0-существующее соединение было принудительно закрыто удаленным хостом.)


У меня есть набор тестов C#, который тестирует службу. Служба и DB были оба на внешних серверах, поэтому я подумал, что это может быть проблемой. Поэтому я развернул службу и DB локально, но безрезультатно. Проблема продолжалась. Набор тестов даже не является жестким тестом производительности, поэтому я понятия не имел, что происходит. Один и тот же тест проваливался каждый раз, но когда я отключал этот тест, другой проваливался непрерывно.

Я попробовал другие методы, предложенные в Интернете, которые тоже не сработали:

  • Увеличьте значения реестра TcpMaxDataRetransmissions и TcpMaxConnectRetransmissions .
  • Отключите параметр «Shared Memory» в Диспетчере конфигурации сервера SQL в разделе «Client Protocols» и отсортируйте TCP/IP на 1-е место в списке.
  • Это может произойти при тестировании масштабируемости с большим количеством попыток подключения клиента. Чтобы устранить эту проблему, используйте утилиту regedit.exe для добавления нового значения DWORD с именем SynAttackProtect в раздел реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters с данными значения 00000000.

Моим последним средством было использовать старую поговорку «Try and try again». Поэтому я вложил операторы try-catch, чтобы гарантировать, что если соединение TCP/IP потеряно в Нижнем протоколе связи,то он не просто сдается, но пытается снова. Теперь это работает для меня, однако это не очень элегантное решение.

Проблемы

Рассмотрим следующий сценарий.

  • Клиентское приложение подключается к экземпляру Microsoft SQL Server 2008 или Microsoft SQL Server 2008 R2.

  • Время ожидания запроса происходит, когда SQL Server сбрасывает соединение между SQL Server 2008 или SQL Server 2008 R2 и клиентским приложением. Кроме того, клиентское приложение отправляет сигнал предупреждения явным образом, отменяя запрос к экземпляру SQL Server.

В этом случае SQL Server выполняет принудительное закрытие соединения, и вы можете получить одно из следующих сообщений об ошибке:

  • Сообщение об ошибке 1

    При текущей команде возникла серьезная ошибка. Результаты, если таковые имеются, должны быть удалены.

  • Сообщение об ошибке 2

    Произошла ошибка на транспортном уровне при получении результатов с сервера. (поставщик: поставщик услуг TCP; ошибка: 0-существующее подключение было принудительно закрыто удаленным узлом.)

Кроме того, в файле Errorlog сервера SQL Server регистрируется сообщение об ошибке, похожее на приведенное ниже.

<Дата><время> <SPID> ошибка: 18056, серьезность: 20, состояние: 29. <Дата><время> <SPID> клиент не смог повторно использовать сеанс с <SPID>, который был сброшен для группировки подключений. КОД ошибки — 29. Эта ошибка может быть вызвана тем, что предыдущая операция завершилась сбоем. Перед сообщением об ошибке Проверьте журналы ошибок на предмет невыполненных операций сразу.

Решение

Сведения о накопительном пакете обновления

SQL Server 2008 R2 с пакетом обновления 2 (SP2)

Исправление для этой проблемы впервые выпущено в накопительном обновлении 1 для SQL Server 2008 R2 с пакетом обновления 2. Для получения дополнительных сведений о том, как получить этот накопительный пакет обновления, щелкните следующий номер статьи базы знаний Майкрософт:

2720425 Накопительный пакет обновления 1 для SQL Server 2008 R2 с пакетом обновления 2 (SP2)Примечание. Поскольку сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008 R2. Рекомендуется установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2730301 Сборки SQL Server 2008 R2, выпущенные после выпуска SQL Server 2008 R2 с пакетом обновления 2 (SP2)

SQL Server 2008 с пакетом обновления 3

Исправление для этой проблемы впервые выпущено в накопительном обновлении 6 для SQL Server 2008 с пакетом обновления 3. Чтобы получить дополнительные сведения об этом накопительном пакете обновления, щелкните следующий номер статьи базы знаний Майкрософт:

2715953 Накопительный пакет обновления 6 для SQL Server 2008 с пакетом обновления 3 (SP3)Примечание. Так как сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008. Корпорация Microsoft рекомендует установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2629969 Сборки SQL Server 2008, выпущенные после выпуска пакета обновления 3 (SP3) для SQL Server 2008 Исправления Microsoft SQL Server 2008 создаются для конкретных пакетов обновления для SQL Server. Вы должны применить исправление SQL Server 2008 с пакетом обновления 3 (SP3) к установке SQL Server 2008 с пакетом обновления 3 (SP3). По умолчанию любое исправление, предоставленное в пакете обновления SQL Server, входит в следующий пакет обновления для SQL Server.

SQL Server 2008 R2

Исправление для этой проблемы впервые выпущено в накопительном обновлении 14. Для получения дополнительных сведений о том, как получить этот накопительный пакет обновления для SQL Server 2008 R2, щелкните следующий номер статьи базы знаний Майкрософт:

2703280 Накопительный пакет обновления 14 для SQL Server 2008 R2 Примечание. Поскольку сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008 R2. Рекомендуется установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

981356 Сборки SQL Server 2008 R2, выпущенные после выпуска SQL Server 2008 R2

SQL Server 2008 с пакетом обновления 1

Исправление для этой проблемы впервые выпущено в накопительном обновлении 14 для SQL Server 2008 с пакетом обновления 1 (SP1). Чтобы получить дополнительные сведения об этом накопительном пакете обновления, щелкните следующий номер статьи базы знаний Майкрософт:

2527187 Накопительный пакет обновления 14 для SQL Server 2008 с пакетом обновления 1 (SP1)Примечание. Так как сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008. Корпорация Microsoft рекомендует установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

956909 Сборки SQL Server 2008, выпущенные после выпуска SQL Server 2008 Исправления Microsoft SQL Server 2008 создаются для конкретных пакетов обновления для SQL Server. Вы должны применить исправление для SQL Server 2008 с пакетом обновления 1 (SP1) к установке SQL Server 2008 с пакетом обновления 1. По умолчанию любое исправление, предоставленное в пакете обновления SQL Server, входит в следующий пакет обновления для SQL Server.

SQL Server 2008 с пакетом обновления 2

Исправление для этой проблемы впервые выпущено в накопительном обновлении 10 для SQL Server 2008 с пакетом обновления 2. Чтобы получить дополнительные сведения об этом накопительном пакете обновления, щелкните следующий номер статьи базы знаний Майкрософт:

2696625 Накопительный пакет обновления 10 для SQL Server 2008 с пакетом обновления 2 (SP2)Примечание. Так как сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008. Корпорация Microsoft рекомендует установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2402659 Сборки SQL Server 2008, выпущенные после выпуска пакета обновления 2 (SP2) для SQL Server 2008 Исправления Microsoft SQL Server 2008 создаются для конкретных пакетов обновления для SQL Server. Необходимо применить исправление для SQL Server 2008 с пакетом обновления 2 (SP2) к установке SQL Server 2008 с пакетом обновления 2. По умолчанию любое исправление, предоставленное в пакете обновления SQL Server, входит в следующий пакет обновления для SQL Server.

SQL Server 2008 R2 с пакетом обновления 1 (SP1)

Исправление для этой проблемы впервые выпущено в накопительном обновлении 6 для SQL Server 2008 R2 с пакетом обновления 1 (SP1). Для получения дополнительных сведений о том, как получить этот накопительный пакет обновления, щелкните следующий номер статьи базы знаний Майкрософт:

2679367 Накопительный пакет обновления 6 для SQL Server 2008 R2 с пакетом обновления 1 (SP1)Примечание. Поскольку сборки являются кумулятивными, каждый новый выпуск исправлений содержит все исправления и все исправления безопасности, которые были включены в предыдущий выпуск исправлений для SQL Server 2008 R2. Рекомендуется установить последнюю версию исправления, которая включает это исправление. Дополнительные сведения см. в следующей статье базы знаний Майкрософт:

2567616 Сборки SQL Server 2008 R2, выпущенные после выпуска SQL Server 2008 R2 с пакетом обновления 1 (SP1)

Статус

Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».

Дополнительная информация

Дополнительные сведения об этой проблеме, включая шаги по устранению неполадок, приведены в следующей записи блога из команды службы SQL Server эскалации:

http://blogs.msdn.com/b/psssql/archive/2010/05/05/error-18056-can-be-unwanted-noise-in-certain-scenarios.aspx

  • Ошибка на часах g917510
  • Ошибка на форд мондео 4 p0132
  • Ошибка на цифровой приставке 05d
  • Ошибка на форд куга p0234
  • Ошибка на хоноре при включении