The Fastest Way to Purge a Tenant in Cosmos DB — If You Know the Hidden Switch
In multi-tenant systems, it’s often necessary to completely and permanently remove a tenant’s data — whether for regulatory reasons, cleanup, or customer requests.
When using Azure Cosmos DB, which is commonly partitioned by tenant ID for scalability and isolation, this raises the question: how can we efficiently delete all data for a given tenant without manually scanning and deleting documents?
The Ideal API for Partition Deletion
Cosmos DB offers a feature that allows you to delete all items associated with a particular partition key via a single API call. This is incredibly appealing when you want to purge a tenant’s data at the drop of a hat.
Here’s what that looks like in code:
public async Task<bool> PurgeAsync(string tenantId, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(tenantId)) throw new ArgumentException("tenantId is required.", nameof(tenantId));
try
{
var resp = await _container.DeleteAllItemsByPartitionKeyStreamAsync(
new PartitionKey(tenantId),
cancellationToken: ct);
var statusCode =resp.StatusCode;
// Cosmos returns 204 NoContent on success (even if there were 0 docs)
return (int)statusCode is >= 200 and < 300;
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// Partition key doesn’t “exist” if there were no items; treat as not found if you prefer
return false;
}
}
This method wraps the DeleteAllItemsByPartitionKeyStreamAsync call, which removes all documents under the specified partition key. It handles standard success and not-found cases cleanly.
However, if you try running this against a Cosmos DB account that hasn’t explicitly enabled this feature, you’ll encounter a problem.
When the API Fails: Feature Not Enabled
Attempting to use the partition delete feature on a Cosmos account that doesn’t have it enabled results in a 400 BadRequesterror. The following message is returned:
Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: ff39a801–3f3e-4ddf-95f0–312ce46cf099; Reason: (Message: {“Errors”:[“Partition key delete feature is disabled for this account. Please contact Azure Support [https://azure.microsoft.com/support] to enable it.”]}
ActivityId: ff39a801–3f3e-4ddf-95f0–312ce46cf099, Request URI: /apps/2d6d2718–68a8–48dd-90e1–4411fee456e7/services/31811aac-37b4–42e7-a642–06997302cc1b/partitions/506465ed-df7d-4c2a-9279–81abdb8c9496/replicas/134056320013380986p/, RequestStats: , SDK: Microsoft.Azure.Documents.Common/2.14.0, Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, Windows/10.0.26200 cosmos-netstandard-sdk/3.41.0);
This error makes it clear: you must explicitly enable partition-level deletes at the Cosmos DB account level before this operation will work.
Enabling Partition Deletes in Terraform
To resolve the issue, I updated the Terraform configuration for the Cosmos DB account to enable the required capability:
resource "azurerm_cosmosdb_account" "main" {
name = "cosmos-${random_string.suffix.result}"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
kind = "GlobalDocumentDB"
offer_type = "Standard"
capabilities {
name = "DeleteAllItemsByPartitionKey"
}
// Other config...
}
This adds the “DeleteAllItemsByPartitionKey” capability to the Cosmos DB account. Note that this is a capability flag, not a default behavior—even if your account has been running for a while, it won’t support this feature unless explicitly enabled.
The Wait: Immediate Enablement Isn’t Guaranteed
After applying the Terraform change, I re-ran my integration tests expecting immediate success. However, I continued to receive the same 400 BadRequest error for a short while. This suggests that enabling the feature is eventually consistent—there may be a brief propagation delay before the capability becomes fully active on the backend.
After a few minutes, the feature kicked in, and I was able to successfully delete partitions using the DeleteAllItemsByPartitionKeyStreamAsync API.
Conclusion
Deleting a tenant’s data efficiently in Cosmos DB is possible, but it hinges on enabling the right feature: DeleteAllItemsByPartitionKey. This feature streamlines partition deletion down to a single API call, making tenant data purging reliable and performant. Just be aware of the configuration requirement and allow time for the change to take effect after provisioning it via Terraform or other IaC tools. Once enabled, it’s a simple and effective solution for tenant-level data management.
