Set Up Azure Cosmos DB
Learn to set up an Azure Cosmos DB account step by step. This lesson covers the core concepts, a hands-on walkthrough, and troubleshooting tips to get you started quickly.
Focus: set up azure cosmos db account
You’ve got a killer app idea, but where do you put the data? If you’re like most developers, you’ve spent countless hours wrestling with database provisioning, scaling, and maintenance — all before writing a single line of application code. The pain is real: managing connection strings, dealing with slow query performance, and worrying about downtime. In this lesson, you’ll learn how to set up an Azure Cosmos DB account — the fully managed, multi-model database service that eliminates most of that infrastructure headache. By the end, you’ll have a running Cosmos DB account with a database and container, ready to power your next cloud-native application.
The problem this lesson solves
Provisioning a production-ready database is a rite of passage that often turns into a survival test. Traditional approaches force you to:
- Manually provision virtual machines or clusters — you become a part-time DBA, patching OSes and managing backups.
- Guess capacity upfront — you either over-provision and waste money or under-provision and hit performance walls.
- Wrestle with multi-region replication — setting up geo-redundancy across continents is a distributed systems nightmare.
- Handle schema migrations — relational schemas lock you into rigid structures when your data model evolves.
Azure Cosmos DB eliminates these problems. It’s a globally distributed, multi-model database service that offers single-digit millisecond read and write latencies at any scale, guaranteed SLAs, and automatic horizontal scaling. You don’t provision a server; you create an account, and Azure handles the rest.
The pain this lesson solves is the setup barrier. Even though Cosmos DB is fully managed, you still need to make a few critical decisions during account creation — choosing the right API, capacity mode, and consistency level. Getting these wrong can cost you real money or haunt you with performance issues later. Let’s get them right the first time.
Core concept / mental model
Think of an Azure Cosmos DB account as a smart database container that lives in the cloud. Instead of renting a virtual machine and installing database software, you create a logical account that Azure physically hosts across one or more Azure regions. The account is your entry point — it holds the connection string and globally unique endpoint.
Here’s the hierarchy you need to internalize:
Azure Cosmos DB Account
└── Database (logical container for collections)
└── Container (stores JSON documents, has a partition key)
└── Items (the actual data — JSON documents)
- Account: The top-level unit. It has a globally unique DNS name, like
myapp-cosmos.documents.azure.com. It is not a server; it’s a grouping of databases with a set of shared configurations (consistency, replication, etc.). - Database: A logical grouping of containers. Think of it like a namespace within the account.
- Container: The actual data store. It is schema-agnostic (you store JSON documents) and has a partition key that determines how data is distributed across physical partitions.
- Item: A single JSON document inside a container. This is your actual data record.
Why the account abstraction matters
Because the account is a logical boundary, you can apply global distribution at the account level. With a single Azure PowerShell command, you can add a read region in Europe and a write region in Asia, and Cosmos DB handles replication, failover, and consistency — no extra infrastructure on your part.
Pro tip: Think of the account like a phone number — it’s a single, stable identifier that never changes. Your application code connects to the account endpoint, not to specific databases or containers. This decoupling means you can restructure your data without rewriting connection logic.
How it works step by step
Setting up an Azure Cosmos DB account follows a logical sequence. You’ll make architectural decisions at each step that affect performance and cost. Let’s walk through the decision tree.
- Choose an API (data model). Cosmos DB is multi-model, but you must pick one API at account creation. Your options include Core (SQL), MongoDB, Cassandra, Gremlin, and Table. Choose the API that matches your current stack or your team’s familiarity.
- Choose a capacity mode. You can pick Provisioned throughput (you specify RU/s — Request Units per second) or Serverless (you pay per request, no reserved capacity). Serverless is ideal for dev/test or spiky workloads.
- Choose a consistency level. Azure offers five levels, from Strong to Eventual, each with a trade-off between consistency and latency. For most apps, Session is the sweet spot — it gives you read-your-writes in a single session.
- Configure networking (optional). You can enable Azure Private Link for private IP connectivity, or keep the default public endpoint with IP firewall rules.
- Create the account. You can use the Azure portal, Azure CLI, PowerShell, ARM templates, or Terraform. The portal is easiest for a first-time setup.
- Create a database and container. Within the account, you define a database and at least one container. The container must have a partition key — the most critical design decision.
Understanding partition keys (the real work)
A partition key is a property in your JSON documents (e.g., userId, tenantId). Cosmos DB uses this key to distribute data across physical partitions for horizontal scaling. Choosing a bad key can cause hot partitions (all traffic hitting one partition) and throttling.
Pro tip: Choose a high-cardinality key — one with many possible values (like a user ID or GUID). Avoid low-cardinality keys like
status(e.g.,activevsinactive), which will create a hot partition bottleneck.
Hands-on walkthrough
Let’s put theory into practice. You have two paths: the Azure portal (graphical, easy) and the Azure CLI (scriptable, repeatable). We’ll cover both so you can choose your workflow.
Option 1: Azure Portal (visual approach)
- Go to portal.azure.com and sign in.
- Click Create a resource, search for Azure Cosmos DB, and select Create.
- In the Basics tab:
- Subscription: Select your Azure subscription.
- Resource Group: Create a new one (e.g.,
rg-cosmos-demo) or use an existing one. - Account Name: Enter a unique name (e.g.,myapp-cosmos-account). - API: Choose Core (SQL) for this tutorial. - Location: Select your nearest region (e.g.,East US). - Capacity Mode: Select Serverless for simplicity. - Configure Networking as Public endpoint (default).
- Click Review + create, then Create. Wait for the deployment to finish.
Option 2: Azure CLI (scriptable approach)
First, log in and set your subscription:
az login
az account set --subscription "your-subscription-id"
Then create the account, database, and container:
# Create the account (Core SQL API, single-region, provisioned throughput)
az cosmosdb create \
--name myapp-cosmos-account \
--resource-group rg-cosmos-demo \
--kind GlobalDocumentDB \
--locations regionName="East US" failoverPriority=0 isZoneRedundant=False \
--default-consistency-level Session
# Create a database
az cosmosdb sql database create \
--account-name myapp-cosmos-account \
--resource-group rg-cosmos-demo \
--name appdb
# Create a container with a partition key
az cosmosdb sql container create \
--account-name myapp-cosmos-account \
--resource-group rg-cosmos-demo \
--database-name appdb \
--name users \
--partition-key-path "/userId" \
--throughput 400
Expected output (abbreviated):
{
"id": "/subscriptions/.../resourceGroups/rg-cosmos-demo/providers/Microsoft.DocumentDB/databaseAccounts/myapp-cosmos-account/sqlDatabases/appdb/containers/users",
"name": "users",
"partitionKey": { "kind": "Hash", "paths": ["/userId"] },
"throughput": 400
}
Connect from Python
Now that your account is running, let’s connect from Python. First, install the SDK:
pip install azure-cosmos
Then write a small script:
from azure.cosmos import CosmosClient, PartitionKey
# Replace with your own values from the Azure portal
ENDPOINT = "https://myapp-cosmos-account.documents.azure.com:443/"
KEY = "your-account-key-from-portal" # never hardcode in production!
# Create client
client = CosmosClient(ENDPOINT, KEY)
# Create database and container (idempotent if they exist)
db = client.create_database_if_not_exists(id="appdb")
container = db.create_container_if_not_exists(
id="users",
partition_key=PartitionKey(path="/userId")
)
# Insert an item
item = {
"id": "user-001",
"userId": "alice",
"email": "alice@example.com",
"signupDate": "2025-01-15"
}
container.upsert_item(item)
# Read it back
read_item = container.read_item(item="user-001", partition_key="alice")
print(read_item["email"]) # Output: alice@example.com
Pro tip: In production, never put keys in code. Use Azure Key Vault or Managed Identity — you’ll cover that later in this track.
Expected output: The script prints alice@example.com after inserting and reading the item.
Compare options / when to choose what
When you set up an Azure Cosmos DB account, you’ll face several key decisions. Here’s a comparison of the main options:
| Decision | Option A | Option B | When to use |
|---|---|---|---|
| API | Core (SQL) | MongoDB API | Use Core (SQL) if you write SQL-like queries; use MongoDB API if you have existing Mongo code or tooling. |
| Capacity mode | Provisioned (RU/s) | Serverless | Use Provisioned for predictable, always-on production workloads; Serverless for dev/test or spiky traffic. |
| Consistency | Strong | Eventual | Use Strong for financial transactions; Eventual for social feeds or low-latency global reads. |
| Replication | Single-region | Multi-region write | Start single-region to save cost; add multi-region only when you genuinely need global low-latency writes. |
Recommendation: For most tutorials and prototypes, start with Core (SQL), Serverless, and Session consistency. You can always migrate later, but changing these choices after creation is more work.
Variations: alternative setup paths
- Terraform: You can define your Cosmos DB account with an infrastructure-as-code template, making it reproducible across environments. Example snippet:
hcl resource "azurerm_cosmosdb_account" "main" { name = "myapp-cosmos" resource_group_name = azurerm_resource_group.main.name location = azurerm_resource_group.main.location offer_type = "Standard" kind = "GlobalDocumentDB" consistency_policy { consistency_level = "Session" } } - ARM templates: Use Azure Resource Manager templates to deploy the account as part of a release pipeline.
Troubleshooting & edge cases
You’re likely to hit a few common snags during setup. Here’s how to diagnose and fix them:
| Symptom | Likely Cause | Fix |
|---|---|---|
ResourceNotFound when accessing a container |
Container name is wrong or not created yet | Double-check the container name and ensure the create_container_if_not_exists code runs without errors. |
RequestRateTooLargeException (HTTP 429) |
You exceeded provisioned throughput (RU/s) | Increase throughput, switch to Serverless, or optimize queries with better partitioning. |
AuthorizationFailed on connection |
Incorrect account key or expired SAS token | Regenerate the key in the portal and update your connection string. |
| Account name already taken | Cosmos DB account names must be globally unique | Add a random suffix, e.g., myapp-cosmos-2025 |
| High RU charges on a single query | Query is doing a cross-partition scan because the partition key isn’t in the filter | Include the partition key in your query's WHERE clause to target a single physical partition. |
Edge case: Serverless vs. provisioned throughput
If you create a Serverless account, you don’t worry about RU/s caps, but you can’t set a manual throughput limit. In dev environments with runaway loops, this can bill you more than expected. Always set up budget alerts if you go Serverless.
Another edge case: consistency level changes. You can change the default consistency level after creation, but it can cause a brief account reconfiguration. If you’re in production, schedule this as a maintenance activity.
What you learned & what's next
You’ve just set up an Azure Cosmos DB account — the fully managed, globally distributed database that removes the infrastructure burden from your app. You now understand the account/database/container/item hierarchy, can choose between Core SQL and other APIs, and can pick the right capacity mode and consistency level. You’ve also written Python code that connects, inserts, and reads a document — proof that your setup works.
Key takeaways:
- An Azure Cosmos DB account is a logical container with a global endpoint, not a physical server.
- The partition key is your most important design decision for performance and cost.
- Choose Serverless for dev/test, Provisioned for predictable production throughput.
- Session consistency is the default and best for most apps.
- You can set up the account via portal, CLI, or Terraform — all equally valid.
Next up: In the next lesson, you’ll learn how to secure your Cosmos DB account — networking, firewall rules, and managed identity. Your set up azure cosmos db account skills will be the foundation for that deeper security dive.
Pro tip: Before moving on, try deleting your test account and recreating it using the Azure CLI script in this lesson. Automation is a muscle — flex it now so you’re ready for production.
Now go create your account, and let’s keep building.
Practice recap
To reinforce this lesson, create a new Cosmos DB account using the CLI script above with a unique name. Then write a Python script that inserts 100 fake user items into your container using a loop and a high-cardinality userId partition key. Finally, query a few items back by their partition key and observe the low RU cost. This will solidify your partition-key design intuition before moving on to security.
Common mistakes
- Choosing a low-cardinality partition key (e.g.,
statusorcountry) — leads to hot partitions, throttling, and higher RU consumption. Always pick a key with many distinct values. - Forgetting that Cosmos DB account names must be globally unique across all Azure — the portal will reject
cosmos-db-accountif it's taken. Add a unique suffix. - Hardcoding the account key in Python or committing it to git — a serious security leak. Use environment variables or Azure Key Vault instead.
- Assuming all APIs are interchangeable — you can’t change the API after account creation, so choose Core (SQL) vs. MongoDB wisely from day one.
- Using
create_container_if_not_existsin a hot path — it performs a read and may incur extra RU. Create containers once at startup or via deployment scripts.
Variations
- Use the Azure portal for a one-off graphical setup, but adopt Azure CLI or Terraform for reproducible, automated deployments.
- If you have existing MongoDB code, choose the MongoDB API instead of Core SQL — you get the same Cosmos DB backend with a familiar driver.
- Leverage ARM templates or Bicep to deploy the account as part of your CI/CD pipeline, ensuring consistency across environments.
Real-world use cases
- A global e-commerce app using Cosmos DB with Session consistency to keep shopping carts low-latency in multiple regions.
- An IoT telemetry pipeline ingesting millions of sensor readings per second, using provisioned throughput and a deviceId partition key.
- A gaming leaderboard backend that needs sub-10ms reads and automatic failover, using Core SQL API and multi-region writes.
Key takeaways
- The Azure Cosmos DB account is the top-level logical unit — it hosts databases, containers, and items, and exposes a unique endpoint.
- Master the account-database-container hierarchy; you manage containers, not tables, and each container requires a partition key.
- Choose your API once at creation — Core SQL for SQL-like queries, MongoDB API for existing Mongo tools.
- Select capacity mode and consistency level thoughtfully — Serverless for dev/test, Session as the default consistency for most apps.
- The partition key is the single most critical design choice for performance, scalability, and cost in Cosmos DB.
- Hands-on: you can now create an account via portal or CLI, connect with Python, and run your first CRUD operation.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.