Skip to content
Visual explainer 3h to learn 5 steps

Evaluate Cosmos DB and managed Redis on Azure

Decide when Cosmos DB or a managed Redis cache fits, choosing partition keys, consistency and TTLs with cost in mind.

By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 14 minutes to read.

Topic 16 of 33

In short

Azure Cosmos DB is a globally distributed NoSQL database that charges in request units and spreads data across partitions by a partition key you choose. Azure Managed Redis is the current managed Redis service, an in-memory store used as a cache in front of slower databases; it replaces Azure Cache for Redis, which is being retired. Both are fast at scale, but only if you design keys, consistency and expiry for your access patterns, and sometimes a relational database is the better fit.

Think of it like this: Cosmos DB is a huge library where the partition key decides which room a book goes in; Redis is the desk by the door where popular books wait.

Explained simply

Not every piece of data needs tables and joins. Azure Cosmos DB stores JSON documents and is built to answer simple lookups very fast at any size, in one region or many. Instead of renting a server, you buy throughput measured in request units, or RUs. Reading one small document by its id costs about one RU.

Cosmos DB splits data across partitions using a partition key, a property you pick when you create a container, such as customerId. All items with the same key value live together. A good key spreads work evenly and appears in most queries. A bad key piles everything into one partition, which then hits its limit while the others sit idle.

A cache is a small, very fast store that keeps copies of data you read often, so you do not ask the database every time. Redis is the most common cache. On Azure the current managed service is Azure Managed Redis; the older Azure Cache for Redis is being retired, so new projects should start on Managed Redis.

Every cached item should have a time to live, or TTL, after which it disappears. That limits how stale data can get. Cosmos DB also supports TTL on items, which is handy for sessions, carts or temporary tokens that should clean themselves up.

Cost note: Cosmos DB has a free tier for one account per subscription covering a small amount of throughput and storage, plus a serverless mode for spiky dev use. Managed Redis is billed by the hour. For free practice, use the Cosmos DB emulator and run Redis locally in Docker.

Press Play on a diagram to walk through it one step at a time.

FlowCache-aside read path
  1. 1
    Request arrives

    GET /products/42

  2. 2
    Check Redis

    Key product:42 found? Return it.

  3. 3
    Cache miss

    Read from the database.

  4. 4
    Fill the cache

    SET product:42 with a 300 second TTL.

  5. 5
    Return result

    Next request is served from memory.

LayersCosmos DB consistency levels, strongest to weakest
  1. 1
    Strong

    Reads always see the latest committed write.

  2. 2
    Bounded staleness

    Reads lag by at most K versions or T time.

  3. 3
    Session (default)

    A client always sees its own writes in order.

  4. 4
    Consistent prefix

    Reads never see writes out of order.

  5. 5
    Eventual

    Replicas converge; lowest cost and latency.

CompareCosmos DB, Managed Redis or a relational database
Cosmos DB
  • Durable JSON documents
  • Scale by partition and RU/s
  • Multi-region writes possible
  • Transactions within one partition
Azure Managed Redis
  • In-memory, very low latency
  • Cache, sessions, counters, queues
  • Data can be evicted or expire
  • Not the system of record
PostgreSQL or Azure SQL
  • Tables, joins, constraints
  • Multi-row ACID transactions
  • Ad hoc SQL and reporting
  • Scale up first, then read replicas

In depth

Choosing a partition key

A container's partition key cannot be changed later without moving the data, so choose it carefully. Look at your most frequent queries and writes. The key should have many distinct values, spread reads and writes evenly, and appear in the WHERE clause of most queries so they hit one partition. For an orders container, customerId is usually good: many customers, and most screens show one customer's orders.

Each logical partition, meaning all items with one key value, is limited to 20 GB. Cosmos DB groups logical partitions onto physical partitions, each serving up to 10,000 RU/s. If one key value is very large or very busy, such as one huge tenant, consider hierarchical partition keys (for example tenantId then userId) or a synthetic key that combines two properties.

MapPartition key candidates for an orders container
orders
  • Good: /customerId
    • Many distinct values
    • Matches most queries
    • Even writes
  • Poor: /status
    • Only a few values
    • Hot partition for new orders
  • Poor: /orderDate
    • Today's writes all in one partition
  • Large tenants: /tenantId then /customerId
    • Hierarchical key
    • Lifts the 20 GB per value limit

Estimating and paying for request units

Every operation reports its RU charge. A point read of a 1 KB item by id and partition key costs about 1 RU. Writes cost more, roughly 5 RUs or more for a small item, depending on size and indexing. Queries vary a lot: a query inside one partition with a good index is cheap; a query across all partitions costs much more. Read the charge from the response and measure your real operations.

A rough estimate: 500 point reads per second plus 50 writes per second at about 6 RUs each needs around 800 RU/s. You can pay in three ways. Provisioned throughput sets a fixed RU/s. Autoscale lets you set a maximum and scales between 10 percent of it and the maximum, billing for the highest level used each hour. Serverless bills per RU consumed, which suits dev and spiky low traffic. Requests above the limit get HTTP 429 and should be retried after the suggested wait.

  • Point read 1 KB: about 1 RU
  • Small write: about 5 RUs or more
  • Cross-partition queries cost the most
  • HTTP 429 means throttled: back off and retry

Picking a consistency level

Cosmos DB replicates data, and the consistency level decides what a read may see. The account sets a default, and a client can ask for a weaker level per request. Session, the default, gives each client read-your-own-writes and in-order reads, which is what most user-facing apps expect. Strong guarantees every read sees the latest commit, but reads cost about twice the RUs and writes get slower, especially across regions. Bounded staleness allows a fixed lag. Consistent prefix and eventual are the cheapest and fit counters, feeds or analytics where a moment of lag is fine.

Ask one question: what goes wrong if a user reads data a second old? If the answer is nothing serious, Session or weaker is right. Reserve Strong for cases such as balances where a stale read breaks a rule.

Caching with Azure Managed Redis

Azure Managed Redis runs Redis Enterprise software as a managed service. You choose a tier by the balance of memory and CPU: Memory Optimized, Balanced, Compute Optimized, or Flash Optimized, which moves colder keys to NVMe storage. High availability, with replicas across zones where available, is on by default and can be turned off only for dev. Clients connect over TLS and can authenticate with Microsoft Entra ID instead of access keys.

Most apps use the cache-aside pattern: read the cache, fall back to the database on a miss, then store the result with a TTL. When data changes, update the database first, then delete the cache key so the next read refills it. Choose TTLs by how stale data may be: seconds for stock levels, minutes for product pages, hours for reference lists. Plan for the cache being empty, for example after a restart, so the database can take the load.

CycleLife of a cache key
  1. 1
    Miss

    Key absent; app reads the database.

  2. 2
    Set with TTL

    SET product:42 value EX 300.

  3. 3
    Hits

    Reads served from memory.

  4. 4
    Invalidate or expire

    App deletes the key on change, or TTL ends.

  5. Back to step 1

When a relational database fits better

Cosmos DB and Redis are excellent at known, key-based access patterns. They are weaker where relational databases shine. If you need joins across many entities, ad hoc reporting queries, strict constraints such as foreign keys and unique rules across the whole dataset, or multi-row transactions that span many customers, PostgreSQL or Azure SQL is usually simpler and cheaper. Cosmos DB transactions only cover items in one logical partition.

A common design uses both: the relational database as the system of record, Redis in front for hot reads, and Cosmos DB only where its strengths matter, such as global low-latency reads, huge write volume or schemaless documents. Start with one database you know well, measure, and add another store when a real need appears, not by default.

  • Joins and ad hoc reports: relational
  • Cross-entity transactions: relational
  • Key lookups at global scale: Cosmos DB
  • Hot reads of slow queries: Redis cache

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Choose a partition key~35m
  2. 2
    Estimate request units~35m
  3. 3
    Pick a consistency level~35m
  4. 4
    Set cache TTLs~35m
  5. 5
    Know when relational fits better~35m

Key points

  • Choose a partition key with many distinct values that appears in most queries, such as customerId or tenantId.
  • Everything in Cosmos DB costs request units (RUs); a 1 KB point read by id and partition key costs about 1 RU.
  • Session consistency is the default and fits most apps; stronger levels cost more RUs and latency.
  • Every cache entry needs a TTL and a plan for staleness; the cache is a copy, not the source of truth.
  • Pick relational storage when you need joins, multi-row transactions across many entities or ad hoc reporting.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import json, redis

r = redis.Redis(host="localhost", port=6379, decode_responses=True)

def get_product(pid: int) -> dict:
    key = f"product:{pid}"
    if (hit := r.get(key)) is not None:
        return json.loads(hit)
    row = load_product_from_db(pid)   # your database call
    r.set(key, json.dumps(row), ex=300)  # expire after 5 minutes
    return row

Cache-aside against a local Redis; Azure Managed Redis uses TLS and Entra ID or an access key instead.

Design and create a carts container

Requirement: shopping carts read and written by one customer at a time, gone after 24 hours of inactivity. Step 1: partition key /customerId, because every cart operation knows the customer. Step 2: TTL 86400 seconds on the container, and the app rewrites the cart on each change, which resets its timer. Step 3: estimate 200 reads and 40 writes per second, about 200 + 240 = 440 RU/s, so start with autoscale at 1,000 RU/s maximum. Evidence: the container shows the key and TTL. Cleanup: delete the resource group.

bash
az cosmosdb create -g rg-lab-data -n cosmos-contoso-lab \
  --default-consistency-level Session --enable-free-tier true
az cosmosdb sql database create -g rg-lab-data -a cosmos-contoso-lab -n shop
az cosmosdb sql container create -g rg-lab-data -a cosmos-contoso-lab -d shop \
  -n carts --partition-key-path /customerId --ttl 86400 --max-throughput 1000
az cosmosdb sql container show -g rg-lab-data -a cosmos-contoso-lab -d shop -n carts \
  --query "{pk:resource.partitionKey.paths, ttl:resource.defaultTtl}"

Measure what a query really costs

Goal: see why queries should include the partition key. Prerequisites: the account above, and your identity assigned the Cosmos DB Built-in Data Contributor data-plane role. Step 1: write an item. Step 2: point-read it and print the RU charge. Step 3: run a query without the partition key and print its charge. Evidence: the point read costs about 1 RU, while the cross-partition query costs several times more, and the gap grows with data size.

python
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential

client = CosmosClient("https://cosmos-contoso-lab.documents.azure.com:443/", DefaultAzureCredential())
carts = client.get_database_client("shop").get_container_client("carts")
charge = lambda: carts.client_connection.last_response_headers["x-ms-request-charge"]

carts.upsert_item({"id": "cart-1", "customerId": "c-42", "items": 3})
carts.read_item(item="cart-1", partition_key="c-42")
print("point read RU:", charge())
list(carts.query_items("SELECT * FROM c WHERE c.items > 2", enable_cross_partition_query=True))
print("cross-partition query RU:", charge())

Quick reference

  • Point read of a 1 KB item by id and partition key: about 1 RU
  • Logical partition limit: 20 GB per partition key value
  • Default consistency is Session; Strong costs more RUs and latency
  • HTTP 429 from Cosmos DB means throttled; retry after the suggested delay
  • Cosmos TTL: set defaultTtl on the container, override with ttl on an item
  • Cache-aside: read cache, miss goes to DB, SET with EX seconds
  • New Redis work on Azure: Azure Managed Redis, not Azure Cache for Redis

Common mistakes

  • Partitioning by a value with few distinct values, such as status or country. One hot partition throttles while others sit idle.
  • Running queries without the partition key. They fan out to every partition and cost many more RUs.
  • Caching without a TTL or invalidation plan, so users see stale prices or permissions for hours.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which is the best partition key for a container of user profiles read by user id?

Question 2

2Your app gets HTTP 429 from Cosmos DB at peak times. What does it mean?

Question 3

3A user edits their profile and immediately reloads it, but sees the old data under eventual consistency. Which level fixes this at the lowest cost?

Question 4

4Product prices change in the database. What should the app do with the cached copy?

Question 5

5Finance needs ad hoc reports joining orders, customers and refunds. Which store fits best?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start Redis locally, set a key with a 60 second TTL and watch it count down and disappear.

  2. Exercise 2medium

    Estimate RU/s for 1,000 point reads per second of 1 KB items and 100 writes per second at about 7 RUs each, then pick a throughput mode for a workload that is busy only 4 hours a day.

  3. Exercise 3hard

    Add caching to the sample API's GET /products/{id} with invalidation on PUT, and explain what happens when Redis is down.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is Cosmos DB the same as MongoDB?
No. Cosmos DB is Microsoft's own database with several APIs. Its NoSQL API is the native one; there is also a MongoDB-compatible offering for apps that already use MongoDB drivers.
What happened to Azure Cache for Redis?
It is being retired in favour of Azure Managed Redis: the Enterprise tiers on 31 March 2027, and Basic, Standard and Premium on 30 September 2028. New projects should use Managed Redis, and existing caches should plan a migration using Microsoft's guides.
Can I change a Cosmos DB partition key later?
Not in place. You create a new container with the new key and copy the data, for example with the container copy feature or change feed.
Can I practise Cosmos DB for free?
Yes. Use the Cosmos DB emulator locally, or the free tier, which gives one account per subscription a small amount of free throughput and storage.

Go deeper

ShareXLinkedInWhatsApp