Understanding Redis Cache Memory Pressure
Azure Cache for Redis stores data in memory. When memory fills up, Redis starts evicting keys based on its eviction policy, causing cache misses and degraded application performance. Severe memory pressure leads to connection failures, increased latency, and even data loss. This guide covers how to diagnose, resolve, and prevent Redis memory issues.
Understanding the Root Cause
Resolving Azure Redis Cache Eviction and Memory Pressure requires more than applying a quick fix to suppress error messages. The underlying cause typically involves a mismatch between your application’s expectations and the service’s actual behavior or limits. Azure services enforce quotas, rate limits, and configuration constraints that are documented but often overlooked during initial development when traffic volumes are low and edge cases are rare.
When this issue appears in production, it usually indicates that the system has crossed a threshold that was not accounted for during capacity planning. This could be a throughput limit, a connection pool ceiling, a timeout boundary, or a resource quota. The error messages from Azure services are designed to be actionable, but they sometimes point to symptoms rather than the root cause. For example, a timeout error might actually be caused by a DNS resolution delay, a TLS handshake failure, or a downstream dependency that is itself throttled.
The resolution strategies in this guide are organized from least invasive to most invasive. Start with configuration adjustments that do not require code changes or redeployment. If those are insufficient, proceed to application-level changes such as retry policies, connection management, and request patterns. Only escalate to architectural changes like partitioning, sharding, or service tier upgrades when the simpler approaches cannot meet your requirements.
Impact Assessment
Before implementing any resolution, assess the blast radius of the current issue. Determine how many users, transactions, or dependent services are affected. Check whether the issue is intermittent or persistent, as this distinction changes the urgency and approach. Intermittent issues often indicate resource contention or throttling near a limit, while persistent failures typically point to misconfiguration or a hard limit being exceeded.
Review your Service Level Objectives (SLOs) to understand the business impact. If your composite SLA depends on this service’s availability, calculate the actual downtime or degradation window. This information is critical for incident prioritization and for justifying the engineering investment required for a permanent fix versus a temporary workaround.
Consider the cascading effects on downstream services and consumers. When Azure Redis Cache Eviction and Memory Pressure degrades, every service that depends on it may also experience failures or increased latency. Map out your service dependency graph to understand the full impact scope and prioritize the resolution accordingly.
Signs of Memory Pressure
- Cache hit ratio drops suddenly
OOM command not allowed when used memory > 'maxmemory'errors- Increased latency on GET/SET operations
- Connection timeouts and
RedisConnectionException - Server load exceeding 80% in Azure Monitor metrics
Checking Memory Usage
# Check cache metrics
az redis show \
--name myRedis \
--resource-group myRG \
--query "{sku:sku.name, capacity:sku.capacity, hostName:hostName}" -o json
# Get memory info via redis-cli
redis-cli -h myRedis.redis.cache.windows.net -p 6380 -a "access-key" --tls INFO memory
# Key output fields:
# used_memory: 1073741824 (bytes currently used)
# used_memory_human: 1.00G
# used_memory_peak: 2147483648
# maxmemory: 2684354560 (configured limit)
# mem_fragmentation_ratio: 1.2 (> 1.5 indicates fragmentation)
# Check memory stats
redis-cli -h myRedis.redis.cache.windows.net -p 6380 -a "access-key" --tls MEMORY STATS
# Find the biggest keys consuming memory
redis-cli -h myRedis.redis.cache.windows.net -p 6380 -a "access-key" --tls --bigkeys
Eviction Policies
| Policy | Behavior | Use Case |
|---|---|---|
volatile-lru |
Evict least recently used keys with TTL set | Default — good for caching |
allkeys-lru |
Evict least recently used keys (all keys) | Pure cache, no persistent data |
volatile-lfu |
Evict least frequently used keys with TTL | Frequency-based caching |
allkeys-lfu |
Evict least frequently used keys (all keys) | Frequency-based, all keys |
volatile-random |
Random eviction of keys with TTL | Random access patterns |
allkeys-random |
Random eviction of any key | Random access patterns |
volatile-ttl |
Evict keys with shortest TTL first | TTL-prioritized caching |
noeviction |
Return errors on writes when full | Data must not be lost |
# Check current eviction policy
redis-cli -h myRedis.redis.cache.windows.net -p 6380 -a "access-key" --tls CONFIG GET maxmemory-policy
# Change eviction policy
az redis update \
--name myRedis \
--resource-group myRG \
--set "redisConfiguration.maxmemory-policy=allkeys-lru"
Configuring maxmemory-reserved
The maxmemory-reserved setting reserves memory for non-cache operations like replication, failover buffers, and fragmentation overhead. Without sufficient reservation, these operations steal memory from cached data.
# Set maxmemory-reserved (in MB)
az redis update \
--name myRedis \
--resource-group myRG \
--set "redisConfiguration.maxmemory-reserved=256"
# Recommendations:
# Small caches (C0-C1): 10% of total memory
# Medium caches (C2-C3): 15-25% of total memory
# Large/Premium (P1-P5): 25-50% of total memory
# Clustered caches: Higher reservation per shard
Resilience Patterns for Long-Term Prevention
Once you resolve the immediate issue, invest in resilience patterns that prevent recurrence. Azure’s cloud-native services provide building blocks for resilient architectures, but you must deliberately design your application to use them effectively.
Retry with Exponential Backoff: Transient failures are expected in distributed systems. Your application should automatically retry failed operations with increasing delays between attempts. The Azure SDK client libraries implement retry policies by default, but you may need to tune the parameters for your specific workload. Set maximum retry counts to prevent infinite retry loops, and implement jitter (randomized delay) to prevent thundering herd problems when many clients retry simultaneously.
Circuit Breaker Pattern: When a dependency consistently fails, continuing to send requests increases load on an already stressed service and delays recovery. Implement circuit breakers that stop forwarding requests after a configurable failure threshold, wait for a cooldown period, then tentatively send a single test request. If the test succeeds, the circuit closes and normal traffic resumes. If it fails, the circuit remains open. Azure API Management provides a built-in circuit breaker policy for backend services.
Bulkhead Isolation: Separate critical and non-critical workloads into different resource instances, connection pools, or service tiers. If a batch processing job triggers throttling or resource exhaustion, it should not impact the real-time API serving interactive users. Use separate Azure resource instances for workloads with different priority levels and different failure tolerance thresholds.
Queue-Based Load Leveling: When the incoming request rate exceeds what the backend can handle, use a message queue (Azure Service Bus or Azure Queue Storage) to absorb the burst. Workers process messages from the queue at the backend’s sustainable rate. This pattern is particularly effective for resolving throughput-related issues because it decouples the rate at which requests arrive from the rate at which they are processed.
Cache-Aside Pattern: For read-heavy workloads, cache frequently accessed data using Azure Cache for Redis to reduce the load on the primary data store. This is especially effective when the resolution involves reducing request rates to a service with strict throughput limits. Even a short cache TTL of 30 to 60 seconds can dramatically reduce the number of requests that reach the backend during traffic spikes.
Connection Limits by Tier
| Tier | Size | Max Connections | Memory |
|---|---|---|---|
| Basic C0 | 250 MB | 256 | 250 MB |
| Basic C1 | 1 GB | 1,000 | 1 GB |
| Standard C2 | 2.5 GB | 2,000 | 2.5 GB |
| Standard C3 | 6 GB | 5,000 | 6 GB |
| Premium P1 | 6 GB | 7,500 | 6 GB |
| Premium P4 | 53 GB | 40,000 | 53 GB |
Resilient Connection Configuration (C#)
using StackExchange.Redis;
var options = new ConfigurationOptions
{
EndPoints = { "myRedis.redis.cache.windows.net:6380" },
Password = "access-key",
Ssl = true,
AbortOnConnectFail = false, // Don't throw on initial failure
ConnectRetry = 3, // Retry connection 3 times
ConnectTimeout = 5000, // 5 second connect timeout
SyncTimeout = 3000, // 3 second sync operation timeout
AsyncTimeout = 5000, // 5 second async timeout
ReconnectRetryPolicy = new ExponentialRetry(5000), // Exponential backoff
KeepAlive = 60 // Send keepalive every 60 seconds
};
// Use a singleton connection multiplexer
private static Lazy<ConnectionMultiplexer> _connection =
new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(options));
public static ConnectionMultiplexer Connection => _connection.Value;
// Usage with retry
public async Task<string> GetWithRetry(string key, int maxRetries = 3)
{
for (int i = 0; i < maxRetries; i++)
{
try
{
var db = Connection.GetDatabase();
return await db.StringGetAsync(key);
}
catch (RedisConnectionException) when (i < maxRetries - 1)
{
await Task.Delay(TimeSpan.FromMilliseconds(Math.Pow(2, i) * 100));
}
}
throw new Exception($"Failed to get key '{key}' after {maxRetries} retries");
}
Monitoring with Azure Monitor
# Create alerts for memory pressure
az monitor metrics alert create \
--name "RedisMemoryAlert" \
--resource-group myRG \
--scopes "/subscriptions/{subId}/resourceGroups/myRG/providers/Microsoft.Cache/redis/myRedis" \
--condition "avg UsedMemoryPercentage > 80" \
--description "Redis memory usage exceeds 80%"
# Alert for high eviction rate
az monitor metrics alert create \
--name "RedisEvictionAlert" \
--resource-group myRG \
--scopes "/subscriptions/{subId}/resourceGroups/myRG/providers/Microsoft.Cache/redis/myRedis" \
--condition "total EvictedKeys > 1000" \
--window-size 5m \
--description "Redis evicting more than 1000 keys in 5 minutes"
# Alert for server load
az monitor metrics alert create \
--name "RedisLoadAlert" \
--resource-group myRG \
--scopes "/subscriptions/{subId}/resourceGroups/myRG/providers/Microsoft.Cache/redis/myRedis" \
--condition "avg ServerLoad > 80" \
--description "Redis server load exceeds 80%"
Understanding Azure Service Limits and Quotas
Every Azure service operates within defined limits and quotas that govern the maximum throughput, connection count, request rate, and resource capacity available to your subscription. These limits exist to protect the multi-tenant platform from noisy-neighbor effects and to ensure fair resource allocation across all customers. When your workload approaches or exceeds these limits, the service enforces them through throttling (HTTP 429 responses), request rejection, or degraded performance.
Azure service limits fall into two categories: soft limits that can be increased through a support request, and hard limits that represent fundamental architectural constraints of the service. Before designing your architecture, review the published limits for every Azure service in your solution. Plan for the worst case: what happens when you hit the limit during a traffic spike? Your application should handle throttled responses gracefully rather than failing catastrophically.
Use Azure Monitor to track your current utilization as a percentage of your quota limits. Create dashboards that show utilization trends over time and set alerts at 70 percent and 90 percent of your limits. When you approach a soft limit, submit a quota increase request proactively rather than waiting for a production incident. Microsoft typically processes quota increase requests within a few business days, but during high-demand periods it may take longer.
For services that support multiple tiers or SKUs, evaluate whether upgrading to a higher tier provides the headroom you need. Compare the cost of the upgrade against the cost of engineering effort to work around the current limits. Sometimes, paying for a higher service tier is more cost-effective than building complex application-level sharding, caching, or load-balancing logic to stay within the lower tier's constraints.
Disaster Recovery and Business Continuity
When resolving service issues, consider the broader disaster recovery and business continuity implications. If Azure Redis Cache Eviction and Memory Pressure is a critical dependency, your Recovery Time Objective (RTO) and Recovery Point Objective (RPO) determine how quickly you need to restore service and how much data loss is acceptable.
Implement a multi-region deployment strategy for business-critical services. Azure paired regions provide automatic data replication and prioritized recovery during regional outages. Configure your application to failover to the secondary region when the primary region is unavailable. Test your failover procedures regularly to ensure they work correctly and meet your RTO targets.
Maintain infrastructure-as-code templates for all your Azure resources so you can redeploy your entire environment in a new region if necessary. Store these templates in a geographically redundant source code repository. Document the manual steps required to complete a region failover, including DNS changes, connection string updates, and data synchronization verification.
Key Optimization Strategies
// Set TTL on all cached items
await db.StringSetAsync("user:123", userData, TimeSpan.FromMinutes(30));
// Use hash types instead of separate string keys
await db.HashSetAsync("user:123", new HashEntry[] {
new HashEntry("name", "Alice"),
new HashEntry("email", "alice@example.com"),
new HashEntry("role", "admin")
});
// Compress large values before storing
using var compressedStream = new MemoryStream();
using (var gzip = new GZipStream(compressedStream, CompressionLevel.Optimal))
{
await JsonSerializer.SerializeAsync(gzip, largeObject);
}
await db.StringSetAsync("large:key", compressedStream.ToArray(), TimeSpan.FromHours(1));
Scaling Up
# Scale to a larger tier
az redis update \
--name myRedis \
--resource-group myRG \
--sku Premium \
--vm-size P2
# Enable clustering for horizontal scaling
az redis create \
--name myClusteredRedis \
--resource-group myRG \
--location eastus \
--sku Premium \
--vm-size P1 \
--shard-count 3
Capacity Planning and Forecasting
The most effective resolution is preventing the issue from recurring through proactive capacity planning. Establish a regular review cadence where you analyze growth trends in your service utilization metrics and project when you will approach limits.
Use Azure Monitor metrics to track the key capacity indicators for Azure Redis Cache Eviction and Memory Pressure over time. Create a capacity planning workbook that shows current utilization as a percentage of your provisioned limits, the growth rate over the past 30, 60, and 90 days, and projected dates when you will reach 80 percent and 100 percent of capacity. Share this workbook with your engineering leadership to support proactive scaling decisions.
Factor in planned events that will drive usage spikes. Product launches, marketing campaigns, seasonal traffic patterns, and batch processing schedules all create predictable demand increases that should be accounted for in your capacity plan. If your application serves a global audience, consider time-zone-based traffic distribution and scale accordingly.
Implement autoscaling where the service supports it. Azure autoscale rules can automatically adjust capacity based on real-time metrics. Configure scale-out rules that trigger before you reach limits (at 70 percent utilization) and scale-in rules that safely reduce capacity during low-traffic periods to optimize costs. Test your autoscale rules under load to verify that they respond quickly enough to protect against sudden traffic spikes.
Summary
Redis memory pressure is resolved through a combination of proper eviction policy selection (use allkeys-lru for pure caching), adequate maxmemory-reserved configuration (10-50% depending on tier), TTL enforcement on all cached keys, and proactive monitoring with Azure Monitor alerts. When memory pressure persists despite optimization, scale up to a larger tier or enable clustering. Always use --bigkeys to identify memory hogs, and compress large values before caching.
For more details, refer to the official documentation: What is Azure Cache for Redis?, Troubleshoot Azure Cache for Redis client-side issues, Troubleshoot Azure Cache for Redis latency and timeouts.