适用于 Azure Cosmos DB 和 .NET SDK v2 的性能提示Performance tips for Azure Cosmos DB and .NET SDK v2

Azure Cosmos DB 是一个快速、弹性的分布式数据库,可以在提供延迟与吞吐量保证的情况下无缝缩放。Azure Cosmos DB is a fast and flexible distributed database that scales seamlessly with guaranteed latency and throughput. 凭借 Azure Cosmos DB,无需对体系结构进行重大更改或编写复杂的代码即可缩放数据库。You don't have to make major architecture changes or write complex code to scale your database with Azure Cosmos DB. 扩展和缩减操作就像执行单个 API 调用一样简单。Scaling up and down is as easy as making a single API call. 若要了解详细信息,请参阅如何预配容器吞吐量如何预配数据库吞吐量To learn more, see how to provision container throughput or how to provision database throughput. 但是,由于 Azure Cosmos DB 是通过网络调用访问的,因此,使用 SQL .NET SDK 时可以通过进行客户端优化来获得最高性能。But because Azure Cosmos DB is accessed via network calls, there are client-side optimizations you can make to achieve peak performance when you use the SQL .NET SDK.

因此,如果你尝试改善数据库性能,请考虑以下选项:So, if you're trying to improve your database performance, consider these options:

升级到 .NET V3 SDKUpgrade to the .NET V3 SDK

.NET v3 SDK 已发布。The .NET v3 SDK is released. 如果使用 .NET v3 SDK,请参阅 .NET v3 性能指南了解以下信息:If you use the .NET v3 SDK, see the .NET v3 performance guide for the following information:

  • 默认为“直接 TCP”模式Defaults to Direct TCP mode
  • 流 API 支持Stream API support
  • 支持自定义序列化程序以允许使用 System.Text.JSONSupport custom serializer to allow System.Text.JSON usage
  • 集成的批处理和批量操作支持Integrated batch and bulk support

托管方面的建议Hosting recommendations

对于查询密集型工作负载,请使用 Windows 64 位主机处理,而不要使用 Linux 或 Windows 32 位主机处理For query-intensive workloads, use Windows 64-bit instead of Linux or Windows 32-bit host processing

我们建议使用 Windows 64 位主机处理来改善性能。We recommend Windows 64-bit host processing for improved performance. SQL SDK 包含一个本机 ServiceInterop.dll,用于在本地分析和优化查询。The SQL SDK includes a native ServiceInterop.dll to parse and optimize queries locally. ServiceInterop.dll 仅在 Windows x64 平台上受支持。ServiceInterop.dll is supported only on the Windows x64 platform. 对于不支持 ServiceInterop.dll 的 Linux 和其他平台,将对网关发出附加的网络调用以获取优化的查询。For Linux and other unsupported platforms where ServiceInterop.dll isn't available, an additional network call is made to the gateway to get the optimized query. 以下类型的应用程序默认使用 32 位主机处理。The following types of applications use 32-bit host processing by default. 若要将主机处理更改为 64 位处理,请根据应用程序的类型执行以下步骤:To change host processing to 64-bit processing, follow these steps, based on the type of your application:

  • 对于可执行应用程序,可以在“项目属性”窗口中的“版本”选项卡上,通过将平台目标设置为“x64”来更改主机处理。 For executable applications, you can change host processing by setting the platform target to x64 in the Project Properties window, on the Build tab.

  • 对于基于 VSTest 的测试项目,可以通过在 Visual Studio“测试”菜单中选择“测试” > “测试设置” > “默认处理器体系结构为 X64”,来更改主机处理。 For VSTest-based test projects, you can change host processing by selecting Test > Test Settings > Default Processor Architecture as X64 on the Visual Studio Test menu.

  • 对于本地部署的 ASP.NET Web 应用程序,可以通过在“工具” > “选项” > “项目和解决方案” > “Web 项目”下选择“对网站和项目使用 IIS Express 的 64 位版”,来更改主机处理。 For locally deployed ASP.NET web applications, you can change host processing by selecting Use the 64-bit version of IIS Express for web sites and projects under Tools > Options > Projects and Solutions > Web Projects.

  • 对于部署在 Azure 上的 ASP.NET Web 应用程序,可以通过在 Azure 门户上的“应用程序设置”中选择“64 位”平台,来更改主机处理。 For ASP.NET web applications deployed on Azure, you can change host processing by selecting the 64-bit platform in Application settings in the Azure portal.

备注

新的 Visual Studio 项目默认设置为“任何 CPU”。By default, new Visual Studio projects are set to Any CPU. 我们建议将项目设置为“x64”,使其不会切换到“x86”。 We recommend that you set your project to x64 so it doesn't switch to x86. 如果添加了仅限 x86 的依赖项,则设置为“任何 CPU”的项目可以轻松切换到“x86”。 A project set to Any CPU can easily switch to x86 if an x86-only dependency is added.
ServiceInterop.dll 所处的文件夹必须是在其中执行 SDK DLL 的文件夹。ServiceInterop.dll needs to be in the folder that the SDK DLL is being executed from. 仅当你手动复制 DLL 或使用自定义的生成/部署系统时,此位置才是一个考虑因素。This should be a concern only if you manually copy DLLs or have custom build/deployment systems.

启用服务器端垃圾回收 (GC)Turn on server-side garbage collection (GC)

在某些情况下,降低垃圾回收的频率可能会有帮助。Reducing the frequency of garbage collection can help in some cases. 在 .NET 中,将 gcServer 设置为 trueIn .NET, set gcServer to true.

横向扩展客户端工作负载Scale out your client workload

如果以高吞吐量级别(大于 50,000 RU/秒)进行测试,客户端应用程序可能成为瓶颈,因为计算机的 CPU 或网络利用率将达到上限。If you're testing at high throughput levels (more than 50,000 RU/s), the client application could become the bottleneck due to the machine capping out on CPU or network utilization. 如果达到此上限,可以跨多个服务器横向扩展客户端应用程序以继续进一步推送 Azure Cosmos DB 帐户。If you reach this point, you can continue to push the Azure Cosmos DB account further by scaling out your client applications across multiple servers.

备注

CPU 使用率高可能会导致延迟增大和请求超时异常。High CPU usage can cause increased latency and request timeout exceptions.

网络Networking

连接策略:使用直接连接模式Connection policy: Use direct connection mode

客户端连接到 Azure Cosmos DB 的方式对性能有重大影响,尤其是在观察到的客户端延迟方面。How a client connects to Azure Cosmos DB has important performance implications, especially for observed client-side latency. 可以使用这两个重要配置设置来配置客户端连接策略:连接模式和连接协议。There are two key configuration settings available for configuring client connection policy: the connection mode and the connection protocol. 两种可用模式:The two available modes are:

* <span data-ttu-id="4bb63-151">网关模式(默认)</span><span class="sxs-lookup"><span data-stu-id="4bb63-151">Gateway mode (Default)</span></span>

    <span data-ttu-id="4bb63-152">网关模式受所有 SDK 平台支持并已配置为 [Microsoft.Azure.DocumentDB SDK](sql-api-sdk-dotnet.md) 的默认设置。</span><span class="sxs-lookup"><span data-stu-id="4bb63-152">Gateway mode is supported on all SDK platforms and is the configured default for the [Microsoft.Azure.DocumentDB SDK](sql-api-sdk-dotnet.md).</span></span> <span data-ttu-id="4bb63-153">如果应用程序在有严格防火墙限制的企业网络中运行,则网关模式是最佳选择,因为它使用标准 HTTPS 端口与单个终结点。</span><span class="sxs-lookup"><span data-stu-id="4bb63-153">If your application runs within a corporate network with strict firewall restrictions, gateway mode is the best choice because it uses the standard HTTPS port and a single endpoint.</span></span> <span data-ttu-id="4bb63-154">但是,对于性能的影响是:每次在 Azure Cosmos DB 中读取或写入数据时,网关模式都涉及到额外的网络跃点。</span><span class="sxs-lookup"><span data-stu-id="4bb63-154">The performance tradeoff, however, is that gateway mode involves an additional network hop every time data is read from or written to Azure Cosmos DB.</span></span> <span data-ttu-id="4bb63-155">因此,直接模式因为网络跃点较少,可以提供更好的性能。</span><span class="sxs-lookup"><span data-stu-id="4bb63-155">So direct mode offers better performance because there are fewer network hops.</span></span> <span data-ttu-id="4bb63-156">在套接字连接数量有限的环境中运行应用程序时,我们也建议使用网关连接模式。</span><span class="sxs-lookup"><span data-stu-id="4bb63-156">We also recommend gateway connection mode when you run applications in environments that have a limited number of socket connections.</span></span>

    <span data-ttu-id="4bb63-157">在 Azure Functions 中使用 SDK 时,尤其是在[消耗计划](../azure-functions/functions-scale.md#consumption-plan)中使用时,请注意当前的[连接限制](../azure-functions/manage-connections.md)。</span><span class="sxs-lookup"><span data-stu-id="4bb63-157">When you use the SDK in Azure Functions, particularly in the [Consumption plan](../azure-functions/functions-scale.md#consumption-plan), be aware of the current [limits on connections](../azure-functions/manage-connections.md).</span></span> <span data-ttu-id="4bb63-158">这种情况下,如果还在 Azure Functions 应用程序中使用其他基于 HTTP 的客户端,则使用网关模式可能更好。</span><span class="sxs-lookup"><span data-stu-id="4bb63-158">In that case, gateway mode might be better if you're also working with other HTTP-based clients within your Azure Functions application.</span></span>

* <span data-ttu-id="4bb63-159">直接模式</span><span class="sxs-lookup"><span data-stu-id="4bb63-159">Direct mode</span></span>

    <span data-ttu-id="4bb63-160">直接模式支持通过 TCP 协议的连接。</span><span class="sxs-lookup"><span data-stu-id="4bb63-160">Direct mode supports connectivity through TCP protocol.</span></span>

在网关模式下,当你使用 Azure Cosmos DB API for MongoDB 时,Azure Cosmos DB 会使用端口 443 以及端口 10250、10255 和 10256。In gateway mode, Azure Cosmos DB uses port 443 and ports 10250, 10255, and 10256 when you're using the Azure Cosmos DB API for MongoDB. 端口 10250 映射到没有异地复制功能的默认 MongoDB 实例。Port 10250 maps to a default MongoDB instance without geo-replication. 端口 10255 和 10256 映射到具有异地复制功能的 MongoDB 实例。Ports 10255 and 10256 map to the MongoDB instance that has geo-replication.

在直接模式下使用 TCP 时,除了网关端口,还需确保 10000 到 20000 这个范围的端口处于打开状态,因为 Azure Cosmos DB 使用动态 TCP 端口(在专用终结点上使用直接模式时,必须打开整个范围的 TCP 端口(即从 0 到 65535))。When you use TCP in direct mode, in addition to the gateway ports, you need to ensure the port range between 10000 and 20000 is open because Azure Cosmos DB uses dynamic TCP ports (when using direct mode on private endpoints, the full range of TCP ports - from 0 to 65535 - has to be open). 如果这些端口未处于打开状态,你会在尝试使用 TCP 时收到“503 服务不可用”错误。If these ports aren't open and you try to use TCP, you receive a 503 Service Unavailable error. 下表显示了可用于各种 API 的连接模式,以及用于每个 API 的服务端口:This table shows the connectivity modes available for various APIs and the service ports used for each API:

连接模式Connection mode 支持的协议Supported protocol 支持的 SDKSupported SDKs API/服务端口API/Service port
网关Gateway HTTPSHTTPS 所有 SDKAll SDKs SQL (443)、MongoDB(10250、10255、10256)、表 (443)、Cassandra (10350)、Graph (443)SQL (443), MongoDB (10250, 10255, 10256), Table (443), Cassandra (10350), Graph (443)
直接Direct TCPTCP .NET SDK.NET SDK 使用公共/服务终结点时:端口介于 10000 到 20000 之间When using public/service endpoints: ports in the 10000 through 20000 range
使用专用终结点时:端口介于 0 到 65535 之间When using private endpoints: ports in the 0 through 65535 range

Azure Cosmos DB 提供基于 HTTPS 的简单开放 RESTful 编程模型。Azure Cosmos DB offers a simple, open RESTful programming model over HTTPS. 此外,它提供高效的 TCP 协议,该协议在其通信模型中也是 RESTful,可通过 .NET 客户端 SDK 获得。Additionally, it offers an efficient TCP protocol, which is also RESTful in its communication model and is available through the .NET client SDK. TCP 协议使用 TLS 来进行初始身份验证和加密通信。TCP protocol uses TLS for initial authentication and encrypting traffic. 为了获得最佳性能,请尽可能使用 TCP 协议。For best performance, use the TCP protocol when possible.

对于 Microsoft.Azure.DocumentDB SDK,可以在构造 DocumentClient 实例期间使用 ConnectionPolicy 参数配置连接模式。For the Microsoft.Azure.DocumentDB SDK, you configure the connection mode during the construction of the DocumentClient instance by using the ConnectionPolicy parameter. 如果使用直接模式,则也可以使用 ConnectionPolicy 参数设置 ProtocolIf you use direct mode, you can also set the Protocol by using the ConnectionPolicy parameter.

var serviceEndpoint = new Uri("https://contoso.documents.azure.cn");
var authKey = "your authKey from the Azure portal";
DocumentClient client = new DocumentClient(serviceEndpoint, authKey,
new ConnectionPolicy
{
    ConnectionMode = ConnectionMode.Direct, //ConnectionMode.Gateway is the default
    ConnectionProtocol = Protocol.Tcp
});

由于仅在直接模式下才支持 TCP,因此如果使用网关模式,则 HTTPS 协议始终用来与网关通信,并忽略 ConnectionPolicy 中的 Protocol 值。Because TCP is supported only in direct mode, if you use gateway mode, the HTTPS protocol is always used to communicate with the gateway and the Protocol value in ConnectionPolicy is ignored.

Azure Cosmos DB 连接策略

调用 OpenAsync 以避免首次请求时启动延迟Call OpenAsync to avoid startup latency on first request

默认情况下,第一个请求因为需要提取地址路由表而有较高的延迟。By default, the first request has higher latency because it needs to fetch the address routing table. 使用 SDK V2 时,请在初始化期间调用 OpenAsync() 一次,以避免在首次请求时出现这种启动延迟:When you use SDK V2, call OpenAsync() once during initialization to avoid this startup latency on the first request:

await client.OpenAsync();

备注

OpenAsync 会生成多个请求,这些请求用于获取帐户中所有容器的地址路由表。OpenAsync will generate requests to obtain the address routing table for all the containers in the account. 如果帐户有多个容器,但其应用程序访问的是其中的一部分,则 OpenAsync 会生成不必要数量的流量,导致初始化速度缓慢。For accounts that have many containers but whose application accesses a subset of them, OpenAsync would generate an unnecessary amount of traffic, which would make the initialization slow. 因此,在这种情况下使用 OpenAsync 可能不起作用,因为它会降低应用程序启动速度。So using OpenAsync might not be useful in this scenario because it slows down application startup.

出于性能考虑,请将客户端并置在同一 Azure 区域中For performance, collocate clients in same Azure region

如果可能,请将任何调用 Azure Cosmos DB 的应用程序放在 Azure Cosmos DB 数据库所在的区域。When possible, place any applications that call Azure Cosmos DB in the same region as the Azure Cosmos DB database. 下面是大致的比较:在同一区域中对 Azure Cosmos DB 的调用可在 1 到 2 毫秒内完成,而中国东部和中国北部区域之间的延迟则超过了几十毫秒。Here's an approximate comparison: calls to Azure Cosmos DB within the same region complete within 1 ms to 2 ms, but the latency between the East and North region of the China is more than dozens of ms. 根据请求采用的路由,各项请求从客户端传递到 Azure 数据中心边界时的此类延迟可能有所不同。This latency can vary from request to request, depending on the route taken by the request as it passes from the client to the Azure datacenter boundary. 确保调用应用程序位于预配的 Azure Cosmos DB 终结点所在的 Azure 区域即可尽可能降低延迟。You can get the lowest possible latency by ensuring the calling application is located within the same Azure region as the provisioned Azure Cosmos DB endpoint. 有关可用区域的列表,请参阅 Azure 区域For a list of available regions, see Azure regions.

Azure Cosmos DB 连接策略

增加线程/任务数目Increase the number of threads/tasks

由于对 Azure Cosmos DB 的调用是通过网络执行的,因此可能需要改变请求的并行度,以便最大程度地减少客户端应用程序等待请求的时间。Because calls to Azure Cosmos DB are made over the network, you might need to vary the degree of parallelism of your requests so that the client application spends minimal time waiting between requests. 例如,如果使用 .NET 任务并行库,请创建大约数百个在 Azure Cosmos DB 中进行读取或写入操作的任务。For example, if you're using the .NET Task Parallel Library, create on the order of hundreds of tasks that read from or write to Azure Cosmos DB.

启用加速网络Enable accelerated networking

为了降低延迟和 CPU 抖动情况,我们建议在客户端虚拟机上启用加速网络。To reduce latency and CPU jitter, we recommend that you enable accelerated networking on client virtual machines. 请参阅创建具有加速网络的 Windows 虚拟机创建具有加速网络的 Linux 虚拟机See Create a Windows virtual machine with accelerated networking or Create a Linux virtual machine with accelerated networking.

SDK 用法SDK usage

安装最新的 SDKInstall the most recent SDK

Azure Cosmos DB SDK 正在不断改进以提供最佳性能。The Azure Cosmos DB SDKs are constantly being improved to provide the best performance. 请参阅 Azure Cosmos DB SDK 页以了解最新的 SDK 并查看改进内容。See the Azure Cosmos DB SDK pages to determine the most recent SDK and review improvements.

在应用程序生存期内使用单一实例 Azure Cosmos DB 客户端Use a singleton Azure Cosmos DB client for the lifetime of your application

每个 DocumentClient 实例都是线程安全的,在直接模式下运行时可执行高效的连接管理和地址缓存。Each DocumentClient instance is thread-safe and performs efficient connection management and address caching when operating in direct mode. 若要实现有效的连接管理和提高 SDK 客户端性能,建议在应用程序的生存期内对每个 AppDomain 使用单个实例。To allow efficient connection management and better SDK client performance, we recommend that you use a single instance per AppDomain for the lifetime of the application.

在使用网关模式时增加每台主机的 System.Net MaxConnectionsIncrease System.Net MaxConnections per host when using gateway mode

使用网关模式时,Azure Cosmos DB 请求是通过 HTTPS/REST 发出的。Azure Cosmos DB requests are made over HTTPS/REST when you use gateway mode. 这些请求受制于每个主机名或 IP 地址的默认连接限制。They're subjected to the default connection limit per hostname or IP address. 可能需要将 MaxConnections 设置为较大的值(100 到 1,000),以便客户端库能够同时使用多个连接来访问 Azure Cosmos DB。You might need to set MaxConnections to a higher value (100 to 1,000) so the client library can use multiple simultaneous connections to Azure Cosmos DB. 在 .NET SDK 1.8.0 及更高版本中,ServicePointManager.DefaultConnectionLimit 的默认值为 50。In .NET SDK 1.8.0 and later, the default value for ServicePointManager.DefaultConnectionLimit is 50. 若要更改此值,可将 Documents.Client.ConnectionPolicy.MaxConnectionLimit 设置为更大的值。To change the value, you can set Documents.Client.ConnectionPolicy.MaxConnectionLimit to a higher value.

优化已分区集合的并行查询Tune parallel queries for partitioned collections

SQL .NET SDK 1.9.0 及更高版本支持并行查询,使你能够并行查询分区的集合。SQL .NET SDK 1.9.0 and later support parallel queries, which enable you to query a partitioned collection in parallel. 有关详细信息,请参阅与使用这些 SDK 相关的代码示例For more information, see code samples related to working with the SDKs. 并行查询旨在提供更低的查询延迟,以及优于其对应的串行查询的吞吐量。Parallel queries are designed to provide better query latency and throughput than their serial counterpart. 并行查询提供两个参数,你可以根据要求优化这些参数:Parallel queries provide two parameters that you can tune to fit your requirements:

  • MaxDegreeOfParallelism 控制可以并行查询的最大分区数。MaxDegreeOfParallelism controls the maximum number of partitions that can be queried in parallel.
  • MaxBufferedItemCount 控制预提取的结果数。MaxBufferedItemCount controls the number of pre-fetched results.

优化并行度Tuning degree of parallelism

并行查询的工作原理是并行查询多个分区。Parallel query works by querying multiple partitions in parallel. 但就查询本身而言,会按顺序提取单个分区中的数据。But data from an individual partition is fetched serially with respect to the query. SDK V2 中的 MaxDegreeOfParallelism 设置为分区数最有可能实现最高性能的查询,前提是所有其他的系统条件保持不变。Setting MaxDegreeOfParallelism in SDK V2 to the number of partitions has the best chance of achieving the most performant query, provided all other system conditions remain the same. 如果不知道分区数,可将并行度设置为较大的数字。If you don't know the number of partitions, you can set the degree of parallelism to a high number. 系统会选择最小值(分区数、用户提供的输入)作为并行度。The system will choose the minimum (number of partitions, user provided input) as the degree of parallelism.

请注意,如果查询时数据均衡分布在所有分区之间,则并行查询的优势最大。Note that parallel queries produce the most benefit if the data is evenly distributed across all partitions with respect to the query. 如果对已分区的集合进行分区,使查询返回的全部或大部分数据集中于几个分区(最坏的情况为一个分区),则这些分区会使查询性能出现瓶颈。If the partitioned collection is partitioned so that all or most of the data returned by a query is concentrated in a few partitions (one partition is the worst case), those partitions will bottleneck the performance of the query.

优化 MaxBufferedItemCountTuning MaxBufferedItemCount

并行查询设计为当客户端正在处理当前结果批时预提取结果。Parallel query is designed to pre-fetch results while the current batch of results is being processed by the client. 这种预提取可帮助改善查询的总体延迟。This pre-fetching helps improve the overall latency of a query. MaxBufferedItemCount 参数限制预提取的结果数。The MaxBufferedItemCount parameter limits the number of pre-fetched results. MaxBufferedItemCount 设置为预期返回的结果数(或更大的数字)可让查询通过预提取获得最大优势。Set MaxBufferedItemCount to the expected number of results returned (or a higher number) to allow the query to receive the maximum benefit from pre-fetching.

预提取的工作方式与并行度无关,使用一个单独的缓冲区来存储所有分区的数据。Pre-fetching works the same way regardless of the degree of parallelism, and there's a single buffer for the data from all partitions.

按 RetryAfter 间隔实现退让Implement backoff at RetryAfter intervals

在性能测试期间,应该增加负载,直到系统对小部分请求进行限制为止。During performance testing, you should increase load until a small rate of requests are throttled. 如果请求受到限制,客户端应用程序应按照服务器指定的重试间隔在限制时退让。If requests are throttled, the client application should back off on throttle for the server-specified retry interval. 允许退让可确保最大程度地减少等待重试的时间。Respecting the backoff ensures you spend a minimal amount of time waiting between retries.

以下 SDK 提供重试策略支持:Retry policy support is included in these SDKs:

有关详细信息,请参阅 RetryAfterFor more information, see RetryAfter.

在 .NET SDK 1.19 及更高版本中,有一个机制可以记录附加诊断信息和排查延迟问题,如以下示例中所示。In version 1.19 and later of the .NET SDK, there's a mechanism for logging additional diagnostic information and troubleshooting latency issues, as shown in the following sample. 可以记录具有较高读取延迟的请求的诊断字符串。You can log the diagnostic string for requests that have a higher read latency. 捕获的诊断字符串可帮助你了解收到给定请求的 429 错误的次数。The captured diagnostic string will help you understand how many times you received 429 errors for a given request.

ResourceResponse<Document> readDocument = await this.readClient.ReadDocumentAsync(oldDocuments[i].SelfLink);
readDocument.RequestDiagnosticsString 

缓存较低读取延迟的文档 URICache document URIs for lower read latency

尽可能缓存文档 URI 以获得最佳读取性能。Cache document URIs whenever possible for the best read performance. 创建资源时,需要定义用于缓存资源 ID 的逻辑。You need to define logic to cache the resource ID when you create a resource. 基于资源 ID 的查找比基于名称的查找更快,因此缓存这些值可提高性能。Lookups based on resource IDs are faster than name-based lookups, so caching these values improves performance.

优化查询/读取源的页面大小以提高性能Tune the page size for queries/read feeds for better performance

使用读取源功能(例如 ReadDocumentFeedAsync)对文档进行批量读取时,或发出 SQL 查询时,如果结果集太大,则会以分段方式返回结果。When you do a bulk read of documents by using read feed functionality (for example, ReadDocumentFeedAsync) or when you issue a SQL query, the results are returned in a segmented fashion if the result set is too large. 默认情况下,以包括 100 个项的块或 1 MB 大小的块返回结果(以先达到的限制为准)。By default, results are returned in chunks of 100 items or 1 MB, whichever limit is hit first.

若要减少检索所有适用结果所需的网络往返次数,可以使用 x-ms-max-item-count 请求最多 1,000 个标头,以增加页面大小。To reduce the number of network round trips required to retrieve all applicable results, you can increase the page size by using x-ms-max-item-count to request as many as 1,000 headers. 如果只需要显示几个结果(例如,用户界面或应用程序 API 一次只返回 10 个结果),也可以将页面大小减小到 10,以降低读取和查询所耗用的吞吐量。When you need to display only a few results, for example, if your user interface or application API returns only 10 results at a time, you can also decrease the page size to 10 to reduce the throughput consumed for reads and queries.

备注

maxItemCount 属性不应仅用于分页目的。The maxItemCount property shouldn't be used just for pagination. 它的主要用途是通过减少单个页面中返回的最大项数来提高查询性能。Its main use is to improve the performance of queries by reducing the maximum number of items returned in a single page.

也可以使用提供的 Azure Cosmos DB SDK 设置页面大小。You can also set the page size by using the available Azure Cosmos DB SDKs. FeedOptions 中的 MaxItemCount 属性允许你设置要在枚举操作中返回的最大项数。The MaxItemCount property in FeedOptions allows you to set the maximum number of items to be returned in the enumeration operation. maxItemCount 设置为 -1 时,SDK 会根据文档大小自动查找最佳值。When maxItemCount is set to -1, the SDK automatically finds the optimal value, depending on the document size. 例如:For example:

IQueryable<dynamic> authorResults = client.CreateDocumentQuery(documentCollection.SelfLink, "SELECT p.Author FROM Pages p WHERE p.Title = 'About Seattle'", new FeedOptions { MaxItemCount = 1000 });

执行查询时,结果数据在 TCP 数据包中发送。When a query is executed, the resulting data is sent within a TCP packet. 如果为 maxItemCount 指定的值太低,则在 TCP 数据包中发送数据所需的往返次数很高,这会影响性能。If you specify too low a value for maxItemCount, the number of trips required to send the data within the TCP packet is high, which affects performance. 因此,如果你不确定要为 maxItemCount 属性设置什么值,最好将其设置为 -1,让 SDK 选择默认值。So if you're not sure what value to set for the maxItemCount property, it's best to set it to -1 and let the SDK choose the default value.

增加线程/任务数目Increase the number of threads/tasks

请参阅本文“网络”部分中的增加线程/任务数目See Increase the number of threads/tasks in the Networking section of this article.

索引策略Indexing policy

从索引中排除未使用的路径以加快写入速度Exclude unused paths from indexing for faster writes

Azure Cosmos DB 的索引策略还允许使用索引路径(IndexingPolicy.IncludedPaths 和 IndexingPolicy.ExcludedPaths)指定要在索引中包括或排除的文档路径。The Azure Cosmos DB indexing policy also allows you to specify which document paths to include in or exclude from indexing by using indexing paths (IndexingPolicy.IncludedPaths and IndexingPolicy.ExcludedPaths). 在事先已知查询模式的情况下,索引路径可以提高写入性能并减少索引存储。Indexing paths can improve write performance and reduce index storage for scenarios in which the query patterns are known beforehand. 这是因为,索引成本与已编制索引的唯一路径数目直接相关。This is because indexing costs correlate directly to the number of unique paths indexed. 例如,以下代码演示如何使用“*”通配符从索引中排除文档的一整个部分(子树):For example, this code shows how to exclude an entire section of the documents (a subtree) from indexing by using the "*" wildcard:

var collection = new DocumentCollection { Id = "excludedPathCollection" };
collection.IndexingPolicy.IncludedPaths.Add(new IncludedPath { Path = "/*" });
collection.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/nonIndexedContent/*");
collection = await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri("db"), excluded);

有关索引的详细信息,请参阅 Azure Cosmos DB 索引策略For more information, see Azure Cosmos DB indexing policies.

吞吐量Throughput

度量并优化较低的每秒请求单位使用量Measure and tune for lower Request Units/second usage

Azure Cosmos DB 提供一组丰富的数据库操作。Azure Cosmos DB offers a rich set of database operations. 这些操作包括 UDF 的关系和分层查询、存储过程和触发器,全都在数据库集合中的文档上进行。These operations include relational and hierarchical queries with UDFs, stored procedures, and triggers, all operating on the documents within a database collection. 与其中每个操作关联的成本取决于完成该操作所需的 CPU、IO 和内存。The cost associated with each of these operations varies depending on the CPU, IO, and memory required to complete the operation. 可以将请求单位 (RU) 视为执行各种数据库操作和处理应用程序请求所需的资源的单一度量,无需考虑和管理硬件资源。Instead of thinking about and managing hardware resources, you can think of a Request Unit (RU) as a single measure for the resources required to perform various database operations and service an application request.

吞吐量的预配取决于为每个容器设置的请求单位数。Throughput is provisioned based on the number of Request Units set for each container. 请求单位消耗以每秒速率进行评估。Request Unit consumption is evaluated as a rate per second. 如果应用程序的速率超过了为其容器预配的请求单位速率,则会受到限制,直到该速率降到容器的预配级别以下。Applications that exceed the provisioned Request Unit rate for their container are limited until the rate drops below the provisioned level for the container. 如果应用程序需要较高级别的吞吐量,可以通过预配更多请求单位来增加吞吐量。If your application requires a higher level of throughput, you can increase your throughput by provisioning additional Request Units.

查询的复杂性会影响操作消耗的请求单位数量。The complexity of a query affects how many Request Units are consumed for an operation. 谓词数、谓词性质、UDF 数目和源数据集的大小都会影响查询操作的成本。The number of predicates, the nature of the predicates, the number of UDFs, and the size of the source dataset all influence the cost of query operations.

若要度量任一操作(创建、更新或删除)的开销,请检查 x-ms-request-charge 标头(或者 .NET SDK 的 ResourceResponse\<T>FeedResponse\<T> 中的等效 RequestCharge 属性),以度量这些操作消耗的请求单位数:To measure the overhead of any operation (create, update, or delete), inspect the x-ms-request-charge header (or the equivalent RequestCharge property in ResourceResponse\<T> or FeedResponse\<T> in the .NET SDK) to measure the number of Request Units consumed by the operations:

// Measure the performance (Request Units) of writes
ResourceResponse<Document> response = await client.CreateDocumentAsync(collectionSelfLink, myDocument);
Console.WriteLine("Insert of document consumed {0} request units", response.RequestCharge);
// Measure the performance (Request Units) of queries
IDocumentQuery<dynamic> queryable = client.CreateDocumentQuery(collectionSelfLink, queryString).AsDocumentQuery();
while (queryable.HasMoreResults)
    {
        FeedResponse<dynamic> queryResponse = await queryable.ExecuteNextAsync<dynamic>();
        Console.WriteLine("Query batch consumed {0} request units", queryResponse.RequestCharge);
    }

在此标头中返回的请求费用是已预配吞吐量(即 2,000 RU/秒)的一小部分。The request charge returned in this header is a fraction of your provisioned throughput (that is, 2,000 RUs / second). 例如,如果上述查询返回 1,000 个 1-KB 的文档,则操作成本是 1,000。For example, if the preceding query returns 1,000 1-KB documents, the cost of the operation is 1,000. 因此,在一秒内,服务器在对后续请求进行速率限制之前只接受两个此类请求。So, within one second, the server honors only two such requests before rate limiting later requests. 有关详细信息,请参阅请求单位请求单位计算器For more information, see Request Units and the Request Unit calculator.

处理速率限制/请求速率太大Handle rate limiting/request rate too large

客户端尝试超过为帐户保留的吞吐量时,服务器的性能不会降低,并且不会使用超过保留级别的吞吐量容量。When a client attempts to exceed the reserved throughput for an account, there's no performance degradation at the server and no use of throughput capacity beyond the reserved level. 服务器会提前结束请求并返回 RequestRateTooLarge(HTTP 状态代码 429)错误。The server will preemptively end the request with RequestRateTooLarge (HTTP status code 429). 它会返回 x-ms-retry-after-ms 标头,指示重试该请求之前用户必须等待的时间(以毫秒为单位)。It will return an x-ms-retry-after-ms header that indicates the amount of time, in milliseconds, that the user must wait before attempting the request again.

HTTP Status 429,
Status Line: RequestRateTooLarge
x-ms-retry-after-ms :100

SDK 全部都会隐式捕获此响应,并遵循服务器指定的 retry-after 标头,并重试请求。The SDKs all implicitly catch this response, respect the server-specified retry-after header, and retry the request. 除非多个客户端同时访问帐户,否则下次重试就会成功。Unless your account is being accessed concurrently by multiple clients, the next retry will succeed.

如果累计有多个客户端持续在超过请求速率的情况下运行,则当前由客户端在内部设置为 9 的默认重试计数可能并不足够。If you have more than one client cumulatively operating consistently above the request rate, the default retry count currently set to 9 internally by the client might not suffice. 在此情况下,客户端会向应用程序引发 DocumentClientException,其状态代码为 429。In this case, the client throws a DocumentClientException with status code 429 to the application.

可以通过在 ConnectionPolicy 实例上设置 RetryOptions 来更改默认重试计数。You can change the default retry count by setting the RetryOptions on the ConnectionPolicy instance. 默认情况下,如果请求继续以高于请求速率的方式运行,则在 30 秒的累积等待时间后返回 DocumentClientException 和状态代码 429。By default, the DocumentClientException with status code 429 is returned after a cumulative wait time of 30 seconds if the request continues to operate above the request rate. 即使当前的重试计数小于最大重试计数(无论当前值是默认值 9 还是用户定义的值),也会返回此错误。This error returns even when the current retry count is less than the maximum retry count, whether the current value is the default of 9 or a user-defined value.

自动重试行为有助于改善大多数应用程序的复原能力和可用性。The automated retry behavior helps improve resiliency and usability for most applications. 但是,在执行性能基准测试时(尤其是在度量延迟时),自动重试可能不是最佳行为。But it might not be the best behavior when you're doing performance benchmarks, especially when you're measuring latency. 如果实验达到服务器限制并导致客户端 SDK 静默重试,则客户端观测到的延迟会剧增。The client-observed latency will spike if the experiment hits the server throttle and causes the client SDK to silently retry. 若要避免性能实验期间出现延迟高峰,可以测量每个操作返回的费用,并确保请求以低于保留请求速率的方式运行。To avoid latency spikes during performance experiments, measure the charge returned by each operation and ensure that requests are operating below the reserved request rate. 有关详细信息,请参阅请求单位For more information, see Request Units.

针对较小文档进行设计以提高吞吐量For higher throughput, design for smaller documents

给定操作的请求费用(即请求处理成本)与文档大小直接相关。The request charge (that is, the request-processing cost) of a given operation correlates directly to the size of the document. 大型文档的操作成本高于小型文档的操作成本。Operations on large documents cost more than operations on small documents.

后续步骤Next steps

如果需要使用一个示例应用程序来评估 Azure Cosmos DB,以便在数个客户端计算机上实现高性能方案,请参阅使用 Azure Cosmos DB 进行性能和缩放测试For a sample application that's used to evaluate Azure Cosmos DB for high-performance scenarios on a few client machines, see Performance and scale testing with Azure Cosmos DB.

若要深入了解如何设计应用程序以实现缩放和高性能,请参阅 Azure Cosmos DB 中的分区和缩放To learn more about designing your application for scale and high performance, see Partitioning and scaling in Azure Cosmos DB.