Skip to main content

Fixed: The provided cross partition query can not be directly served by the gateway

· 22 min read
Jagdish Kumawat
Founder @ Dewiride

I asked the Azure Cosmos DB REST API for a container's door-sensor events, sorted by time, and got HTTP 400 back: The provided cross partition query can not be directly served by the gateway. The gateway that every REST call goes through won't run an ORDER BY across partitions. Giving the request one partition key fixed it, and an SDK, which merges the partitions itself, returned every event in order.

What I Was Doing​

A container named events, in the database howto, holds the events of door sensors. Its partition key path is /deviceId, so each sensor's events form their own partition. Each event's at is a UTC time with seven fraction digits, a format that sorts correctly as text (how to store dates and times that sort correctly). The container held four events from two sensors:

deviceIdnameat
front-doorDoor opened2026-12-03T10:00:00.0000000Z
back-doorDoor opened2026-12-03T10:00:05.0000000Z
front-doorDoor closed2026-12-03T10:00:10.0000000Z
back-doorDoor closed2026-12-03T10:00:15.0000000Z

I wanted them in time order from the terminal, without writing an app, so I called the Azure Cosmos DB REST API directly:

  1. I got a Microsoft Entra access token from the Azure CLI. My account has a Cosmos DB data role on the database (how to give your account that role), so the token can read its items.
  2. I sent the query SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at as a POST to the container's docs, with curl in the terminal and with Invoke-RestMethod in PowerShell 7.6.
Terminal
TOKEN=$(az account get-access-token --scope https://cosmos.azure.com/.default --query accessToken --output tsv)
curl --silent --request POST \
"https://cosmos-maf-servicedesk-4224.documents.azure.com/dbs/howto/colls/events/docs" \
--header "Authorization: type%3Daad%26ver%3D1.0%26sig%3D$TOKEN" \
--header "x-ms-date: $(LC_ALL=C date -u '+%a, %d %b %Y %H:%M:%S GMT')" \
--header "x-ms-version: 2018-12-31" \
--header "Content-Type: application/query+json" \
--header "x-ms-documentdb-isquery: True" \
--header "x-ms-documentdb-query-enablecrosspartition: True" \
--data '{"query": "SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at", "parameters": []}' \
--write-out '\nHTTP status: %{http_code}\n'

What each part does:

  • az account get-access-token --scope https://cosmos.azure.com/.default gets an access token for Azure Cosmos DB, as the account the Azure CLI is signed in with. --query accessToken --output tsv keeps only the token's text. The Azure CLI reference says the token will be valid for at least 5 minutes with the maximum at 60 minutes.
  • Authorization carries the token as type=aad&ver=1.0&sig= followed by the token. Learn's access control page lists aad as the token type when you use Azure Cosmos DB role-based access control, with the OAuth token as the signature. The = and & are written as %3D and %26, because The authorization string should be encoded before adding it to the REST request to ensure that it contains no invalid characters.
  • x-ms-date is the time of the request in the RFC 1123 format, in UTC, like Learn's example Fri, 08 Apr 2015 03:52:31 GMT. In bash, date -u writes it. date writes the day and month names in the machine's language, so LC_ALL=C keeps them in English. In PowerShell, ToString("r") writes the same format: Learn's page on standard format strings says the "R" or "r" specifier always uses the invariant culture.
  • x-ms-version: 2018-12-31 is the version of the REST API, the same version Learn's access control example sends.
  • Content-Type: application/query+json and x-ms-documentdb-isquery: True tell Cosmos DB that this POST is a query, as Learn's page on querying with the REST API asks.
  • x-ms-documentdb-query-enablecrosspartition: True lets the query run across partitions. Learn's Query Documents page: If the collection is partitioned, this must be set to True to allow execution across multiple partitions. My query reads both sensors, so I set it.
  • --data in curl and $body in PowerShell send the query with an empty parameters list. Learn marks both query and parameters as required.
  • --silent hides curl's progress meter, and --write-out prints the HTTP status code after the answer: curl's manual describes http_code as the numerical response code of the last transfer.
  • In PowerShell, $headers holds the same headers, and Invoke-RestMethod sends the POST with -ContentType and -Body.

What I Expected​

All four events in one list, oldest first: the front door opened at 10:00:00, the back door opened at 10:00:05, the front door closed at 10:00:10 and the back door closed at 10:00:15.

What I Got​

Status 400 and no events. curl printed the answer and the status line. PowerShell stopped at Invoke-RestMethod, line 10 of query.ps1, and showed the same answer as an error:

Output
{"code":"BadRequest","message":"The provided cross partition query can not be directly served by the gateway. This is a first chance (internal) exception that all newer clients will know how to handle gracefully. This exception is traced, but unless you see it bubble up as an exception (which only happens on older SDK clients), then you can safely ignore this message.\r\nActivityId: 00000000-0000-0000-0000-000000000000, Microsoft.Azure.Documents.Common/2.14.0","additionalErrorInfo":"{\"partitionedQueryExecutionInfoVersion\":2,\"queryInfo\":{\"distinctType\":\"None\",\"top\":null,\"offset\":null,\"limit\":null,\"orderBy\":[\"Ascending\"],\"orderByExpressions\":[\"c.at\"],\"groupByExpressions\":[],\"groupByAliases\":[],\"aggregates\":[],\"groupByAliasToAggregateType\":{},\"rewrittenQuery\":\"SELECT c._rid, [{\\\"item\\\": c.at}] AS orderByItems, {\\\"deviceId\\\": c.deviceId, \\\"name\\\": c.name, \\\"at\\\": c.at} AS payload\\nFROM c\\nWHERE ({documentdb-formattableorderbyquery-filter})\\nORDER BY c.at\",\"hasSelectValue\":false,\"dCountInfo\":null,\"hasNonStreamingOrderBy\":false},\"queryRanges\":[{\"min\":\"\",\"max\":\"FF\",\"isMinInclusive\":true,\"isMaxInclusive\":false}],\"hybridSearchQueryInfo\":null}"}
HTTP status: 400

I replaced the activity ID with zeros. Here is the curl run:

macOS-style terminal window titled Terminal — GatewayQuery showing the TOKEN line with az account get-access-token, a curl POST to the docs of the events container with the Authorization, x-ms-date, x-ms-version, Content-Type, x-ms-documentdb-isquery and x-ms-documentdb-query-enablecrosspartition headers and the query SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at, then the JSON answer with the code BadRequest, the message The provided cross partition query can not be directly served by the gateway, the additionalErrorInfo with queryRanges, and HTTP status: 400

What I Checked​

What the message says. It names the gateway, and it calls itself a first chance (internal) exception that all newer clients will know how to handle gracefully. It also says the exception only bubbles up on older SDK clients, so the clients it means are the Azure Cosmos DB SDKs. curl and PowerShell aren't SDKs, and for them the request simply failed.

What the gateway is. Learn's page on REST interactions describes two ways to connect. In gateway mode, the edge machines translate the logical URI to the physical address of the replica which manages the resource and forwards the request, and its table lists the REST API under gateway mode only. So every REST call, mine included, goes through the gateway.

What the gateway can't run. Learn's page Querying Azure Cosmos DB resources using the REST API has a section on exactly this: Any query that requires state across continuations cannot be served by the gateway. It lists six kinds:

  • TOP
  • ORDER BY
  • OFFSET LIMIT
  • Aggregates
  • DISTINCT
  • GROUP BY

The gateway can serve simple projections and filters. The same page says You will also get a 400 bad request if a query cannot be served by the gateway, and shows the same message as its example answer. My query had an ORDER BY and no partition key.

What additionalErrorInfo holds. It isn't a second error. It's the query's plan: orderBy is ["Ascending"] on orderByExpressions ["c.at"], and rewrittenQuery is my query rewritten to return each item's _rid and its sort value (orderByItems) next to the three fields I selected (payload). queryRanges holds one range, from "" to "FF". Learn's page on query performance explains these ranges: Since partitions are transient, the APIs use an abstraction of a partition key range, which denotes the ranges of partition key hashes. My request had no partition key, so nothing narrowed the range to one sensor's partition.

What an SDK does with such a query. The same performance page lists the steps an SDK takes for a query:

  1. Parse the SQL query to determine the query execution plan.
  2. If the query doesn't have a filter on the partition key, then it's executed in all partitions and results from each partition are merged client side.
  3. For an ORDER BY, results from individual partitions are merge-sorted to return results in globally sorted order.

So sorting across partitions is the client's job. An SDK does it. curl and Invoke-RestMethod send one request and show its answer.

Why It Happens​

Every REST request goes through the gateway. My query asked for an ORDER BY over every partition, and that is one of the queries the gateway can't serve: the results of several partitions would have to be merge-sorted into one list. With x-ms-documentdb-query-enablecrosspartition: True and no partition key, the gateway answered with status 400 and the query's plan instead of items. An SDK gets past this because it runs the query in each partition and merge-sorts the results itself. A plain HTTP client gets the 400.

The Fix​

There are two fixes, and the right one depends on what you need:

  • One partition's items, sorted: give the request a partition key, and the gateway runs the query in that partition alone.
  • Every partition's items in one sorted list: run the query with an SDK, which merges the partitions itself.

Fix 1: Query One Partition​

Replace x-ms-documentdb-query-enablecrosspartition: True with x-ms-documentdb-partitionkey: ["front-door"]. Learn's list of common request headers describes it: This value is used to scope your query to documents that match the partition key criteria. By design it's a single partition query. Its value is a JSON array that holds the partition key value.

Terminal
TOKEN=$(az account get-access-token --scope https://cosmos.azure.com/.default --query accessToken --output tsv)
curl --silent --request POST \
"https://cosmos-maf-servicedesk-4224.documents.azure.com/dbs/howto/colls/events/docs" \
--header "Authorization: type%3Daad%26ver%3D1.0%26sig%3D$TOKEN" \
--header "x-ms-date: $(LC_ALL=C date -u '+%a, %d %b %Y %H:%M:%S GMT')" \
--header "x-ms-version: 2018-12-31" \
--header "Content-Type: application/query+json" \
--header "x-ms-documentdb-isquery: True" \
--header 'x-ms-documentdb-partitionkey: ["front-door"]' \
--data '{"query": "SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at", "parameters": []}' \
--write-out '\nHTTP status: %{http_code}\n'
Output
{"_rid":"oCZPAP4tLuU=","Documents":[{"deviceId":"front-door","name":"Door opened","at":"2026-12-03T10:00:00.0000000Z"},{"deviceId":"front-door","name":"Door closed","at":"2026-12-03T10:00:10.0000000Z"}],"_count":2}
HTTP status: 200

Status 200 this time, with two events in time order: the front door opened at 10:00:00 and closed at 10:00:10. _count is 2. The back door's events aren't there, because they're in another partition. In C#, the same scoping is the PartitionKey of QueryRequestOptions (how to query the items of one partition).

Fix 2: Let an SDK Run the Query Across Partitions​

When you need every sensor's events in one list, run the same query with an SDK. It runs the query in each partition and merge-sorts the results, as Learn's steps above describe. I ran it with the Azure Cosmos DB .NET SDK in a small console app, SdkCrossPartition, with these packages:

SdkCrossPartition.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>

Microsoft.Azure.Cosmos is the Cosmos DB SDK, Newtonsoft.Json is a package the SDK requires you to reference yourself, and Azure.Identity has the Microsoft Entra ID credentials. The app's Program.cs sends the same query with no partition key:

Program.cs
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container events = client.GetContainer("howto", "events");

// No partition key: the SDK asks for the query plan, runs the query in every partition and merges the results.
FeedIterator<StoredEvent> query = events.GetItemQueryIterator<StoredEvent>("SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at");
while (query.HasMoreResults)
{
FeedResponse<StoredEvent> page = await query.ReadNextAsync();
foreach (StoredEvent stored in page)
{
Console.WriteLine($"{stored.At} {stored.DeviceId,-10} {stored.Name}");
}
}

record StoredEvent(string DeviceId, string Name, string At);

macOS-style code window titled Program.cs — SdkCrossPartition showing a CosmosClient for the account endpoint with AzureCliCredential and JsonSerializerOptions.Web, the events container of the howto database, GetItemQueryIterator with the query SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at and no partition key, a loop that prints each event's time, device and name, and the StoredEvent record

  • AzureCliCredential signs in as the Azure CLI's account, the same identity as the token in the REST calls. How to connect to Azure Cosmos DB with Microsoft Entra ID in C# sets this up step by step.
  • JsonSerializerOptions.Web reads items with System.Text.Json and camelCase names, so the stored deviceId fills the record's DeviceId.
  • GetItemQueryIterator<StoredEvent> takes the same query and no QueryRequestOptions, so there's no partition key, and the SDK runs it across partitions.
  • HasMoreResults and ReadNextAsync() read the results page by page, and the loop prints each event's time, sensor and name.
  • record StoredEvent holds the three fields the query selects.

Run it:

Terminal
dotnet run
Output
2026-12-03T10:00:00.0000000Z front-door Door opened
2026-12-03T10:00:05.0000000Z back-door Door opened
2026-12-03T10:00:10.0000000Z front-door Door closed
2026-12-03T10:00:15.0000000Z back-door Door closed

All four events, from both sensors, in time order.

After the Fix​

With the partition key header, the gateway answered 200 and returned the front door's events in time order:

macOS-style terminal window titled Terminal — GatewayQuery showing the same curl request with the header x-ms-documentdb-partitionkey set to front-door in place of the cross-partition header, and the answer with _rid, Documents holding Door opened at 2026-12-03T10:00:00.0000000Z and Door closed at 2026-12-03T10:00:10.0000000Z in that order, _count 2, and HTTP status: 200

In PowerShell, $response.Documents lists the same two events as a table, with the times shown as dates:

macOS-style terminal window titled PowerShell — GatewayQuery showing ./query-one-documents.ps1 and a table with the columns deviceId, name and at: front-door, Door opened, 12/3/2026 10:00:00 AM, then front-door, Door closed, 12/3/2026 10:00:10 AM

And the .NET SDK returned every sensor's events in one sorted list:

macOS-style terminal window titled Terminal — SdkCrossPartition showing dotnet run and four events in time order: 2026-12-03T10:00:00.0000000Z front-door Door opened, 2026-12-03T10:00:05.0000000Z back-door Door opened, 2026-12-03T10:00:10.0000000Z front-door Door closed and 2026-12-03T10:00:15.0000000Z back-door Door closed

Common Mistakes​

MistakeWhat happensDo this instead
Sending a query with TOP, ORDER BY, OFFSET LIMIT, an aggregate, DISTINCT or GROUP BY across partitions to the REST APIStatus 400 with this message, and no itemsSend x-ms-documentdb-partitionkey, or run the query with an SDK
Taking then you can safely ignore this message at its word outside an SDKThe request failed: status 400, nothing returnedOutside an SDK, treat it as the error it is
Reading the 400 as a mistake in the SQLLearn's response table lists 400 as The syntax of the SQL statement is incorrect, so you look for a typo that isn't thereRead the message: it names the gateway, not the syntax
Expecting the one-partition request to return every sensorOnly that partition's items come back: 2 of the 4 events hereUse an SDK when you need one list across partitions

Troubleshooting​

SymptomLikely causeFix
HTTP 400 with The provided cross partition query can not be directly served by the gatewayA query the gateway can't serve across partitions, sent with no partition keyAdd x-ms-documentdb-partitionkey, or use an SDK
PowerShell stops at Invoke-RestMethod and prints the same JSON as an errorThe same status 400: Invoke-RestMethod shows the error answer as a PowerShell errorThe same two fixes
Status 200, but only some of the itemsThe partition key header limits the query to one partitionUse an SDK when you need every partition

FAQ​

Why does the message say I can safely ignore it?​

The message is written for SDKs. It says that all newer clients will know how to handle it and that it bubbles up as an exception only on older SDK clients. An SDK runs the query in each partition and merge-sorts the results itself, so your code never sees the 400. curl and Invoke-RestMethod don't, so for them the 400 is the final answer.

Which queries can the gateway run across partitions?​

Learn lists simple projections and filters. TOP, ORDER BY, OFFSET LIMIT, aggregates, DISTINCT and GROUP BY need state across continuations, and the gateway doesn't serve them.

Does a cross-partition query through an SDK cost more?​

It reads every partition. Learn's query tips for the SDKs say: Cross-partition queries require the SDK to visit all existing partitions to check for results. The partitioning page puts the overhead of checking each additional physical partition, when the partition key isn't included, at 2-3 RU per physical partition. When you only need one sensor's events, send its partition key.

Does the REST API take a Microsoft Entra token for queries?​

It did here: the one-partition query returned 200 with a type=aad token. Learn's page on querying with the REST API still says in its header table Only the master key token is allowed for this operation, while its access control page lists aad as a token type for Azure Cosmos DB role-based access control.

Why does PowerShell show the times as 12/3/2026 10:00:00 AM?​

Invoke-RestMethod automatically converts JSON content to objects, and here it turned each at string into a date. Learn's ConvertFrom-Json page describes the same conversion: a timestamp string with a trailing Z becomes a UTC DateTime. PowerShell prints it in its own date format, so 12/3/2026 10:00:00 AM is 2026-12-03T10:00:00.0000000Z, and the order is the one Cosmos DB returned.

Conclusion​

The provided cross partition query can not be directly served by the gateway means the REST API's gateway got a query it can't run across partitions: TOP, ORDER BY, OFFSET LIMIT, an aggregate, DISTINCT or GROUP BY, with no partition key. It answers with status 400 and the query's plan, which SDKs handle and plain HTTP clients don't. Send the partition key in x-ms-documentdb-partitionkey to sort one partition through the REST API, or use an SDK to get one sorted list across partitions.

Additional Resources​