An exception has been raised that is likely due to a transient failure перевод
An exception has been raised that is likely due to a transient failure перевод
Ошибка при постоянном подключении к базе данных
Когда я запрашиваю из базы данных в непрерывном цикле, через некоторое время я получаю сообщение об ошибке:
An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy.
Нормально работает нормально.
Если вы используете EF Core, настройте повторную попытку при сбое для отказоустойчивых подключений:
При подключении к базе данных SQL вы должны учитывать временные сбои подключения. Эти сбои подключения могут произойти, например, при развертывании обновлений, сбое оборудования и т. Д. Ошибка, которую вы видите, указывает на то, что произошло одно из этих событий, поэтому ваше соединение было разорвано. Включение стратегии выполнения, предложенной Анбуджем, должно решить проблему.
Я публикую этот ответ, так как при поиске ответа на вопрос сталкиваюсь с множеством проблем. Ниже приводится подробное сообщение об ошибке, которое я получал:
Разделение ошибок на части, так как ошибка была слишком длинной:
В Azure есть уровни ценообразования, которые существенно различаются по производительности. Для этого они регулируют множество показателей производительности, например мощность процессора, количество запросов в минуту и т. Д.
Это означает, что если вы перейдете на свой уровень, ваши запросы начнут ставиться в очередь, поскольку мощность процессора / объем запросов слишком высоки для обработки. Это приводит к тайм-аутам, а затем лимит запросов увеличивается, поскольку запросы ожидают обработки. В конце концов, дело доходит до того, что база данных по существу выходит из строя.
Мой опыт показывает, что нижние уровни базы данных, такие как S0 и S1, недостаточно активны и не должны использоваться ни для чего, кроме разработки или очень простых сайтов.
На портале Azure есть несколько отличных инструментов, которые позволяют вам отлаживать то, что происходит с вашей базой данных, например графики ЦП, советник по индексам и аналитика производительности запросов.
Вот ссылки по теме:
Заключение:
Часть 2: Вам необходимо обновить подписку в Azure (если позволяет цена).
Я получаю эту ошибку, когда учетная запись, с которой я пытаюсь подключиться к базе данных, не имеет связанного пользователя в базе данных.
Я видел, что никто не ставил решение в случае Entity Framework, а не ядра EF. Самый простой способ реализовать SqlAzureExecutionStrategy:
Перейдите в файл Context.cs, который содержит: public partial class YourEntity : DbContext
добавить ссылку: using System.Data.Entity.SqlServer;
добавьте еще один класс в конец файла, содержащий следующий код:
Вы можете обратиться к этой документации для получения дополнительной информации.
Я хотел бы внести свой вклад в тех, кто, как и я, столкнулся с этой ошибкой, даже если они не находятся в ситуации, когда им приходится взаимодействовать с базой данных в Azure или на другой платформе в облаке.
В моем случае сценарий был таким: 2 экземпляра одной и той же программы (это служба Windows), которые вставляют записи в таблицу. Две особенности:
В этом сценарии одновременно все экземпляры служб пытаются записать одну и ту же таблицу, и каждая операция записи, выполняемая с помощью EF6, создает запрос, в котором есть очень конкретный выбор для извлечения и улучшения ключевого поля, которое оно представляет собой. Что-то вроде этого:
Этот тип записи приводит к ситуации параллелизма между двумя процессами (особенно когда таблица содержит около 5 миллионов записей), что побуждает механизм SQL разрешить один запрос и отменить другой. Интерпретация вызывающей программы в точности такова: « Возникло исключение, вероятно, из-за временного сбоя. Если вы подключаетесь к базе данных SQL Azure, рассмотрите возможность использования SqlAzureExecutionStrategy ».
Чтобы обойти проблему, мне пришлось отказаться от восстановления инкрементного идентификатора, назначенного новой записи, рассматривая таблицу как стек и сократив операцию записи до операции прямой вставки, используя:
В качестве альтернативы можно уточнить операцию с помощью двух операций записи, которые не включают анализатор EF TSQL, а также получить идентификатор, присвоенный последней добавленной записи.
Error when connect database continuously
When I am querying from database in continuous looping, after some time I get an error :
An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy.
Normally it is working fine.
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you are using EF Core configure retry on failure for resilient connections :
When connecting to a SQL Database you have to account for transient connection failures. These connection failures can happen for example when updates are rolled out, hardware fails etc. The error you see indicates that one of these things happened which is why your connection was dropped. Enabling an Execution Strategy as suggested by Anbuj should solve the issue.
I could see that nobody put the solution in case of Entity Framework, and not EF core. The easiest way to implement SqlAzureExecutionStrategy is:
Go to Context.cs file that contains: public partial class YourEntity : DbContext
add the reference: using System.Data.Entity.SqlServer;
add another class at the end of the file containing the following code:
You may refer to this documentation for more information.
I am posting this answer as I face lot of issue while researching the answer of the issue. Below is the detailed error message I was getting:
Dividing the errors in the parts as the error was too long:
After research I found that it was related to the limits of Azure SQL Database maximum logins. I was using ‘Basic‘ service tire and max concurrent users can login with that is 30.
Azure has pricing tiers that have quite dramatic differences in performance. To achieve that, they throttle a lot of performance metrics, e.g. CPU power, requests per minute, etc.
This means that if you’re pushing over your tier, your requests will start getting queued up as the CPU power / volume of requests is too high to process. This results in timeouts and then the request limit grows as requests wait to be processed. Eventually, it gets to the point where the database essentially goes down.
My experience is that the lower database levels, such as S0 and S1, are under-powered and shouldn’t be used for anything other than development or very basic sites.
There are some great tools in the Azure portal that allow you to debug what is going on with your database, such as the CPU graphs, index advisor and query performance insights.
Here are the related links:
Conclusion:
Part 2: You need to upgrade the subscription in the Azure(if price permits).
I would like to give my contribution to those who, like me, have encountered this error even though they are not in the situation of having to interact with a database on Azure or on another platform in the cloud.
The first goal is to get to the exact origin of the problem; like me many will have collided with the exception text and a mile-long stack trace string. It was useful for me to process the matryoshkas of the InnerExceptions to get to the real message that the database provider issues before closing the connection (which was active at the time of the message!). Alternatively, if possible, it is sufficient to monitor the transactions towards the database from an external tool that allows you to check any errors connected to the TSQL operations in progress (eg SQL Server Profiler).
In my case the scenario was this: 2 instances of the same program (it is a Windows service) that insert records inside a table. Two peculiarities:
In this scenario, concurrently, all services’s instances try to write the same table and each write operation performed with EF6 produces a query that has a very particular select within it for retrieving and enhancing the key field it represents identity. Something like this:
This type of writing leads to a situation of concurrency between the two processes (expecially when table have about 5M records), which induce the SQL engine to resolve one request and cancel the other. The interpretation of the calling program is precisely «An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy.«
To get around the problem I had to make a waiver on the recovery of the incremental id assigned to the new record, treating the table as a stack and reducing the write operation to a direct insert operation using:
Alternatively, it is possible to refine the operation with two write operations that do not involve the EF TSQL parser and also retrieve the identifier assigned to the last added record.
TheCodeBuzz
Best Practices for Software Development
Consider Enabling transient error resiliency by adding EnableRetryOnFailure
Error: An exception has been raised that is likely due to a transient failure Consider enabling transient error resiliency by adding EnableRetryOnFailure()
Issue Description
Entity Framework Core DB execution gives the below error,
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding ‘EnableRetryOnFailure()’ to the ‘UseSqlServer’ call.
Resolution
Transient error issues may be caused due to network connectivity issues or the temporary unavailability of a service, timeout issues, etc.
An application using shared resources in a shared environment, especially in the cloud environment is more sensitive to transient faults.
Transient faults are generally temporary in nature and often get corrected on its own provided you enable retry pattern.
To fix the issue, Please enable the Retry option using any of the below methods.
Configure EnableRetry within Startup.cs as below,
Please set the EnableRetry option using the OnConfiguring() method within your DBContext class as below.
Additionally, EnableRetryOnFailure() can be used for specifying the option like Maximum retry count or maximum retry delay or error numbers to add, etc.
Custom Execution strategy
Transient errors can also be fixed using the Custom Execution strategy.
If you wish to register a custom execution strategy then please see the below article with a sample execution strategy with custom patterns.
Database operation handling Transactions for Example- like defined with BeginTransaction() scope, etc. needs to be addressed differently i.e manually invoking the Execution strategy with a delegate. Such an execution strategy should encapsulate everything that needs to be executed.
References:
Hope this helps you to fix the issue. Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
I am using EF Core for an ASP.NET website. In one method I have about 7 complex queries similar to (simple example):
This usually works, but occasionally the page crashes with:
I know I could add ‘EnableRetryOnFailure()’ but I am worried that the true cause is that it is running multiple queries at the same time. Is there a way to make this safer and more efficient?
I’ve tried looking up guides, but none of them cover what to do if you are trying lots of queries at once.
1 Answer 1
Honestly, I think this probably has less to do with your code and more to do with some sort of network or database issue. While there’s ways this code could be improved, there’s really no reason it shouldn’t consistently work, as-is.
That said, you’re blocking on all these queries, which is never a good idea. Everything EF Core does is async. The sync methods merely block on the async ones, and exist only for scenarios where async cannot be used, such as event delegates in desktop apps and such. In short, you should always use the async methods, unless you run into a specific situation where you can’t. In an ASP.NET Core application, there is no such situation, so async should always be used at all times. Long and short, use ToListAsync instead of ToList and await each line.
Next, there’s no point in your where clauses. Whether you select many on only items that have dogs, for example, or all items, whether or not they have dogs, you still get back the same results. All of this will be run at the database, either way, so there isn’t even a performance benefit to one approach or the other. You also don’t need to use Include if you’re selecting from the relationships. EF is smart enough to issue the joins based on the data it needs to return.
An exception has been raised that is likely due to a transient failure перевод
Question
We have multiple database in one azure. At the time of having only one database in azure, it doesn’t have connection failure at any time. But after adding the database one by one. Its getting database connection error randomly.
The below exception we got.
An exception occurred while initializing the database. See the InnerException for details.
An exception has been raised that is likely due to a transient failure. If you are connecting to a SQL Azure database consider using SqlAzureExecutionStrategy
Can anyone update on this?
All replies
I agree with MasaSam, your case more related to Azure SQL Database, I will help move your case to
Microsoft Azure > Azure SQL Database forum for better support.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.
Could you please provide me with some details of your retry logic. There are a couple of
ways in which you can go about implementing the retry logic:
1) You are currently using entity framework (EF) to handle this. I think you are using the
‘SqlAzureExecutionStrategy’ in the entity framework which in turn calls the
‘DbExecutionStrategy’ which has exponential backoff as the inbuilt mechanism.
3) If you are getting a lots of time out then timeout recommended is 30 sec for SQL
Azure.
Источники информации:
- http://stackoverflow.com/questions/29840282/error-when-connect-database-continuously
- http://www.thecodebuzz.com/enabling-transient-error-resiliency-enableretryonfailure/
- http://stackoverflow.com/questions/60972275/asp-net-core-3-ef-framework-transient-failure-when-running-lots-of-queries
- http://social.technet.microsoft.com/Forums/en-US/a3ed3440-bd29-456a-a2ee-a7b2d1f9ffa0/when-connection-database-an-exception-has-been-raised-that-is-likely-due-to-a-transient-failure?forum=ssdsgetstarted