Azure Cosmos DB: A Database That Lives Everywhere at Once

Azure Cosmos DB: A Database That Lives Everywhere at Once

A beginner-friendly guide to Azure Cosmos DB, Microsoft's globally distributed NoSQL database. Learn how it stores data, how it scales, what request units and partition keys mean, and how to choose the right settings.

Imagine a popular pizza chain with shops in Mumbai, London, and New York. Every shop keeps a notebook of customer orders. If each shop had its own separate notebook, a customer who ordered in Mumbai would be a stranger in London. Now imagine a magic notebook that appears in every shop at the same time, always stays up to date, never runs out of pages, and lets staff write a new order in less time than it takes to blink. That magic notebook is the idea behind Azure Cosmos DB.

1What Is Azure Cosmos DB?

Start with a plain definition, then add the details one layer at a time.

Azure Cosmos DB is a fully managed database service from Microsoft Azure. A database is simply an organized place to store information so programs can find it quickly. Cosmos DB belongs to the family called NoSQL databases, which store data in flexible shapes instead of strict tables with fixed columns.

Two features make Cosmos DB special. First, it is globally distributed, which means your data can be copied to many regions around the world with a few clicks. Second, it is built for speed and scale, so it can answer in a few milliseconds even when millions of people use your application at the same time.

It is also “fully managed”. Microsoft handles the servers, the software updates, the copies of your data, and the repairs. You focus on your application and your data, not on babysitting machines.

Simple Analogy

Think of a chain of libraries that all share one magic catalog. When someone adds a new book in Delhi, the catalog in Tokyo shows it almost instantly. Nobody has to carry boxes of cards between buildings. Cosmos DB is that shared catalog for your application data.

<10 ms
Typical read and write speed target at the 99th percentile
99.999%
Availability SLA for multi-region accounts
5
Consistency levels to choose from

2The Problems Cosmos DB Solves

A tool makes sense when you know the pain it removes.

Traditional databases were designed when applications served a few hundred people in one office. Today a mobile game, a shopping site, or a ride-sharing app may serve millions of people in dozens of countries, all at the same moment. Old-style databases struggle in this world.

Problem 1

Slow for faraway users

If the database sits in one country, users on the other side of the planet wait longer for every answer.

Problem 2

Hard to scale

One big server can only grow so much. When traffic doubles, it can crash or slow down.

Problem 3

Rigid structure

Tables with fixed columns make it painful to store data whose shape changes often, such as product catalogs.

Problem 4

Downtime risk

If the single database server or data center fails, the whole application stops.

Problem 5

Heavy operations work

Teams spend time on patching, backups, and capacity planning instead of building features.

Cosmos DB answers these with automatic spreading of data across many machines, copies in many regions, a flexible document-style structure, and a managed service that handles the chores.

“Cosmos DB lets your data live close to every user, without you running a single database server.”

3SQL vs NoSQL in Simple Words

Before going deeper, understand the two big families of databases.

A SQL database, also called a relational database, stores data in tables, like a spreadsheet. Each table has fixed columns, and tables are connected by shared values. It is excellent when your data is very structured and you need complex questions answered across many tables.

A NoSQL database stores data in more flexible forms. The most common form is a document, which is a self-contained bundle of information, like one filled-in form. Each document can have its own fields, and related information is often kept together in the same document.

PointRelational (SQL)NoSQL such as Cosmos DB
StructureFixed tables and columnsFlexible documents or other shapes
Changing shapeNeeds planned changes to the table designNew fields can appear without redesigning everything
Scaling styleOften scales up with a bigger serverScales out by adding more machines
RelationshipsStrong support for joining many tablesPrefers keeping related data together in one item
Best forAccounting, strict records, complex reportingCatalogs, profiles, sensors, gaming, global apps
Simple Analogy

A relational database is like a school register with fixed boxes: name, roll number, grade. A document database is like a folder per student, where one folder might hold a photo and a certificate, and another might hold only a report card. Each folder holds what that student needs.

i
Good to Know

NoSQL does not mean “never use tables”. It means “not only tables”. Many real systems use both kinds of databases, each for the job it does best.

4Core Building Blocks

Learn the vocabulary once and the rest of the topic becomes much easier.

Term 1

Account

The top-level Cosmos DB resource in your Azure subscription. It holds your settings such as regions, API choice, and consistency default.

Term 2

Database

A grouping inside the account, like a folder that holds several related containers.

Term 3

Container

Where the data actually lives and where scaling happens. It is similar to a table, but holds flexible items.

Term 4

Item

A single piece of data, such as one customer or one order. In the NoSQL API an item is a JSON document.

Term 5

Partition Key

A property of each item used to decide which group of machines stores it. It is the most important design choice you make.

Term 6

Request Unit (RU)

The currency of Cosmos DB. Every action costs some request units, and your throughput is measured in request units per second.

flowchart TD
  A["Azure Cosmos DB Account"] --> B["Database: shop"]
  B --> C["Container: customers"]
  B --> D["Container: orders"]
  C --> E["Item: customer 101"]
  C --> F["Item: customer 102"]
  D --> G["Item: order 9001"]
  D --> H["Item: order 9002"]
        
FIG 1 — The hierarchy: account, database, container, item
Simple Analogy

The account is a whole office building. A database is one floor. A container is a filing cabinet on that floor. Items are the individual papers in the cabinet. The partition key is the rule that decides which drawer each paper goes into.

5One Service, Many APIs

Cosmos DB can speak several database languages.

An API is a set of rules that tells your application how to talk to a service. Cosmos DB supports several, so teams can often use skills and tools they already know. You choose the API when you create the account, and it generally cannot be changed later for that account.

API 1

NoSQL (Core)

The native API, working with JSON documents and a SQL-like query language. It gets new features first and is the usual choice for new applications.

API 2

MongoDB

Lets applications written for MongoDB talk to Cosmos DB with little change, which helps when moving existing apps.

API 3

Apache Cassandra

For applications built around Cassandra’s wide-column model, offered as a managed service.

API 4

Gremlin

For graph data, where the important thing is the connections between things, such as friends in a social network.

API 5

Table

For simple key and value data, matching the style of Azure Table Storage with extra speed and global reach.

API 6

PostgreSQL

A distributed option that scales PostgreSQL across many machines for relational workloads that need to grow big.

!
Common Mistake

Picking an API casually. Different APIs have different features and limits. If you are starting something brand new with no old database to move, the NoSQL API is usually the safest, most feature-rich starting point. Always confirm the latest feature list in the official documentation.

6Request Units: The Currency of Cosmos DB

To use Cosmos DB wisely you must understand how work is measured and paid for.

Every action you ask Cosmos DB to perform uses some computer power: memory, processing, and disk work. Instead of making you count those separately, Cosmos DB bundles them into one simple unit called a Request Unit, usually shortened to RU. You can think of RUs as tokens that you spend each time you ask the database to do something.

Reading a small item by its identifier is cheap and costs only a few RUs. Writing an item costs more than reading it. A big search across many items costs much more. The size of the item, the number of properties that are indexed, and the complexity of the question all change the price.

Simple Analogy

Imagine a food court where you buy coupons. A cup of tea costs one coupon, a sandwich costs five, and a full meal costs twenty. Cosmos DB works the same way. You decide how many coupons you get each second, and every request spends some of them.

What happens when you run out?

If your application asks for more RUs per second than you have provisioned, the extra requests are told to wait and try again. This is called rate limiting, and it shows up as an error that tells the application how long to pause. Good applications handle this politely by retrying after the suggested delay.

1

You provision throughput

You choose how many RUs per second a container or database may use.

2

Requests arrive

Each read, write, or query is given a cost in RUs.

3

Budget is checked

If enough RUs remain in the current second, the request runs. If not, it is rejected with a wait-and-retry message.

4

You tune and monitor

You watch usage and adjust throughput, improve queries, or fix the partition design to lower the cost.

i
Cost Tip

Every response from Cosmos DB reports how many RUs it consumed. Use this number while building to find which questions are expensive before they surprise you on the bill.

7Throughput Modes: Paying the Way That Fits You

Cosmos DB gives you three main ways to buy throughput.

Provisioned throughput (manual)

You set a fixed number of RUs per second and pay for it every hour whether you use it or not. This is best for steady, predictable workloads, such as a business application with a well-known daily pattern.

Autoscale provisioned throughput

You set a maximum, and Cosmos DB automatically moves the available RUs up and down between a fraction of that maximum and the maximum itself, depending on demand. It suits workloads with unpredictable or spiky traffic, such as a ticket-booking site during a big sale.

Serverless

You provision nothing in advance and pay only for the RUs your requests actually consume, plus storage. It is ideal for development, testing, small applications, and workloads that are idle most of the time. It has limits on scale, so it is not meant for very large production loads.

ModeYou decideYou pay forGood fit
ProvisionedA fixed RU per second numberReserved capacity every hourSteady, predictable traffic
AutoscaleA maximum RU per second numberThe highest level reached each hourSpiky or unpredictable traffic
ServerlessNothing in advanceRUs actually used plus storageDev, test, small or rarely used apps

Database-level or container-level throughput

You can assign throughput to a single container so it has guaranteed capacity of its own. Or you can assign it to a database so that all containers inside share one pool. Shared pools save money when you have many small containers, while dedicated throughput gives predictable performance for important ones.

Simple Analogy

Provisioned is like a monthly bus pass: you pay the same whether you ride every day or not. Autoscale is like a pass that automatically upgrades on busy days. Serverless is like paying per ride. Choose according to how often and how predictably you travel.

8Partitioning: How Cosmos DB Scales Without Limits

This is the most important chapter. A good partition key makes everything smooth; a bad one causes pain.

One machine can only hold so much data and handle so many requests. To grow beyond that, Cosmos DB splits a container’s data into pieces and spreads them across many machines. This splitting is called partitioning, and it happens automatically. Your job is to choose the rule that decides which piece each item belongs to. That rule is the partition key.

Logical and physical partitions

All items sharing the same partition key value form a logical partition. This is a group of related items that are always stored together. Cosmos DB then places many logical partitions onto physical partitions, which are the real storage and compute units on actual machines. You do not manage physical partitions. The service creates and splits them as your data and traffic grow.

flowchart TD
  C["Container: orders"] --> P1["Physical Partition 1"]
  C --> P2["Physical Partition 2"]
  C --> P3["Physical Partition 3"]
  P1 --> L1["Logical partition: customer A"]
  P1 --> L2["Logical partition: customer B"]
  P2 --> L3["Logical partition: customer C"]
  P2 --> L4["Logical partition: customer D"]
  P3 --> L5["Logical partition: customer E"]
        
FIG 2 — Many logical partitions are packed onto a few physical partitions
Simple Analogy

Imagine a huge post office sorting letters by city. Each city is a logical partition. The sorting room has several tables, and each table handles a set of cities. Those tables are the physical partitions. If one table gets crowded, the post office adds another table and moves some cities over.

What makes a good partition key?

Rule 1

Many distinct values

A key with many different values spreads data into many logical partitions. A key with only a few values creates large lumps.

Rule 2

Even spread of traffic

Requests and storage should be spread evenly. If one value gets most of the traffic, that partition becomes a hot spot.

Rule 3

Used in your common queries

When a question includes the partition key, Cosmos DB goes straight to the right machine. Without it, the question may need to check every partition, which costs more.

Rule 4

Stable over time

The key value of an item cannot be changed in place. Pick a property that does not change.

Good example: a shopping site

Using the customer identifier as the partition key spreads data across many customers, and common questions like “show this customer’s orders” go straight to a single logical partition.

Bad example: the country field for a mostly local app

If most users are in one country, one partition holds most of the data and gets most of the traffic. The other partitions sit idle while that one runs hot and gets rate limited.

!
Important Limit

A single logical partition has a storage size limit of 20 GB. If one partition key value could ever collect more data than that, you need a different design. Hierarchical partition keys, which let you use up to a few levels of keys together, can help spread such data more evenly.

9Global Distribution and Replication

Put your data near your users with a few clicks.

In Cosmos DB you can add Azure regions to your account at any time. Each region you add holds a full copy of your data. Applications automatically read from the nearest copy, which keeps response times low for users everywhere.

Single-region writes and multi-region writes

By default, one region accepts writes and the others are read copies. If the write region has a problem, you can fail over to another region. Alternatively, you can enable multi-region writes, so that every region accepts writes directly. This gives faster writes for faraway users and higher availability, but you must think about what happens when two regions change the same item at nearly the same time. That situation is called a conflict, and Cosmos DB lets you choose how conflicts are resolved, for example by letting the latest write win.

flowchart LR
  U1["Users in India"] --> R1["Region: Central India"]
  U2["Users in Europe"] --> R2["Region: West Europe"]
  U3["Users in USA"] --> R3["Region: East US"]
  R1  R2
  R2  R3
  R1  R3
        
FIG 3 — Each user talks to the nearest region while regions replicate to each other
Feature

Automatic failover

If a region becomes unavailable, the service can switch your application to another region using a priority list you define.

Feature

Availability zones

Inside a region, data can be spread across separate data center buildings, protecting you from the loss of one building.

Feature

Add or remove regions

You can change the list of regions while the application keeps running, without downtime.

Example: a global gaming leaderboard

Players in Asia, Europe, and America each submit scores to their nearest region. Replication shares those scores worldwide, so everyone sees a leaderboard that feels instant, no matter where they live.

i
Cost Reminder

Each added region stores another full copy and, with provisioned throughput, needs its own throughput as well. More regions mean better speed and resilience, but also a higher bill.

10Consistency Levels: How Fresh Is Your Data?

When data is copied to many places, there is a trade-off between freshness and speed.

When you write something in one region, it takes a tiny amount of time to appear in the other regions. During that moment, someone reading from a faraway region might see the old value. Consistency describes how strict the database is about showing everyone the newest value. Strict freshness costs speed and availability. Relaxed freshness is faster and cheaper. Cosmos DB gives you five levels so you can choose the balance.

1

Strong

Everyone always sees the latest committed write. This is the most accurate but has higher delay, and it limits how regions can be spread. Use it for money-critical data.

2

Bounded Staleness

Readers may lag behind writers, but only by a limit you set, such as a number of updates or a span of time. Order is preserved.

3

Session

Within one user session, you always see your own writes and reads follow a sensible order. This is the default and the most popular choice.

4

Consistent Prefix

You may see older data, but never updates out of order. If updates A, B, C happened, you might see A or A and B, but never A and C without B.

5

Eventual

Copies will agree sooner or later, but there is no promise about order or timing in between. It is the fastest and cheapest, suited to things like counts of likes.

LevelFreshnessSpeedTypical use
StrongAlways latestSlowestFinancial balances, inventory that must be exact
Bounded StalenessLag within a set limitSlowerLeaderboards, stock tickers with tolerance
SessionYou see your own changesFastMost web and mobile apps, user profiles
Consistent PrefixOrdered but maybe oldFasterMessage feeds, activity timelines
EventualAgrees laterFastestLikes, view counts, non-critical metrics
Simple Analogy

Think of a class group chat across several cities. With strong consistency, nobody reads a message until everyone has it. With eventual consistency, people read whatever has reached them and the group catches up in a moment. Session consistency is like always seeing your own sent messages immediately, even if friends see them a second later.

i
Practical Advice

Start with Session unless you have a clear reason to change. You can also relax the level for individual requests, but you generally cannot make a single request stricter than the account default.

11Indexing: Why Searches Are Fast

An index is like the index at the back of a textbook.

Without an index, finding a topic in a book means reading every page. With an index you jump straight to the right page. Databases work the same way. Cosmos DB automatically indexes every property of every item by default, so you can ask questions about almost any field without creating indexes yourself.

This convenience has a cost. Indexing uses storage and adds to the RUs spent on writes. If your items have many properties that you never search on, you can customize the indexing policy to include only the paths that matter and exclude the rest. This lowers write costs and improves speed.

Type

Range index

The usual index for equality and comparison questions such as “price greater than 100”.

Type

Spatial index

Helps with location questions such as “find stores within five kilometers”.

Type

Composite index

Combines several properties so that questions sorting or filtering on more than one field run efficiently.

Type

Vector index

Supports similarity search on numeric representations of text or images, which is useful in AI applications.

Simple Analogy

Indexing everything is like labelling every shelf, box, and item in a warehouse. Searching becomes easy, but labelling new stock takes time. Customizing the policy means labelling only what you will actually look for.

12Change Feed: A Live Diary of Everything That Changed

Sometimes you do not only want to store data; you want to react when it changes.

Cosmos DB keeps a change feed for each container. It is an ordered record of items that were created or updated. Other programs can read this record to find out what is new since they last looked, without scanning the whole container.

sequenceDiagram
  participant App as Application
  participant DB as Cosmos DB Container
  participant CF as Change Feed
  participant Fn as Azure Function
  participant Ext as Search or Email Service
  App->>DB: Save new order
  DB->>CF: Record the change
  Fn->>CF: Read new changes
  Fn->>Ext: Send confirmation and update search
        
FIG 4 — A new order triggers follow-up actions through the change feed

Order confirmations and notifications

When a new order item is saved, a small program reading the change feed can send an email, update stock, and notify the warehouse, all without slowing down the customer.

Keeping other systems in sync

Search engines, caches, and reporting systems can read the change feed so they stay up to date with the main data.

Event-driven design

The change feed lets teams build loosely connected systems where each part reacts to events instead of constantly asking “has anything changed?”.

i
Good to Know

Azure Functions can be triggered directly by the Cosmos DB change feed, which is one of the simplest ways to build reactive features. Depending on the mode you use, the feed shows the latest version of changed items, so check the documentation for what it does and does not capture, such as deletes.

13Security: Keeping Data Safe

A database holds valuable information, so protection must come in layers.

Layer 1

Encryption at rest

All stored data is encrypted automatically. You can optionally manage the keys yourself using Azure Key Vault.

Layer 2

Encryption in transit

Connections use secure channels so data cannot be read while traveling over the network.

Layer 3

Identity and role-based access

Applications and people can sign in with Microsoft Entra identities and receive only the permissions they need, instead of using powerful account keys.

Layer 4

Network controls

Firewalls, virtual network rules, and private endpoints can limit which networks are able to reach the account at all.

Layer 5

Auditing and monitoring

Logs record who did what, helping you spot unusual activity and meet compliance needs.

Simple Analogy

Protecting a database is like protecting a bank. There is a locked vault (encryption), an armored van for moving cash (secure connections), ID checks at the counter (identity), a guarded building entrance (network controls), and cameras recording everything (auditing).

ANTI-PATTERN-01 Avoid
Problem

Putting the primary account key into application settings and sharing it widely across teams and tools.

Why It’s Harmful

The key grants full control of all data. If it leaks through a document, a chat, or a code repository, anyone can read or delete everything, and you cannot tell who used it.

Correct Approach

Use identity-based access with limited roles for applications, keep any keys in a secure vault, and rotate keys on a schedule.

14Backup and Recovery

Replication keeps your database running; backups let you undo mistakes.

Replication copies every change, including accidental deletes, to all regions. So you also need backups, which keep older versions you can return to. Cosmos DB offers two backup modes.

Periodic backup

The service takes snapshots at regular intervals and keeps them for a set time. You can configure the interval and retention within allowed limits. To restore, you generally contact Azure support, so it suits less demanding recovery needs.

Continuous backup

The service keeps a continuous record, allowing point-in-time restore to any moment within the retention window. You can restore into a new account yourself, which is helpful when someone deletes the wrong data and you want it back from just before the mistake.

!
Common Misconception

Multiple regions do not equal a backup. A bad update or a deleted container spreads quickly to every region. Choose a backup mode that matches how much data loss and recovery time your business can accept.

15Useful Extra Features

Beyond storing and fetching data, Cosmos DB has handy tools built in.

Feature

Time to Live (TTL)

Items can expire and be deleted automatically after a set time, perfect for sessions, temporary tokens, and logs.

Feature

Server-side programming

Stored procedures, triggers, and user-defined functions written in JavaScript run inside the database, useful for grouping several actions in one transaction within a partition.

Feature

Transactions within a partition

Several changes to items that share a partition key can succeed or fail together as a single unit.

Feature

Analytical store and Synapse Link

Lets you run large reports on a separate column-based copy of your data without slowing down the live application.

Feature

Vector search

Stores and searches numeric representations of meaning, helping AI applications find similar content, which supports chat and recommendation features.

Feature

Unique keys

Rules that stop two items in the same partition from sharing the same value in chosen fields, such as an email address.

Simple Analogy

Time to Live is like a self-destructing note: it removes itself after the time you set. The analytical store is like a copy of your shop records placed in a quiet back office, where accountants can study them without disturbing the customers at the counter.

16Designing Data the Cosmos DB Way

The biggest mindset change for newcomers is how to model data.

In relational databases you split data into many tables and join them when asking questions. In Cosmos DB, joins across containers are not the normal approach. Instead you shape each item to contain what is usually needed together, so a single read gives the full answer.

1

List your questions first

Write down how your application will read data: which screens, which reports, which lookups. Design for the questions, not just the objects.

2

Decide to embed or reference

Embed related data inside one item when it is small, belongs to the parent, and is read together. Keep it separate and refer to it by identifier when it grows without limit or changes independently.

3

Choose the partition key

Pick a key that matches your most frequent questions and spreads data and traffic evenly.

4

Test and measure RU cost

Run realistic questions, look at the RU charge for each, and adjust the design before going live.

Embedding related data

  • One read returns everything needed
  • Lower RU cost for common questions
  • Related changes can be saved together
  • Simple to understand for small, bounded data

Risks of embedding

  • Items can grow too large over time
  • Duplicate data must be updated in several places
  • Not suitable for lists that grow endlessly
!
Item Size Limit

A single item has a maximum size of 2 MB. An ever-growing list stored inside one item, such as every message a user ever sent, will eventually hit this limit. Store such growing lists as separate items instead.

17Monitoring and Performance Tuning

Watching the right numbers helps you fix problems before users notice.

Metric

Normalized RU consumption

Shows how close each partition is to its throughput limit. A single partition at one hundred percent while others are low points to a hot partition.

Metric

Rate-limited requests

Counts requests that were told to retry. A steady stream means you need more throughput or a better design.

Metric

Server-side latency

How long the service takes to answer. Rising values can reveal heavy queries or capacity problems.

Metric

Storage and data usage

Tracks growth of data and index size so you can plan ahead.

Log

Diagnostic logs

Detailed records of requests and their costs, useful for finding expensive questions and unusual access.

Simple ways to lower cost and improve speed

1

Include the partition key in questions

This sends the request to one partition instead of many.

2

Trim the indexing policy

Exclude fields you never search on to cut write cost.

3

Prefer point reads

Fetching one item by identifier and partition key is the cheapest and fastest operation.

4

Keep items small

Smaller items cost fewer RUs to read and write.

5

Place the application near the data

Run your application in the same region as a Cosmos DB replica to reduce network delay.

18Real-World Use Cases

Where do companies actually use Cosmos DB?

E-commerce catalogs and shopping carts

Product details vary a lot between items, and shopping traffic spikes during sales. Flexible items and autoscale handle both well.

Gaming profiles and leaderboards

Player data must load instantly for millions of players worldwide, which suits multi-region replication and low delay.

Internet of Things telemetry

Thousands of devices send small readings continuously. Cosmos DB can absorb the stream, and TTL can delete old readings automatically.

Personalization and recommendations

User preferences and behavior are stored and read quickly to customize what each person sees.

Social and messaging applications

Profiles, posts, and message histories need fast reads and global reach, and the change feed can power notifications.

AI and chat applications

Vector search lets applications find related content to ground answers, and conversation histories can be stored as items.

Global
Replicate data to many regions
Elastic
Scale throughput up and down
Flexible
Items without a rigid schema

19Cosmos DB Compared with Other Azure Data Services

Choosing the right database saves money and pain later.

ServiceTypeStrengthChoose it when
Azure Cosmos DBDistributed NoSQLGlobal reach, low delay, elastic scaleYou need worldwide speed and flexible data at huge scale
Azure SQL DatabaseRelationalStrong relationships, complex queries, familiar toolsYour data is highly structured and needs joins and reporting
Azure Table StorageSimple key and valueVery low cost for simple dataYou only need basic lookups and little else
Azure Blob StorageObject storageCheap storage of large filesYou store images, videos, backups, or documents
Azure Cache for RedisIn-memory cacheExtremely fast temporary dataYou need to speed up repeated reads or store short-lived data
i
Quick Rule

If your data is strongly structured and relationships are the heart of it, think relational. If your data is flexible, huge, and needs to be fast for users around the world, think Cosmos DB.

20Advantages and Trade-offs

Honest comparison helps you decide with open eyes.

Advantages

  • Very low and predictable response times at scale
  • Turnkey global distribution with multi-region options
  • Flexible schema that adapts as your application changes
  • Elastic scaling with provisioned, autoscale, and serverless modes
  • High availability targets backed by service level agreements
  • Automatic indexing and a built-in change feed

Disadvantages / Trade-offs

  • Costs can be hard to predict until you understand RUs
  • Poor partition key choices cause hot spots and rate limiting
  • Not designed for heavy joins across many collections of data
  • Requires a different way of thinking about data modeling
  • Each added region increases cost
  • Some APIs offer fewer features than the native NoSQL API
“Cosmos DB rewards careful design: choose your partition key well and it scales almost without limit.”

21Common Mistakes to Avoid

Most beginners fall into the same few traps. Knowing them in advance saves time and money.

ANTI-PATTERN-02 Avoid
Problem

Choosing a partition key with very few values, such as a status field with only a handful of options.

Why It’s Harmful

Data and traffic pile into a few partitions. Those partitions hit their limits and requests get rate limited even though total throughput looks sufficient.

Correct Approach

Choose a property with many distinct values that also appears in your common questions, or use hierarchical partition keys to spread data further.

ANTI-PATTERN-03 Avoid
Problem

Running queries that do not include the partition key on large containers all the time.

Why It’s Harmful

Each such query must check many partitions, which costs many RUs and grows slower as data grows.

Correct Approach

Design the partition key around your most frequent questions, and use point reads wherever possible.

ANTI-PATTERN-04 Avoid
Problem

Copying a relational design table for table into Cosmos DB and joining everything in the application.

Why It’s Harmful

The application makes many separate requests for one screen, which is slow and expensive.

Correct Approach

Remodel the data around your access patterns, embedding what is read together and referencing what grows or changes alone.

ANTI-PATTERN-05 Avoid
Problem

Provisioning very high fixed throughput “just in case” and never reviewing it.

Why It’s Harmful

You pay for capacity every hour, even when it sits unused, so the bill is far larger than needed.

Correct Approach

Use autoscale for variable traffic or serverless for light use, monitor consumption, and adjust regularly.

ANTI-PATTERN-06 Avoid
Problem

Ignoring rate limit responses in the application and treating them as fatal errors.

Why It’s Harmful

Short bursts of traffic cause visible failures for users when a brief wait and retry would have worked.

Correct Approach

Use the retry behavior built into the official client libraries and review whether sustained rate limiting means more throughput is needed.

22Frequently Asked Questions

Q1Is Cosmos DB a SQL or a NoSQL database?

It is a NoSQL database service. Its native API uses a SQL-like query language over JSON items, which is why the name can be confusing, but the data is stored as flexible items, not in fixed relational tables.

Q2What exactly is a Request Unit?

A Request Unit is a single measure that combines the processing, memory, and disk work needed for an operation. You buy RUs per second, and each operation spends some of them. Small point reads cost the least, while large queries cost the most.

Q3Can I change the partition key later?

Historically the partition key was fixed once a container was created, and changing it meant moving data into a new container. Azure has been adding tools to make such migrations easier, but the safest approach is still to plan the key carefully before you start. Check the latest documentation for current options.

Q4Which consistency level should I choose?

Most applications are happy with Session, which is the default and lets users see their own changes immediately. Choose Strong only when stale reads would cause real harm, and choose weaker levels such as Eventual when speed and cost matter more than perfect freshness.

Q5Is Cosmos DB expensive?

It can be, if it is configured without care. Costs depend on throughput, storage, the number of regions, and backup choices. Using autoscale or serverless where they fit, designing efficient queries, and removing unused capacity keep costs under control. Use the Azure pricing calculator to estimate before building.

Q6Does Cosmos DB support transactions?

Yes, within a single logical partition. Several operations on items sharing the same partition key can succeed or fail together. Transactions across different partitions need extra care in the application design.

Q7Can I run reports without slowing the live application?

Yes. The analytical store with Synapse Link keeps a separate column-based copy of your data that is suited to large reports, so heavy analysis does not use the RUs your live application needs.

Q8Can I use Cosmos DB for free to learn?

Azure has offered a free tier and free trial options for Cosmos DB with limited throughput and storage. The details change over time, so check the Azure website for the current offer before you start.

23Summary and Key Takeaways

Azure Cosmos DB is a fully managed, globally distributed NoSQL database built for applications that need fast answers, flexible data, and the ability to grow without limits. You organize data into accounts, databases, containers, and items. You pay for work in Request Units and pick between provisioned, autoscale, and serverless throughput. A well-chosen partition key spreads data and traffic evenly, and replication across regions puts data near your users. Five consistency levels let you balance freshness against speed, while automatic indexing, the change feed, and built-in security and backup features support real production systems. Learn the vocabulary, design around your questions, measure your RU costs, and Cosmos DB will serve you very well.

Key Takeaways

  • Global and managed — Cosmos DB is a fully managed NoSQL database that can replicate your data to many regions with low response times.
  • Hierarchy to remember — an account holds databases, databases hold containers, and containers hold items.
  • Request Units drive cost — every operation spends RUs, so efficient questions and small items keep the bill down.
  • Pick the throughput mode that fits — provisioned for steady loads, autoscale for spikes, and serverless for light or test use.
  • The partition key is the key decision — choose a value with many distinct values, even traffic, and frequent use in your questions.
  • Choose consistency deliberately — Session is a strong default, with stricter or looser levels for special needs.
  • Protect and back up — use identity-based access, network controls, and continuous or periodic backups, because replication alone does not protect against mistakes.