Microsoft AZ-204: Azure Caching, CDN and Performance — Study Guide
Part of the Microsoft Azure Developer Associate AZ-204 — Study Guide. Practice with verified answers in the Microsoft exam hub, or take timed practice tests on ExamRoll.io.
Overview
Fast, reliable user experiences in Azure depend on placing content and state close to users, minimizing origin load, and handling failure gracefully. Azure Cache for Redis, Azure CDN, and Azure Front Door together provide in-memory acceleration, edge caching, and global anycast routing with security. Mastering Redis data structures and connection patterns, CDN profiles and caching semantics, and Front Door routing and health probes lets you design low-latency, resilient applications.
Azure Cache for Redis: tiers, data structures, eviction, and patterns
Azure Cache for Redis is a managed Redis service that provides sub-millisecond data access, supporting common Redis data structures and advanced capabilities in higher tiers.
Tiers:
- Basic: Single-node cache with no SLA and no data replication. Good for dev/test and noncritical workloads. No data persistence, no clustering, no VNet integration.
- Standard: Two-node primary/replica with automatic failover and an SLA. Suitable for production. Supports scaling up/down with minimal disruption, but no clustering or persistence.
- Premium: Higher performance and throughput, larger cache sizes, Redis persistence (RDB and AOF), clustering (sharding) for horizontal scale, virtual network integration, zone redundancy (in supported regions), and geo-replication for DR. Also supports scheduled patching windows and advanced security.
Data structures and when to use them:
- Strings: Basic key/value, counters, JSON blobs; atomic INCR/DECR for rate limiting and counters.
- Hashes: Store object fields (e.g., user profile) as a single key with field-value pairs for partial updates and space efficiency.
- Lists: Queues or stacks, ordered by insertion; use with LPUSH/BRPOP for simple work queues.
- Sets: Unique collections; use for tags, membership checks, intersections.
- Sorted Sets: Ranking with scores; ideal for leaderboards and time-ordered events.
- Bitmaps/Bitfields: Compact tracking of boolean flags and counters over positions.
- HyperLogLog: Approximate cardinality (unique counts) with fixed memory.
- Geospatial: Store and query lat/long coordinates, radius searches.
- Streams: Append-only log for event ingestion and consumer groups.
Eviction policies (applied when maxmemory is reached):
- volatile-lru: Evict least recently used keys with an expiry (default on Azure Cache for Redis).
- allkeys-lru: Evict least recently used keys regardless of expiry.
- volatile-ttl: Evict keys with the nearest expiration time.
- volatile-random / allkeys-random: Evict random keys, limited to expiring or all keys.
- noeviction: Do not evict; write commands that would add memory fail with an error.
- volatile-lfu / allkeys-lfu: Least frequently used eviction variants (for newer Redis versions).
Pick eviction based on data criticality and access patterns. For caches, allkeys-lru or allkeys-lfu gives best hit rates. For mixed stores with carefully set expirations, volatile-ttl or volatile-lru can respect your TTLs.
Common use cases:
- Session caching: Store user session state via IDistributedCache or session middleware. Keep keys small, use TTL aligned with session timeout, and enable session affinity at the edge if needed.
- Output caching: Cache rendered page fragments or full responses keyed by route and user segment. Invalidate on content changes using key versioning or explicit DEL.
- Pub/Sub: Near-real-time messaging for notifications or cache invalidation fan-out. Use channels to broadcast changes to multiple subscribers.
- Leaderboards: Sorted sets with scores for ranking; ZADD/ZREVRANGE to update and read top-N; use secondary sorted sets for time-windowed rankings.
Connecting to Azure Redis: connection strings, StackExchange.Redis, and resilience
Connection endpoints and keys are provided in the Azure portal under Access keys. The primary connection string includes host, port, TLS, and password (for example, contoso.redis.cache.windows.net:6380,password=…;ssl=True;abortConnect=False). Always use TLS on port 6380 in production.
StackExchange.Redis best practices:
- Use a single, long-lived ConnectionMultiplexer per process. It is thread-safe and multiplexes requests efficiently. Create it once, store it in a static or DI container, and reuse.
- Configuration options: set AbortOnConnectFail=false for cloud failover tolerance; set ConnectRetry and ConnectTimeout for transient issues; SyncTimeout tuned for workload; KeepAlive to maintain NAT pinholes. Example options in text form: ssl=True, abortConnect=False, connectRetry=5, connectTimeout=5000.
- Use async methods to avoid thread pool starvation under load. IDatabase methods (StringGetAsync, HashSetAsync, SortedSetAddAsync) are non-blocking.
- Handle resilience events: subscribe to ConnectionFailed, ConnectionRestored, and ConfigurationChanged events to log and observe topology changes and failovers. StackExchange.Redis automatically re-resolves the primary on failover.
- Avoid long-running Lua scripts and heavy transactions; prefer small, atomic commands. Pipeline naturally via the multiplexer; do not over-batch to the point of timeouts.
- Timeouts and retries: do not blindly retry non-idempotent commands. Use idempotent patterns or write-through queues for critical writes.
- Serialization: store compact payloads (e.g., MessagePack) to minimize network traffic and memory. Avoid giant values; prefer hashes with field-level access.
- Key naming: prefix by app/environment (prod:session:{userId}) to avoid collisions and simplify bulk operations and purges.
- Security: rotate access keys, restrict via VNet (Premium), and consider Private Link for private access. Do not enable “Allow access only via SSL” to false in production.
Azure CDN: profiles, endpoints, origins, optimization, and content freshness
Azure CDN caches static content at edge POPs to reduce latency and origin load. A CDN profile groups endpoints and pricing tier/provider; an endpoint defines the edge hostname and connects to one or more origins.
Profiles and endpoints:
- Create one or more endpoints per application or environment under a profile. Each endpoint has its own edge hostname (e.g., app.azureedge.net) that you map to custom domains with TLS.
- Use separate profiles to isolate billing or apply different providers/features if needed.
Origin types:
- Azure Blob Storage: Ideal for static websites and large media. Enable Static website or map to a container; ensure proper MIME types and cache headers.
- App Service: Use for dynamic content or REST APIs where selected responses can be cached. Configure the origin host header to your app’s hostname and ensure HTTPS.
- Custom origin: Any publicly reachable HTTP(S) endpoint, including on-premises via public IP or reverse proxy.
Optimization types (applied at endpoint creation):
- General web delivery: Balanced for many small/medium assets (HTML, CSS, JS, images) with widespread POP coverage.
- Large file download: Optimized for big files with range request tuning, connection management, and throughput-oriented settings.
- Video streaming: Optimized for progressive download or HLS/DASH segment delivery, keeping segment caching efficient and honoring byte-range requests.
Caching rules and purging:
- Global and custom caching rules let you control TTLs based on path, file extension, request method, and query string behavior. On Standard tiers, configure rules in the endpoint’s caching settings; Premium adds advanced rules engines.
- Purge invalid content by path with wildcards (e.g., /images/*) via portal, CLI, or REST API. Purges propagate across POPs; use targeted purges to minimize blast radius. Premium tiers support preload for warming caches.
Content freshness controls:
- TTL: The CDN honors Cache-Control and Expires headers from the origin by default. You can override or set minimum/maximum TTLs with rules. For immutable assets, serve Cache-Control: public,max-age=31536000,immutable to maximize hit rates.
- Cache-Control directives: no-store and private are not cached by the CDN; must-revalidate and s-maxage allow fine-grained shared cache control. Prefer s-maxage for CDN-specific TTLs while keeping max-age conservative for browsers.
- Query string caching behavior: choose to ignore query strings (single cached object per path), cache every unique URL (each query string combination cached separately), or bypass cache on query string. For versioned assets (e.g., app.css?v=hash), cache every unique URL. For analytics parameters (utm_), ignore query strings to improve hit rates.
- Vary and compression: Ensure Vary: Accept-Encoding is set when compressing; the CDN will cache separate variants per Vary key. Enable CDN compression for text assets to reduce bandwidth.
Azure Front Door: global routing, health, security, and affinity
Azure Front Door provides anycast-based, Layer 7 global load balancing, dynamic site acceleration, and integrated WAF. It complements CDN by routing and protecting dynamic traffic while optionally caching static content in Standard/Premium.
Routing rules:
- Match incoming hostnames and path patterns and route to an origin group (backend pool). Apply path rewrites, header transforms, redirects, and protocol settings per rule.
- Configure caching at the route (Standard/Premium) for edge caching of static or semi-static assets when you want tighter control at the application edge.
- Use priority-based failover and weighted load balancing across origins, optionally with geo-filtering for region-specific routing.
Health probes and backend health:
- Define probe path, protocol, interval, and expected HTTP status codes. Probes run from multiple edge locations to determine origin health.
- Front Door uses health status to steer traffic to healthy origins with low latency. Tune timeouts and sample size to avoid flapping; ensure the probe endpoint is lightweight and uncached.
WAF integration:
- Attach a WAF policy to your Front Door to enforce managed rulesets for common web vulnerabilities and add custom rules for IP restrictions, geoblocking, or request-size limits.
- Use bot protection and rate limiting to absorb abusive traffic at the edge, preserving origin capacity.
Session affinity:
- Enable session affinity when your application requires consecutive requests to hit the same backend (e.g., non-distributed session state). Front Door injects an affinity cookie and routes subsequent requests in the same session to the selected backend within a routing rule.
- Prefer stateless designs or Redis-backed session state to avoid affinity when possible; if used, scope affinity carefully and set appropriate cookie TTLs.
Interplay with CDN:
- CDN should serve static assets (images, scripts, media) with long TTLs; Front Door routes dynamic requests with WAF, TLS termination, and path-based routing. This split maximizes cache hit rates and minimizes dynamic latency.
- For APIs or pages that cannot be cached, keep TTL low or bypass caching; for semi-static HTML, consider short TTLs with purge-on-change workflows.
Practical Problem Scenario
Mozilla is launching a global microsite for add-on discovery with high traffic spikes during releases. They need fast static asset delivery, resilient dynamic APIs, and secure, low-latency user interactions worldwide.
- Front Door for global entry and security
- Create a Front Door Standard profile with custom domain and managed TLS. Define routing rules: /api/* to the App Service API origin group and /* to the CDN endpoint hostname.
- Why: Anycast routing brings users to the nearest edge; WAF at Front Door blocks malicious patterns before reaching origins; path-based routing cleanly separates dynamic and static traffic.
- WAF policy and rate limiting
- Attach a WAF policy with managed rule sets enabled and a custom rule to throttle excessive POST requests to /api/search.
- Why: Protects APIs from OWASP-class attacks and abusive clients, preserving origin capacity during spikes.
- Health probes and origin groups
- Configure API origin group with two App Service instances in different regions. Use health probes on /healthz with 200 expected status and a 10-second interval. Set one region to priority 1, the other to priority 2, with failover.
- Why: Ensures automatic regional failover if a primary region degrades; probes detect health independently of cached responses.
- Redis-backed session and output caching
- Deploy Azure Cache for Redis Standard and integrate the API with IDistributedCache to store minimal session state and short-lived output fragments for common API responses (e.g., popular add-ons lists) with TTLs of 60–300 seconds.
- Why: Reduces API latency and database load while keeping state off the web tier; short TTLs maintain freshness without manual invalidation.
- Redis data structures for leaderboards
- Use a Redis sorted set per category (e.g., addons:top:{category}) to maintain download-based rankings. Update scores asynchronously via a queue consumer and expose read APIs that read top-N entries.
- Why: Sorted sets provide O(log n) updates and fast range reads, perfect for real-time rankings with high read concurrency.
- Connection resilience with StackExchange.Redis
- Initialize a singleton ConnectionMultiplexer with ssl=True, abortConnect=False, connectRetry=5, and sensible timeouts. Handle ConnectionFailed/Restored events for observability and set SyncTimeout high enough for bursts while using async APIs.
- Why: Ensures seamless failover handling and avoids process-wide outages during transient network events or Redis failovers.
- CDN for static assets with aggressive caching
- Create an Azure CDN profile and endpoint optimized for General web delivery with the storage account static website as the origin. Configure caching rules to honor origin headers, but override to a 7-day TTL for /static/*, and enable compression. Set query string caching to Cache every unique URL and fingerprint assets (app.css?v=hash).
- Why: Edge caching delivers assets quickly worldwide; fingerprinting allows long TTLs with instant updates on deploys; compression reduces transfer sizes.
- Purge process in CI/CD
- Add a deployment step that purges CDN paths for HTML and JSON manifests on release (e.g., /index.html, /manifest/*.json) and preloads critical pages for warm caches in supported tiers.
- Why: Ensures users get fresh HTML quickly while keeping immutable assets cached; preloading reduces cold-start latency post-deploy.
- Front Door session affinity only where required
- Keep APIs stateless and rely on Redis for session state; disable Front Door session affinity for /api/* routes. For a legacy admin tool that requires affinity, enable it on /admin/* with a short TTL.
- Why: Maximizes load distribution and cacheability for most users while limiting affinity to the minimal scope required.
This architecture uses Front Door for secure, intelligent edge routing and WAF, Azure CDN for high-hit-rate static content delivery with precise freshness control, and Azure Cache for Redis to offload hot reads, maintain low-latency session and leaderboard data, and absorb spikes gracefully.
← Azure Event-Based and Message Solutions · All domains · Azure Monitoring →
Practice these questions → · Timed practice on ExamRoll.io →
Pass the whole exam — not just this question
You found this answer. Get every verified question and explanation in one place, and save hours of prep. Free to start.
Pass your exam →