Fixed: The provided cross partition query can not be directly served by the gateway
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:
| deviceId | name | at |
|---|---|---|
| front-door | Door opened | 2026-12-03T10:00:00.0000000Z |
| back-door | Door opened | 2026-12-03T10:00:05.0000000Z |
| front-door | Door closed | 2026-12-03T10:00:10.0000000Z |
| back-door | Door closed | 2026-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:
- 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.
- I sent the query
SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.atas aPOSTto the container'sdocs, with curl in the terminal and withInvoke-RestMethodin PowerShell 7.6.
- bash / zsh
- PowerShell
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'
I saved the request as query.ps1 in a folder named GatewayQuery:
$token = az account get-access-token --scope https://cosmos.azure.com/.default --query accessToken --output tsv
$headers = @{
"Authorization" = "type%3Daad%26ver%3D1.0%26sig%3D$token"
"x-ms-date" = [DateTime]::UtcNow.ToString("r")
"x-ms-version" = "2018-12-31"
"x-ms-documentdb-isquery" = "True"
"x-ms-documentdb-query-enablecrosspartition" = "True"
}
$body = '{"query": "SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at", "parameters": []}'
Invoke-RestMethod -Method Post `
-Uri "https://cosmos-maf-servicedesk-4224.documents.azure.com/dbs/howto/colls/events/docs" `
-Headers $headers -ContentType "application/query+json" -Body $body
Then I ran it from that folder:
./query.ps1
What each part does:
az account get-access-token --scope https://cosmos.azure.com/.defaultgets an access token for Azure Cosmos DB, as the account the Azure CLI is signed in with.--query accessToken --output tsvkeeps 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.Authorizationcarries the token astype=aad&ver=1.0&sig=followed by the token. Learn's access control page listsaadas 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%3Dand%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-dateis the time of the request in the RFC 1123 format, in UTC, like Learn's exampleFri, 08 Apr 2015 03:52:31 GMT. In bash,date -uwrites it.datewrites the day and month names in the machine's language, soLC_ALL=Ckeeps 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-31is the version of the REST API, the same version Learn's access control example sends.Content-Type: application/query+jsonandx-ms-documentdb-isquery: Truetell Cosmos DB that thisPOSTis a query, as Learn's page on querying with the REST API asks.x-ms-documentdb-query-enablecrosspartition: Truelets 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.--datain curl and$bodyin PowerShell send the query with an emptyparameterslist. Learn marks bothqueryandparametersas required.--silenthides curl's progress meter, and--write-outprints the HTTP status code after the answer: curl's manual describeshttp_codeas the numerical response code of the last transfer.- In PowerShell,
$headersholds the same headers, andInvoke-RestMethodsends thePOSTwith-ContentTypeand-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:
- bash / zsh
- PowerShell
{"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
Invoke-RestMethod: /Users/you/source/GatewayQuery/query.ps1:10
Line |
10 | Invoke-RestMethod -Method Post `
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| { "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":
| "{\u0022partitionedQueryExecutionInfoVersion\u0022:2,\u0022queryInfo\u0022:{\u0022distinctType\u0022:\u0022None\u0022,\u0022top\u0022:null,\u0022offset\u0022:null,\u0022limit\u0022:null,\u0022orderBy\u0022:[\u0022Ascending\u0022],\u0022orderByExpressions\u0022:[\u0022c.at\u0022],\u0022groupByExpressions\u0022:[],\u0022groupByAliases\u0022:[],\u0022aggregates\u0022:[],\u0022groupByAliasToAggregateType\u0022:{},\u0022rewrittenQuery\u0022:\u0022SELECT c._rid, [{\\\u0022item\\\u0022: c.at}] AS orderByItems, {\\\u0022deviceId\\\u0022: c.deviceId, \\\u0022name\\\u0022: c.name, \\\u0022at\\\u0022: c.at} AS payload\\nFROM c\\nWHERE ({documentdb-formattableorderbyquery-filter})\\nORDER BY c.at\u0022,\u0022hasSelectValue\u0022:false,\u0022dCountInfo\u0022:null,\u0022hasNonStreamingOrderBy\u0022:false},\u0022queryRanges\u0022:[{\u0022min\u0022:\u0022\u0022,\u0022max\u0022:\u0022FF\u0022,\u0022isMinInclusive\u0022:true,\u0022isMaxInclusive\u0022:false}],\u0022hybridSearchQueryInfo\u0022:null}" }
I replaced the activity ID with zeros. Here is the curl run:

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:
- Parse the SQL query to determine the query execution plan.
- 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.
- 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.
- bash / zsh
- PowerShell
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'
{"_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
The array goes in single quotes: To make double-quotation marks appear in a string, enclose the entire string in single quotation marks. Save this as query-one.ps1:
$token = az account get-access-token --scope https://cosmos.azure.com/.default --query accessToken --output tsv
$headers = @{
"Authorization" = "type%3Daad%26ver%3D1.0%26sig%3D$token"
"x-ms-date" = [DateTime]::UtcNow.ToString("r")
"x-ms-version" = "2018-12-31"
"x-ms-documentdb-isquery" = "True"
"x-ms-documentdb-partitionkey" = '["front-door"]'
}
$body = '{"query": "SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at", "parameters": []}'
Invoke-RestMethod -Method Post `
-Uri "https://cosmos-maf-servicedesk-4224.documents.azure.com/dbs/howto/colls/events/docs" `
-Headers $headers -ContentType "application/query+json" -Body $body
./query-one.ps1
_rid Documents _count
---- --------- ------
oCZPAP4tLuU= {@{deviceId=front-door; name=Door opened; at=12/3/2026 10:00:00 AM}, @{deviceId=front-door; name=Door closed; at=12/3/2026 10:00:10 AM}} 2
Invoke-RestMethod turned the JSON answer into an object with three properties, _rid, Documents and _count, and printed it as one row. To list only the events, keep the answer in a variable and print its Documents. Save this as query-one-documents.ps1:
$token = az account get-access-token --scope https://cosmos.azure.com/.default --query accessToken --output tsv
$headers = @{
"Authorization" = "type%3Daad%26ver%3D1.0%26sig%3D$token"
"x-ms-date" = [DateTime]::UtcNow.ToString("r")
"x-ms-version" = "2018-12-31"
"x-ms-documentdb-isquery" = "True"
"x-ms-documentdb-partitionkey" = '["front-door"]'
}
$body = '{"query": "SELECT c.deviceId, c.name, c.at FROM c ORDER BY c.at", "parameters": []}'
$response = Invoke-RestMethod -Method Post `
-Uri "https://cosmos-maf-servicedesk-4224.documents.azure.com/dbs/howto/colls/events/docs" `
-Headers $headers -ContentType "application/query+json" -Body $body
$response.Documents
./query-one-documents.ps1
deviceId name at
-------- ---- --
front-door Door opened 12/3/2026 10:00:00 AM
front-door Door closed 12/3/2026 10:00:10 AM
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:
<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:
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);

AzureCliCredentialsigns 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.Webreads items with System.Text.Json and camelCase names, so the storeddeviceIdfills the record'sDeviceId.GetItemQueryIterator<StoredEvent>takes the same query and noQueryRequestOptions, so there's no partition key, and the SDK runs it across partitions.HasMoreResultsandReadNextAsync()read the results page by page, and the loop prints each event's time, sensor and name.record StoredEventholds the three fields the query selects.
Run it:
dotnet run
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:

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

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

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Sending a query with TOP, ORDER BY, OFFSET LIMIT, an aggregate, DISTINCT or GROUP BY across partitions to the REST API | Status 400 with this message, and no items | Send x-ms-documentdb-partitionkey, or run the query with an SDK |
| Taking then you can safely ignore this message at its word outside an SDK | The request failed: status 400, nothing returned | Outside an SDK, treat it as the error it is |
| Reading the 400 as a mistake in the SQL | Learn's response table lists 400 as The syntax of the SQL statement is incorrect, so you look for a typo that isn't there | Read the message: it names the gateway, not the syntax |
| Expecting the one-partition request to return every sensor | Only that partition's items come back: 2 of the 4 events here | Use an SDK when you need one list across partitions |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| HTTP 400 with The provided cross partition query can not be directly served by the gateway | A query the gateway can't serve across partitions, sent with no partition key | Add x-ms-documentdb-partitionkey, or use an SDK |
PowerShell stops at Invoke-RestMethod and prints the same JSON as an error | The same status 400: Invoke-RestMethod shows the error answer as a PowerShell error | The same two fixes |
| Status 200, but only some of the items | The partition key header limits the query to one partition | Use 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
- Querying Azure Cosmos DB resources using the REST API — the queries the gateway can't serve, and this exact message.
- Common Azure Cosmos DB REST request headers —
x-ms-documentdb-partitionkey,x-ms-documentdb-query-enablecrosspartitionandx-ms-date. - Access control in the Azure Cosmos DB SQL API — the
Authorizationheader and theaadtoken type. - Tuning query performance with Azure Cosmos DB — how an SDK runs a query in each partition and merge-sorts an ORDER BY.
- az account get-access-token — the command that gets the token, and its
--scopeparameter.
