Azure SQL 查询不活动后超时

Azure SQL Timeout after query inactivity

我的托管 Azure SQL 实例经常出现超时。当一段时间内未发生查询 activity 时,预计 return 500-2000 行之间的第一个查询将使用我的定价层(S2 50 DTU 计划)中的所有可用 DTU,并且总是导致以下异常:

System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (258): The wait operation timed out
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
ClientConnectionId:903324e4-4eba-4522-bae8-228a23c0e51c
Error Number:-2,State:0,Class:11
ClientConnectionId before routing:24ca7fb2-4c3b-44ad-b393-d8cda9dda172

紧接着执行相同的查询时,服务器立即响应。可能是因为最近的查询已加载到内存中。 SQL 服务器用于 IoT 设置,因此来自设备的数据流(批量插入)全天不断发生。我尝试通过让 Azure Functions 每小时执行一次查询以将经常访问的数据加载到内存中来解决问题,但这只会解决我在 Azure Functions 中查询的特定实体的问题。根据执行计划,我所有的查询都使用了正确的索引。

我认为实施重试策略不是一个可接受的解决方案。在我看来,这只会进一步降低用户体验。有没有人对这个问题有任何经验?

编辑: 执行计划在这里: https://www.brentozar.com/pastetheplan/?id=rJQvb7tRm

实际执行计划显示 1187 行被 DeviceUniqueIdentifier 聚集索引键上的聚集索引查找读取,即使没有行满足其他条件。将 InstanceIdNVEControllerTimestamp 添加到聚簇索引键将避免不必要地接触这些行。

一般来说,支持 returns 所有列的简单查询的最佳索引是聚集索引,首先是等式谓词键列(DeviceUniqueIdentifierInstanceId),然后是不等式列(NVEControllerTimestamp 上的范围搜索)。

您可以使用 CREATE INDEX...WITH (DROP_EXISTING = ON) 将额外的列添加到现有聚集索引。