Throughput Migration with PowerShell
Complete the full lesson to earn 25 points — 50 with Pro
Work through each section, then tap “Mark as Complete” on the last one.
✦ Skip the page breaks, the wait, and see fewer ads — read each lesson on a single page with Pro
Module: Maintain Azure Cosmos DB Solution
Section: DevOps Implementation
Lesson: Throughput Migration with PowerShell
Introduction: The Importance of Throughput Management
Azure Cosmos DB is designed to provide predictable performance at any scale, primarily through the mechanism of Request Units (RUs). As your application needs evolve—whether due to seasonal traffic spikes, new product launches, or shifts in data access patterns—the ability to adjust throughput becomes a critical operational requirement. While the Azure Portal offers a graphical interface for these changes, relying on manual clicks in a production environment is fraught with risk. It introduces human error, lacks an audit trail, and prevents the repeatable, version-controlled workflows that modern DevOps practices demand.
Throughput migration—the process of transitioning between manual throughput, autoscale throughput, or even migrating between different provisioned tiers—is a fundamental skill for any cloud engineer. By leveraging PowerShell and the Azure command-line tools, you can codify these scaling operations, integrate them into CI/CD pipelines, and ensure that your database performance evolves in lockstep with your application code. This lesson explores the technical mechanics of managing Cosmos DB throughput using PowerShell, focusing on automation, safety, and operational efficiency.
Understanding Throughput Models in Cosmos DB
Before diving into the scripts, it is essential to distinguish between the two primary ways you can provision throughput for your containers and databases in Cosmos DB. Understanding these models is the foundation for any migration strategy.
- Manual Throughput: This is the classic model where you provision a specific amount of RUs per second. This capacity is dedicated to the container or database and remains constant regardless of actual demand. It is cost-effective for steady, predictable workloads where you know exactly how many resources you need.
- Autoscale Throughput: In this model, Cosmos DB automatically scales your provisioned RUs based on the incoming request volume. You set a maximum RU limit, and the system scales between 10% of that maximum and the full maximum value. This is ideal for unpredictable workloads or environments where traffic fluctuates significantly throughout the day.
Callout: Throughput Migration vs. Scaling It is important to distinguish between "scaling" and "migration." Scaling refers to increasing or decreasing the RU value within the same throughput model (e.g., moving from 400 RU/s to 1000 RU/s manually). Throughput migration refers to changing the provisioning type itself, such as converting a container from manual throughput to autoscale, or migrating a container from a shared throughput database to dedicated container-level throughput.
Prerequisites for PowerShell Automation
To manage Cosmos DB via PowerShell, you must have the correct environment configured. The primary tool for this is the Az.CosmosDB module, which is part of the broader Azure PowerShell module set. Before you begin writing scripts, ensure your local development machine or build agent is ready.
- Install the Module: Ensure you have the latest version of the module installed by running
Install-Module -Name Az.CosmosDB -AllowClobber -Scope CurrentUser. - Authentication: You must be authenticated to your Azure environment. Use
Connect-AzAccountto sign in. If you are running this in a DevOps pipeline, use a Service Principal with the "DocumentDB Account Contributor" role assigned at the resource group or subscription level. - Context: Always set your subscription context using
Set-AzContext -SubscriptionId <YourSubscriptionID>to prevent accidental changes to the wrong environment.
Migrating from Manual to Autoscale Throughput
One of the most frequent operational tasks is converting a container that has reached its capacity limits under a manual model to an autoscale model. Autoscale provides a buffer against sudden traffic spikes without requiring manual intervention.
To perform this migration using PowerShell, you use the Update-AzCosmosDBSqlContainer cmdlet. The key is to define the AutoscaleMaxThroughput parameter while simultaneously removing the fixed throughput setting.
Example: Migrating a Container to Autoscale
# Define variables for the migration
$resourceGroupName = "Production-RG"
$accountName = "my-cosmos-db-account"
$databaseName = "OrderDatabase"
$containerName = "Orders"
$maxAutoscaleRUs = 4000
# Perform the migration
# By setting AutoscaleMaxThroughput, the system automatically switches the mode
Update-AzCosmosDBSqlContainer -ResourceGroupName $resourceGroupName `
-AccountName $accountName `
-DatabaseName $databaseName `
-Name $containerName `
-AutoscaleMaxThroughput $maxAutoscaleRUs
Explanation of the Code:
The Update-AzCosmosDBSqlContainer cmdlet is powerful because it handles the underlying API transition. When you specify AutoscaleMaxThroughput, the Azure Resource Manager (ARM) provider recognizes the intent to change the provisioning model. The database engine calculates the necessary resources to switch the container to autoscale, using the value provided as the maximum ceiling.
Note: When you migrate to autoscale, the minimum throughput is automatically set to 10% of your maximum. For example, if you set
AutoscaleMaxThroughputto 4000, your container will fluctuate between 400 and 4000 RU/s.
Managing Throughput within a Shared Database
In many architectures, developers choose to provision throughput at the database level rather than the container level. This allows multiple containers to share a pool of RUs, which is often more cost-efficient for microservices that share a common data store. Migrating throughput in this context requires targeting the database resource instead of the individual container.
Example: Updating Shared Database Throughput
$resourceGroupName = "Production-RG"
$accountName = "my-cosmos-db-account"
$databaseName = "SharedOrdersDB"
$newThroughput = 2000
# Update the database throughput directly
Update-AzCosmosDBSqlDatabaseThroughput -ResourceGroupName $resourceGroupName `
-AccountName $accountName `
-Name $databaseName `
-Throughput $newThroughput
This operation is useful when you notice that one specific container within the shared database is consistently hitting its limits, and you need to scale the entire "pool" to accommodate the increased demand.
Best Practices for Production Throughput Migration
Performing throughput changes in a live environment requires caution. Sudden changes can cause throttling if not handled correctly, and improper automation can lead to unexpected billing costs.
- Implement "Dry Run" Logic: Before executing a change, always query the current throughput settings. Use
Get-AzCosmosDBSqlContainerThroughputto verify the state before applying updates. - Use Incremental Scaling: If you need to increase throughput significantly, do it in steps if possible, rather than jumping from 400 RU/s to 100,000 RU/s. While Azure allows large jumps, gradual scaling is safer for the application's request pipeline.
- Monitor Throttling (429 Errors): After a migration, watch your monitoring metrics closely. If you see a spike in 429 (Too Many Requests) errors, it indicates that your migration did not provide enough throughput to cover the current demand.
- Version Control Your Scripts: Never run these commands ad-hoc from a console. Store your migration scripts in a source control repository (like Git). This allows you to track who changed the throughput, when it was changed, and why.
- Least Privilege Access: Ensure the Service Principal running the automation has exactly the permissions it needs. Do not use Global Administrator or Subscription Owner roles for automation scripts.
Handling Common Pitfalls
Even with the best automation, errors can occur. Below are common challenges encountered during throughput migration and how to resolve them.
1. The "Throughput Limit Reached" Error
Sometimes you may try to scale up, but the request fails because you are attempting to exceed the maximum allowed throughput for your account. This is often a hard limit set by Azure quotas.
- Solution: Check your Azure subscription quotas in the portal. If you need more, you must file a support ticket to increase the quota for your specific region and account type.
2. Migrating Back to Manual
There is no direct "down-grade" command that switches from autoscale back to manual in a single step in all versions of the SDK.
- Solution: To move back to manual, you typically need to update the container and specify a fixed
Throughputvalue. The API will interpret this as a request to disable autoscale and return to a fixed provisioned state.
3. Execution Timeouts
In very large databases, a throughput update might take a few minutes to propagate across all partitions. If your script waits for a synchronous response, it might timeout.
- Solution: Use the
-AsJobparameter in PowerShell to run the update in the background, or implement a retry-loop that checks the status of the operation usingGet-AzCosmosDBAccountor similar monitoring cmdlets.
Warning: Cost Implications Autoscale throughput is generally more expensive per RU than manual throughput because you are paying for the flexibility of the system to scale up. If you have a workload that is perfectly flat and predictable, using autoscale might result in unnecessary costs. Always calculate the cost difference using the Azure Pricing Calculator before migrating production workloads.
Step-by-Step: Automating Throughput via CI/CD
To truly integrate this into your workflow, you should execute these migrations through a pipeline (e.g., Azure DevOps or GitHub Actions). Here is a conceptual workflow for automating this process:
- Define Configuration Files: Create a JSON or YAML file in your repo that defines the desired throughput for each environment (e.g.,
Dev: 400,Prod: 2000). - Pipeline Trigger: Create a pipeline that triggers on a file change or a manual "Run" command.
- Authentication: The pipeline uses a Service Principal to authenticate to Azure.
- Validation: The script reads the target throughput from your config file, compares it against the existing container throughput, and performs the update only if a change is required.
- Logging: The script logs the output of the
Update-AzCosmosDBSqlContainercommand to your pipeline logs for audit purposes.
Example: Conditional Update Script
# Logic to prevent unnecessary updates
$current = Get-AzCosmosDBSqlContainerThroughput -ResourceGroupName $rg -AccountName $acc -DatabaseName $db -Name $cont
$target = 2000
if ($current.Throughput -ne $target) {
Write-Host "Updating throughput to $target"
Update-AzCosmosDBSqlContainerThroughput -ResourceGroupName $rg -AccountName $acc -DatabaseName $db -Name $cont -Throughput $target
} else {
Write-Host "Throughput is already at target level."
}
This conditional logic prevents the "no-op" operations that waste time and could potentially trigger unnecessary API calls or logs.
Comparison: Manual vs. Autoscale Throughput
| Feature | Manual Throughput | Autoscale Throughput |
|---|---|---|
| Scaling | Manual/Programmatic | Automatic |
| Cost | Fixed per hour | Variable based on usage |
| Best For | Steady, predictable traffic | Bursty, unpredictable traffic |
| Min Throughput | 400 RU/s | 10% of Max RU/s |
| Performance | Constant, no cold start | Scales up with latency |
Advanced Scenarios: Serverless Mode
It is worth noting that Cosmos DB also offers a "Serverless" mode. Serverless is not a migration of throughput, but rather a different architectural choice. In serverless, you do not provision any throughput. You are charged only for the RUs consumed by your requests.
If your application has very infrequent traffic (e.g., a background job that runs once a day), migrating to Serverless might be more cost-effective than using autoscale or manual throughput. However, Serverless does not support stored procedures, triggers, or cross-partition queries as efficiently as provisioned throughput, so it is not a drop-in replacement for all workloads.
Troubleshooting and Verification
Once you have performed a migration, verification is the final step in the DevOps lifecycle. You should never assume the migration was successful simply because the PowerShell script completed without error.
- Verify via PowerShell: Immediately run
Get-AzCosmosDBSqlContainerThroughputafter your migration script to inspect theThroughputorAutoscaleMaxThroughputproperties. - Monitor via Azure Monitor: Go to the Azure Portal and check the "Metrics" blade for your Cosmos DB account. Look for "Total Request Units" and "Provisioned Throughput." This will show you exactly when the change took effect and how the system is behaving under the new configuration.
- Check Audit Logs: Use the "Activity Log" in the Azure Portal to view the operation details. The activity log will show the user or Service Principal that initiated the change, providing a clear audit trail for compliance.
Callout: Throughput and Partitioning Always remember that throughput is tied to your partitioning strategy. If your data is "hot" (one partition receiving all the traffic), increasing throughput might not solve your performance issues. You must have a balanced partition key to ensure that the provisioned RUs are distributed effectively across the physical partitions. If you find yourself constantly increasing throughput without seeing performance gains, it is time to re-evaluate your partition key choice rather than just throwing more RUs at the problem.
Summary of Key Takeaways
- Automation is Mandatory: Never manage Cosmos DB throughput manually in production. Use PowerShell to ensure consistency, reproducibility, and auditability.
- Choose the Right Model: Understand the difference between Manual and Autoscale. Use Manual for predictable, steady traffic and Autoscale for unpredictable, bursty traffic.
- Implement Guardrails: Use conditional logic in your scripts to verify current settings before initiating changes. This avoids unnecessary API calls and potential throttling.
- Prioritize Monitoring: Always verify throughput changes via Azure Monitor metrics and Activity Logs. Do not rely solely on the success of the PowerShell script output.
- Consider Partitioning: Throughput is a solution for capacity, not a fix for poor partitioning. Always ensure your partition key is well-distributed before scaling up.
- CI/CD Integration: Integrate your throughput scripts into your deployment pipelines. This ensures that infrastructure changes are treated with the same rigor as application code changes.
- Cost Awareness: Autoscale can be more expensive than manual throughput. Perform cost analysis before switching to ensure it aligns with your budget and traffic patterns.
By mastering the use of PowerShell for Cosmos DB throughput management, you transition from reactive database administration to proactive, automated infrastructure management. This skill is vital for maintaining the performance and cost-efficiency of modern cloud applications. As you apply these techniques, remember that the goal is not just to scale, but to scale intelligently and safely, ensuring that your application remains responsive to users while keeping operational costs within expected bounds.
Reach the last section to complete this lesson and earn points — you're on section 1 of 11.
- Introduction to Cosmos DB Data Modeling
- Introduction to Cosmos DB Data Modeling Quiz5q
- Multiple Entity Types in Same Container
- Multiple Entity Types in Same Container Quiz5q
- Storing Related Entities in Same Document
- Storing Related Entities in Same Document Quiz5q
- Denormalizing Data Across Documents
- Denormalizing Data Across Documents Quiz5q
- Referencing Between Documents
- Referencing Between Documents Quiz5q
- Partition Keys and Document IDs
- Partition Keys and Document IDs Quiz5q
- Time to Live (TTL) Configuration
- Time to Live (TTL) Configuration Quiz5q
- Document Versioning Strategies
- Document Versioning Strategies Quiz5q
- Schema Versioning Patterns
- Schema Versioning Patterns Quiz5q
- Choosing Partition Strategies
- Choosing Partition Strategies Quiz5q
- Partition Key Selection Best Practices
- Partition Key Selection Best Practices Quiz5q
- Transactions and Partition Keys
- Transactions and Partition Keys Quiz5q
- Cross-Partition Query Costs
- Cross-Partition Query Costs Quiz5q
- Data Distribution Analysis
- Data Distribution Analysis Quiz5q
- Throughput Distribution Planning
- Throughput Distribution Planning Quiz5q
- Synthetic Partition Keys
- Synthetic Partition Keys Quiz5q
- Hierarchical Partition Keys
- Hierarchical Partition Keys Quiz5q
- Throughput and Storage Requirements
- Throughput and Storage Requirements Quiz5q
- Serverless vs Provisioned Throughput
- Serverless vs Provisioned Throughput Quiz5q
- Database-Level Provisioned Throughput
- Database-Level Provisioned Throughput Quiz5q
- Granular Scale Units
- Granular Scale Units Quiz5q
- Global Distribution Costs
- Global Distribution Costs Quiz5q
- Configuring Throughput in Portal
- Configuring Throughput in Portal Quiz5q
- Gateway vs Direct Connectivity Mode
- Gateway vs Direct Connectivity Mode Quiz5q
- Creating Database Connections
- Creating Database Connections Quiz5q
- Azure Cosmos DB Emulator
- Azure Cosmos DB Emulator Quiz5q
- Connection Error Handling
- Connection Error Handling Quiz5q
- Singleton Pattern for Clients
- Singleton Pattern for Clients Quiz5q
- Global Distribution Regions
- Global Distribution Regions Quiz5q
- Threading and Parallelism
- Threading and Parallelism Quiz5q
- Arrays and Nested Objects Queries
- Arrays and Nested Objects Queries Quiz5q
- Correlated Subqueries
- Correlated Subqueries Quiz5q
- Array and Type-Checking Functions
- Array and Type-Checking Functions Quiz5q
- Mathematical and String Functions
- Mathematical and String Functions Quiz5q
- Date Functions in Queries
- Date Functions in Queries Quiz5q
- Point Operations vs Query Operations
- Point Operations vs Query Operations Quiz5q
- CRUD Point Operations
- CRUD Point Operations Quiz5q
- Patch Operations for Updates
- Patch Operations for Updates Quiz5q
- Transactional Batch Operations
- Transactional Batch Operations Quiz5q
- Bulk Operations with SDK
- Bulk Operations with SDK Quiz5q
- Optimistic Concurrency with ETags
- Optimistic Concurrency with ETags Quiz5q
- Query Pagination and Continuation
- Query Pagination and Continuation Quiz5q
- Cosmos DB Mirroring for Fabric
- Cosmos DB Mirroring for Fabric Quiz5q
- Mirroring vs Spark Connector
- Mirroring vs Spark Connector Quiz5q
- Enabling Analytical Store
- Enabling Analytical Store Quiz5q
- Synapse Spark and SQL Queries
- Synapse Spark and SQL Queries Quiz5q
- Change Data Capture in Analytical Store
- Change Data Capture in Analytical Store Quiz5q
- Azure Functions and Event Hubs Integration
- Azure Functions and Event Hubs Integration Quiz5q
- Denormalization with Change Feed
- Denormalization with Change Feed Quiz5q
- Referential Integrity with Change Feed
- Referential Integrity with Change Feed Quiz5q
- Azure AI Search Integration
- Azure AI Search Integration Quiz5q
- Azure Functions Change Feed Trigger
- Azure Functions Change Feed Trigger Quiz5q
- Consuming Change Feed with SDK
- Consuming Change Feed with SDK Quiz5q
- Change Feed Estimator
- Change Feed Estimator Quiz5q
- Denormalization via Change Feed
- Denormalization via Change Feed Quiz5q
- Aggregation Persistence with Change Feed
- Aggregation Persistence with Change Feed Quiz5q
- Read-Heavy vs Write-Heavy Indexing
- Read-Heavy vs Write-Heavy Indexing Quiz5q
- Index Type Selection
- Index Type Selection Quiz5q
- Custom Indexing Policies
- Custom Indexing Policies Quiz5q
- Composite Index Implementation
- Composite Index Implementation Quiz5q
- Index Performance Optimization
- Index Performance Optimization Quiz5q
- Response Status Codes and Metrics
- Response Status Codes and Metrics Quiz5q
- Normalized RU Consumption Monitoring
- Normalized RU Consumption Monitoring Quiz5q
- Server-Side Latency Metrics
- Server-Side Latency Metrics Quiz5q
- Data Replication Monitoring
- Data Replication Monitoring Quiz5q
- Azure Monitor Alerts Configuration
- Azure Monitor Alerts Configuration Quiz5q
- Resource Logs Implementation
- Resource Logs Implementation Quiz5q
- Partition Throughput Monitoring
- Partition Throughput Monitoring Quiz5q
- Encryption Key Management
- Encryption Key Management Quiz5q
- Network-Level Access Control
- Network-Level Access Control Quiz5q
- Data Encryption Configuration
- Data Encryption Configuration Quiz5q
- Azure RBAC for Control Plane
- Azure RBAC for Control Plane Quiz5q
- Microsoft Entra ID for Data Plane
- Microsoft Entra ID for Data Plane Quiz5q
- CORS Settings Configuration
- CORS Settings Configuration Quiz5q
- Customer-Managed Keys
- Customer-Managed Keys Quiz5q
- Always Encrypted Implementation
- Always Encrypted Implementation Quiz5q
- Data Movement Strategy Selection
- Data Movement Strategy Selection Quiz5q
- SDK Bulk Operations for Data Movement
- SDK Bulk Operations for Data Movement Quiz5q
- Azure Data Factory Pipelines
- Azure Data Factory Pipelines Quiz5q
- Kafka Connector Integration
- Kafka Connector Integration Quiz5q
- Azure Stream Analytics Integration
- Azure Stream Analytics Integration Quiz5q
- Cosmos DB Spark Connector
- Cosmos DB Spark Connector Quiz5q
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles the points you earn on every lesson and quiz so you progress twice as fast, unlocks half of every practice exam — plus full case studies — with the Learn & Exam study modes, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× points per lesson & quiz
- ✓ 50% of every exam unlocked
- ✓ Learn & Exam modes
- ✓ Distraction-free lessons