Module 6 of 9 25–30% 3 sub-modules · 21 units Domain 2: Develop AI Solutions by Using Azure Data Management Services

Enhance AI Solutions with Azure Managed Redis

Implement Azure Managed Redis data operations including caching, expiration, and invalidation. Implement vector indexing to enable similarity search for semantic caching and RAG.

Azure Managed RedisRediSearchVector Index

Last updated: · Aligned with Course AI-200T00-A

Module

Cache Content with Azure Managed Redis

units
Unit 1

Introduction

3 min

Azure Managed Redis is a fully managed Redis service. Redis is an in-memory key-value store that runs at microsecond latency — 100-1,000x faster than database queries. AI applications use it to cache model inference results, prompt/response pairs, embedding vectors, rate-limit counters, and session state — all to reduce cost and latency.

Exam Tip

Exam pillars: 1) Tiers + features 2) Cache-aside pattern implementation 3) Data types and commands 4) TTL strategy 5) Cache invalidation patterns 6) Redis port 10000 with TLS (not 6379).
Unit 2

Explore Azure Managed Redis

7 min

Cache-Aside Pattern: App checks Redis → HIT returns instantly → MISS fetches DB then caches result

AI Appget_product(id)① Check cacheRedisport 10000 (TLS)HIT → return valueMISS → fetch DB② HIT③ MISS: query DBDatabasePostgreSQL/Cosmos④ cache + TTLTTL: fast-changing 1-5m | stable 1-24h | static 24h+

1. Azure Managed Redis Tiers

#TierMemoryPersistenceClusterUse For
1Memory OptimizedUp to 1.5 TBAOFYesLarge AI caches, embedding stores
2BalancedUp to 120 GBAOFYesGeneral production AI workloads
3Compute OptimizedUp to 120 GBAOFYesHigh throughput, CPU-intensive operations
4Flash OptimizedUp to 13 TBAOFYesVery large datasets, warm data on flash

Also: Azure Cache for Redis with Basic/Standard/Premium tiers — Basic is single-node dev/test; Standard adds replication; Premium adds geo-replication and VNet.

2. Connection: Port 10000 (Not 6379)

Azure Managed Redis uses port 10000 with mandatory TLS — not the default Redis port 6379. This is a common exam trap.

redis://myinstance.redis.azure.com:10000 (TLS required)

Common Gotcha

Port 6379 = open-source Redis default. Azure Managed Redis = port 10000 with TLS. Any question about Azure Redis connection → port 10000.

3. Caching Strategies — Which to Use When

  1. Cache-aside (Lazy loading) — app checks cache first, on MISS fetches from DB and stores in cache. Most common for AI inference results. Requires cache invalidation on source data change.
  2. Write-through — writes go to cache AND DB simultaneously. Cache always consistent. Higher write latency. Good for user profiles that must always be current.
  3. Write-behind (Write-back) — writes go to cache, DB updated asynchronously. Low write latency. Risk of data loss on crash. Advanced scenario.
  4. Read-through — cache fetches from DB on MISS automatically. Cache acts as transparent proxy. Simplifies application code.

Exam Tip

Cache-aside = application manages cache. Cache hit: return from cache. Cache miss: fetch DB, populate cache, set TTL, return. The exam always has a "implement caching" scenario where cache-aside is the right answer for AI inference results.
Unit 3

Client Libraries and Configuration

5 min

1. Python: redis-py with Managed Identity

import redis

# Access key authentication
r = redis.Redis(
    host='your-instance.redis.azure.com',
    port=10000,
    ssl=True,
    decode_responses=True,
    password='your-access-key'
)

# Entra ID (Managed Identity) authentication
from redis_entraid.cred_provider import create_from_default_azure_credential
credential_provider = create_from_default_azure_credential(
    ("https://redis.azure.com/.default",)
)
r = redis.Redis(host='...', port=10000, ssl=True,
    decode_responses=True, credential_provider=credential_provider)

Exam Tip

Production: use create_from_default_azure_credential from redis-entraid package. Token refreshes automatically. Access key = shared long-lived secret — avoid in production.

2. decode_responses=True

Set this in ALL clients. Without it, Redis returns bytes objects. With it, returns Python str. Nearly always what you want.

Unit 4

Implement Redis Data Operations

12 min

1. Strings — Most Common Type (Key→Value)

r.set("inference:result:user-123", '{"answer": "42", "confidence": 0.98}', ex=300)
result = r.get("inference:result:user-123")  # None if expired

r.setex("rate:user-123", 60, 1)  # Set with TTL of 60 seconds
r.incr("rate:user-123")           # Atomic increment — thread-safe counter
remaining = r.ttl("rate:user-123")  # Time to live in seconds

2. Hashes — Object with Multiple Fields

Use for session data, user profiles — avoids serializing/deserializing a full JSON blob when you only need one field.

r.hset("user:1001", mapping={"name": "Alice", "tier": "premium", "credits": "500"})
name = r.hget("user:1001", "name")        # Get one field
profile = r.hgetall("user:1001")          # Get all fields as dict
r.hincrby("user:1001", "credits", -10)   # Atomically decrement credits

3. Lists — Ordered Queue / Recent History

r.lpush("chat:session-abc", "Hello")   # Push to left
r.rpush("chat:session-abc", "World")   # Push to right
history = r.lrange("chat:session-abc", 0, -1)  # All items
r.ltrim("chat:session-abc", 0, 9)      # Keep only last 10 messages

4. Sets — Unique Members

r.sadd("active-sessions", "sess-001", "sess-002")
r.sismember("active-sessions", "sess-001")  # True/False
r.smembers("active-sessions")               # All members

5. Sorted Sets — Leaderboards / Priority Queues

r.zadd("model-latency", {"gpt-4o": 250.5, "gpt-4o-mini": 85.2})
fastest = r.zrange("model-latency", 0, -1, withscores=True)  # Ascending (fastest first)

6. TTL Strategy by Data Type

#DataTTLReason
1Rate limit counters60–300 secondsReset per time window
2Inference result cache5–60 minutesReasonably fresh, invalidate on model update
3User session data15–60 minutesExpire inactive sessions
4Product catalog1–24 hoursChanges infrequently
5Static config24+ hoursVery stable data

Common Gotcha

Never store sensitive data (API keys, PII) in Redis without encryption — Redis stores data in memory and may persist it to disk. Expire sensitive data with short TTLs or use Key Vault instead.

Redis Master Cheatsheet

Azure Redis port10000 (TLS, NOT 6379)
Cache-aside key commandsGET → miss → DB → SET with TTL
Set with TTL (seconds)r.set(key, val, ex=300)
Atomic counterr.incr(key) — thread-safe
Object storageHash: r.hset(key, mapping=dict)
Ordered queueList: lpush/rpush + lrange
Unique membersSet: r.sadd
Ranked dataSorted Set: r.zadd
Decode bytes to strdecode_responses=True
Prod authredis-entraid + DefaultAzureCredential
Unit 5

Exercise — Cache AI Inference Results

30 min
  1. Create Azure Managed Redis instance and connect on port 10000 with TLS
  2. Implement cache-aside for model inference: GET → MISS → model call → SET with 5-min TTL
  3. Implement rate limiting: INCR per user per minute, block at limit
  4. Store session history in a Redis List, trim to last 10 messages
  5. Measure latency difference: Redis HIT vs database query
Unit 6

Knowledge Check

5 min
  1. Q: Azure Managed Redis connection port? A: 10000 with TLS (not 6379)
  2. Q: Cache frequently-read inference results, update on source change. Which pattern? A: Cache-aside (lazy loading)
  3. Q: Track API calls per user per minute atomically. Which command? A: INCR with SETEX for the window TTL
  4. Q: Store user profile fields individually without full JSON serialization. Which data type? A: Redis Hash
  5. Q: Production authentication for Redis without stored keys? A: Entra ID with redis-entraid + DefaultAzureCredential
Unit 7

Summary

2 min

Azure Managed Redis = in-memory cache at microsecond latency. Connect on port 10000 with TLS. Implement cache-aside for AI inference results. Choose data types by pattern: String (simple cache), Hash (objects), List (queues/history), Set (unique members), Sorted Set (leaderboards). Set TTLs based on data volatility. Use Entra ID for production auth.

Memory Tricks

Cache-aside flow: "Get → Miss → DB → Set" — always in that order

Data type mnemonic: "SHLSS" — String (cache), Hash (objects), List (queue), Set (unique), Sorted Set (ranked)

Azure Redis port: 10000 = "ten thousand ms slower than RAM... but still fast" (just remember: 10000, not 6379)

Module Cheatsheet

Azure Managed Redis

20–25% PDF

Key Facts

  • Azure Redis port — 10000 with TLS — NOT the open-source default 6379
  • Cache-aside flow — GET → MISS → DB → SET with TTL → return
  • Atomic counter — r.incr(key) — thread-safe, use for rate limiting
  • Hash (object) — r.hset(key, mapping=dict) — avoids full JSON serialize/deserialize
  • List (queue) — lpush/rpush + lrange + ltrim — chat history, task queues
  • Set (unique) — r.sadd/sismember — active sessions, deduplicated sets
  • Sorted Set (ranked) — r.zadd — leaderboards, priority queues, TTL ordering
  • Prod auth — redis-entraid + DefaultAzureCredential (no stored key)

Commands & Patterns

import redis
r = redis.Redis(host="myinst.redis.azure.com",
  port=10000, ssl=True, decode_responses=True,
  password="your-access-key")
# Cache-aside
def get_result(key):
  hit = r.get(key)
  if hit: return hit
  val = db_query()
  r.set(key, val, ex=300)  # 5-min TTL
  return val
# Atomic rate limit
key = f"rate:{user_id}:{int(time.time())//60}"
count = r.incr(key); r.expire(key, 60)
if count > 10: raise RateLimitError()
# Hash for user profile
r.hset("user:1001", mapping={"name":"Alice","tier":"premium"})
r.hincrby("user:1001", "credits", -10)
# List: keep last 10 messages
r.lpush("chat:abc", "Hello"); r.ltrim("chat:abc", 0, 9)
Module

Implement Vector Indexing and Semantic Caching with Azure Managed Redis

units
Unit 1

Introduction to Redis Vector Search

3 min

Azure Managed Redis (via the RediSearch module) supports vector similarity search — store embeddings in Redis hashes and query with FT.SEARCH KNN. The primary AI use case is semantic caching: return cached LLM responses for semantically similar prompts instead of calling the API every time.

Exam Tip

Redis vector exam pillars: 1) FT.CREATE with VECTOR HNSW field 2) FLOAT32 / DIM / DISTANCE_METRIC COSINE 3) FT.SEARCH KNN syntax with DIALECT 2 4) Cosine distance 0=identical — similarity = 1 - distance 5) Cache hit threshold ~0.95.
Unit 2

Create a Vector Index with FT.CREATE

8 min

Create RediSearch Vector Index

import redis, struct

r = redis.Redis(
    host="myredis.redis.cache.windows.net",
    port=10000, password="key", ssl=True,
    decode_responses=False  # MUST be False for binary vectors
)

r.execute_command(
    "FT.CREATE", "idx:docs", "ON", "HASH",
    "PREFIX", "1", "doc:",
    "SCHEMA",
    "title", "TEXT",
    "embedding", "VECTOR", "HNSW", "6",
        "TYPE", "FLOAT32",
        "DIM", "1536",
        "DISTANCE_METRIC", "COSINE"
)

# Store document with embedding
def embed(text):
    vec = oai.embeddings.create(input=text,
        model="text-embedding-3-small").data[0].embedding
    return struct.pack(f"{len(vec)}f", *vec)

r.hset("doc:1", mapping={
    "title": "Azure Key Vault",
    "embedding": embed("Azure Key Vault secures secrets")
})

Exam Tip

decode_responses=False required for binary vector data. HNSW = approximate index type. DIM 1536 must match your embedding model dimensions.
Unit 4

Semantic Caching Pattern

8 min

Cache-Aside with Similarity Threshold

import hashlib

THRESHOLD = 0.95  # cosine similarity for cache hit

def semantic_cache_get(prompt):
    q_emb = embed(prompt)
    res = r.execute_command(
        "FT.SEARCH", "idx:cache",
        "*=>[KNN 1 @embedding $blob AS score]",
        "PARAMS", "2", "blob", q_emb,
        "RETURN", "2", "response", "score",
        "DIALECT", "2"
    )
    if res[0] > 0:
        distance = float(dict(zip(res[2][::2],
            res[2][1::2]))[b"score"])
        if (1 - distance) >= THRESHOLD:
            return res[2][res[2].index(b"response")+1]
    return None

def semantic_cache_set(prompt, response, ttl=3600):
    key = f"cache:{hashlib.md5(prompt.encode()).hexdigest()}"
    r.hset(key, mapping={
        "prompt": prompt,
        "response": response,
        "embedding": embed(prompt)
    })
    r.expire(key, ttl)

Common Gotcha

Redis returns cosine distance (0=identical). Similarity = 1 - distance. Always set TTL on cached responses — LLM answers become stale. Never cache user-specific or sensitive data.
Unit 5

Exercise

20 min
  1. Create an Azure Managed Redis (Enterprise tier with RediSearch)
  2. Create an FT.CREATE index with HNSW FLOAT32 DIM=1536 COSINE
  3. Store 10 Q&A pairs with embeddings using r.hset()
  4. Implement semantic_cache_get() with 0.95 similarity threshold
  5. Test with rephrased questions — verify cache hits vs misses
Unit 6

Summary

2 min

Redis vector search: FT.CREATE with HNSW index → HSET with binary embedding → FT.SEARCH KNN with DIALECT 2. Cosine similarity = 1 - distance. Semantic cache returns cached LLM responses for similar prompts (≥0.95 threshold). Always TTL cache entries. Use decode_responses=False for binary vector operations.

Exam Scenario Walkthrough

Sub-Millisecond Semantic Prompt Cache with Azure Cache for Redis Enterprise

A generative AI assistant receives thousands of repetitive user questions. Repeatedly calling Azure OpenAI GPT-4o incurs heavy token costs and 1,500ms latencies. Frequent questions must be answered from cache in <5ms.

Scenario Constraints & Requirements:
  • Cache prompt responses based on semantic similarity (>92% similarity match).
  • Evict least-recently-used items automatically when cache memory reaches capacity.
  • High availability with zero data loss during node reboots.
Architecture Solution:

Deploy Azure Cache for Redis Enterprise with the RediSearch module enabled, configure `allkeys-lru` eviction policy, and query vector indexes using Flat or HNSW indexing.

1. Provision Azure Cache for Redis Enterprise with RediSearch
az redisenterprise create \
  --cluster-name redis-ai-cache \
  --resource-group rg-ai \
  --sku Enterprise_E10 \
  --location eastus \
  --modules name=RediSearch name=RedisJSON
Key Rule: Enterprise tier is required for RediSearch module (vector indexing & JSON documents).
2. Create Vector Index for Prompt Embeddings
FT.CREATE prompt_idx ON HASH PREFIX 1 prompt:
SCHEMA
  text TEXT
  response TEXT
  embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
Key Rule: RediSearch enables vector search directly over in-memory key-value hashes.
3. Query Nearest Neighbor with Similarity Distance Threshold
query = "*=>[KNN 1 @embedding $vec AS score]"
results = r.ft("prompt_idx").search(query, query_params={"vec": query_embedding_bytes})
if results.docs and float(results.docs[0].score) < 0.08:
    return results.docs[0].response # Cache Hit! (< 0.08 distance = > 92% cosine similarity)
Key Rule: Return cached response in 2ms without invoking LLM API.
Key Exam Takeaway

Standard and Basic Redis do NOT support RediSearch vector similarity. You must choose Azure Cache for Redis Enterprise or Enterprise Flash for RediSearch.

Architectural Comparison

Azure Cache for Redis: Basic vs Standard vs Premium vs Enterprise

Understanding tier requirements for vector caching, clustering, and persistence.

FeatureBasicStandardPremiumEnterprise
SLANone (No SLA)99.9% (Primary/Replica)99.9% (Primary/Replica)99.99% (Multi-AZ)
Data Persistence (RDB/AOF)NoNoYes (Append-Only File / Snapshot)Yes (Export/Import & AOF)
Clustering / ShardingNoNoYes (OSS Redis Clustering)Yes (Enterprise Clustering)
RediSearch & RedisJSONNoNoNoYes (Required for Vector Search)
Active Geo-ReplicationNoNoNoYes (Multi-region active-active writes)
Virtual Network (Private Link)NoNoYes (VNet injection / Private Link)Yes (Private Link)
Exam Traps to Avoid

Common Mistakes & Gotchas in Azure Managed Redis

✕ The Trap: Assuming `allkeys-random` or `noeviction` is safe for LLM prompt caching.
The Reality: `noeviction` returns Out-Of-Memory (OOM) errors to applications once Redis reaches 100% capacity.
✓ Correct Answer Rule: Use `allkeys-lru` or `volatile-lru` for caching workloads so stale queries are safely recycled.
✕ The Trap: Choosing Redis Premium expecting to run RediSearch vector queries.
The Reality: Redis Premium does NOT include Redis modules like RediSearch or RedisJSON. Those modules only exist in Enterprise SKUs.
✓ Correct Answer Rule: Always select Azure Cache for Redis Enterprise when vector similarity caching is requested.
✕ The Trap: Failing to configure TLS/SSL on client connection string.
The Reality: Azure Redis disables non-SSL port 6379 by default; connecting on unencrypted port fails silently or rejects handshake.
✓ Correct Answer Rule: Always connect on TLS port 6380 with `ssl=True`.

Recommended Next Steps for Azure Managed Redis

Quick Quiz

5 questions — test your understanding before moving on

Finished reading this module? Mark it complete to track your progress.

Related Modules — Develop AI Solutions by Using Azure Data Management Services

Frequently Asked Questions — Azure Managed Redis

What port and TLS configuration does Azure Managed Redis use in AI-200 questions? +

Azure Managed Redis connects on port 10000 with mandatory TLS encryption. Connecting to the standard open-source Redis port 6379 without TLS is a common exam distractor.

How does Azure Managed Redis Enterprise implement semantic caching for AI models? +

Using the RediSearch module with vector similarity indexing. When a prompt arrives, its embedding is checked against existing cached embeddings. If a vector distance is within a similarity threshold (e.g., cosine distance < 0.05), the cached LLM response is returned in sub-milliseconds.

What is the Cache-Aside pattern, and why is it preferred for AI application caches? +

The application first queries Redis. On a cache hit, it returns the cached item immediately. On a cache miss, the app queries the database or LLM, writes the result to Redis with a TTL, and returns it. This ensures the app handles cache outages gracefully.

Which Redis data types are best suited for session history vs rate limiting vs leaderboards? +

Use Lists (`LPUSH`/`LTRIM`) for rolling chat message history, Strings with `INCR` and expiration TTL for API rate limiting counters, and Sorted Sets (`ZADD`/`ZRANGE`) for ranking and priority queues.

How do you authenticate to Azure Managed Redis in production without access keys? +

Configure Microsoft Entra ID access policies on the Redis instance, assign roles to your service managed identity, and connect using identity-based tokens with automatic rotation.