Redis Best Practices for Development: Keys, Expiry, Security

Your Redis cache works in development, then production brings slow commands, memory that never stops growing, or keys nobody can find. Most of those problems come from a handful of habits that are cheap to fix at design time and expensive to fix later.

These Redis best practices cover key naming, data structures, expiry and eviction, the cache-aside pattern, big and hot keys, SCAN instead of KEYS, pipelining, connection reuse, persistence, security and monitoring. The .NET sample at the end uses StackExchange.Redis 2.8.58 on .NET 10 and was compiled here. It was not run against a live server (see the notes in the summary).

Diagram of the cache-aside pattern: the application reads Redis first, loads from the database on a miss and stores the value in Redis with a TTL

Which Redis best practices matter most?

  • Design: predictable key names, the right data structure, small values.
  • Lifetime: a TTL on every cache key, a memory limit and an eviction policy.
  • Access: cache-aside reads, SCAN for lookups, pipelining for batches, one shared connection.
  • Operations: pick persistence on purpose, lock down access, watch INFO and SLOWLOG.

This article is the design checklist. For the .NET wiring, see dependency injection of the ConnectionMultiplexer and Redis distributed cache in C# .NET with examples.

Key naming and design

Redis has no schemas or tables, so the key name is your schema. Use one consistent pattern, usually colon separated: app:entity:id[:field]. The keyspace documentation describes keys and their commands.

SET shop:product:42 "{…json…}" SET shop:session:9f3a "{…}" SET billing:invoice:2024:1007 "{…}"
  • Start with a namespace (shop:) so several apps or environments can share one instance without collisions.
  • Put the stable part first and the id last, so a pattern such as shop:product:* stays useful.
  • Keep keys short but readable. Very long keys cost memory in every copy and every replica.
  • Do not put secrets or personal data in key names; key names show up in logs, SLOWLOG and monitoring tools.
  • Add a version when the stored shape changes, for example shop:v2:product:42, so old and new code can coexist during a deployment.

Choose the right data structure

A JSON string is fine for a whole object you always read and write together. Other structures often fit better:

  • String: a serialized object, a counter (INCR) or a flag.
  • Hash: an object whose fields you update one at a time (HSET, HGET).
  • Set: unique members and membership checks, such as tags.
  • Sorted set: leaderboards and time-ordered indexes.
  • List and stream: queues and event logs.

Pick the structure for the operation you run most. Reading one field of a hash is cheaper than deserializing a large JSON string to read one value.

TTL, expiry and eviction policies

A cache without expiry grows until it fills memory. Set a TTL when you write (SET key value EX 600, or the expiry argument in StackExchange.Redis) instead of a separate EXPIRE call, so a crash between two commands never leaves an immortal key. EXPIRE documents the command.

  • Add random jitter to TTLs so a batch of keys loaded together does not expire together and send a spike to your database.
  • Choose the TTL from how stale the data may be, not from a habit of one hour.
  • Set maxmemory so Redis has a ceiling, and choose maxmemory-policy deliberately.

The eviction documentation lists the policies. The ones most used for caches:

  • allkeys-lru: evict the least recently used keys, whether or not they have a TTL. A common choice for a pure cache.
  • allkeys-lfu: evict the least frequently used keys.
  • volatile-ttl: among keys with a TTL, evict those closest to expiry.
  • noeviction: refuse writes that need more memory. Use it when Redis holds data you cannot lose.

The volatile-* policies only consider keys that have an expiry, so keys without a TTL are never evicted by them.

Cache-aside pattern

In cache-aside the application owns the logic: read the cache, on a miss load from the source, store the result with a TTL, return it. When data changes, update the database first and then delete (or overwrite) the cached key. The diagram above shows the flow and the code in the example section implements it.

  • Treat the cache as optional: if Redis is down, fall back to the database instead of failing the request.
  • Cache missing results briefly too (for example a short TTL on a “not found” marker) if repeated misses would hammer the database.
  • A popular key that expires can make many requests hit the database at once. Jitter helps; for very hot keys also consider a lock or refresh-ahead approach.

Avoid big keys and hot keys

Redis runs commands on one main thread, so one slow command delays every client. Two usual causes are:

  • Big keys: a huge string, or a hash, list or set with millions of members. Reading or deleting it blocks other work. Split it into smaller keys or buckets, and delete large keys with UNLINK (non-blocking free) instead of DEL. Check sizes with MEMORY USAGE key, or run redis-cli --bigkeys against a non-critical instance.
  • Hot keys: one key that receives a large share of traffic. Cache a copy in application memory for a few seconds, or spread the load over several keys such as shop:config:1 to shop:config:4.
  • Unbounded collections: a list or set that only ever grows. Trim it or give it a TTL.

Use SCAN, not KEYS

The KEYS command page warns to use extreme care in production because it may ruin performance on large databases. SCAN walks the keyspace in small steps with a cursor, so other clients keep being served.

# avoid in production KEYS shop:product:* # use a cursor and a hint for the page size SCAN 0 MATCH shop:product:* COUNT 500

SCAN may return the same key more than once and keys added or removed during the scan may or may not appear, so make the work per key safe to repeat. COUNT is a hint, not a limit. On a cluster each node must be scanned. See get all keys from Redis cache in C#.NET for the .NET side.

Pipelining and connection reuse

Each command costs a network round trip. Pipelining sends several commands without waiting for each reply, which cuts the waiting time for batches. In StackExchange.Redis, CreateBatch() does this, and plain async calls from many threads are already multiplexed over one connection.

Connection reuse matters just as much. Opening a connection per request costs a TCP (and TLS) handshake each time. Create one ConnectionMultiplexer, register it as a singleton and share it. If connections drop, see Redis connection resiliency in ASP.NET Core and set AbortOnConnectFail=false so the client keeps retrying at start-up.

Persistence: RDB vs AOF

The persistence documentation describes the options:

  • None: fastest and simplest for a pure cache you can rebuild. Everything is lost on restart.
  • RDB snapshots: compact point-in-time files, quick restarts, but changes since the last snapshot can be lost.
  • AOF: logs every write. With appendfsync everysec (the default policy) you can lose about one second of writes; always is safer and slower.
  • RDB + AOF: both in one instance when you need durability and fast restarts.

Decide from the data: a cache that can be rebuilt from the database rarely needs AOF, while Redis used as a primary store does.

Security: auth, ACLs and TLS

Never expose Redis directly to the internet. The security documentation recommends keeping it reachable only by trusted clients.

  • Network: bind to private interfaces and firewall the port.
  • Authentication and ACLs: require a password and create ACL users with only the commands and key patterns each application needs, instead of sharing the default user.
  • TLS: encrypt traffic between clients and server, especially across networks you do not control.
  • Dangerous commands: restrict FLUSHALL, CONFIG and KEYS with ACLs.
ACL SETUSER shopapp on >use-a-long-secret ~shop:* +get +set +del +expire +scan

For connection strings with TLS and passwords, see Redis connect with SSL/TLS using C# .NET. The ACL line above was not run here.

Monitoring: INFO and SLOWLOG

Two commands answer most questions. INFO reports memory, clients, hit and miss counters (keyspace_hits, keyspace_misses), evictions and persistence status. SLOWLOG GET 10 shows the slowest recent commands; the SLOWLOG GET reference notes that the time is the command execution time in microseconds and excludes network I/O.

redis-cli INFO memory redis-cli INFO stats redis-cli SLOWLOG GET 10
  • A falling hit ratio means TTLs are too short or keys are evicted too early.
  • Rising evicted_keys means memory is too small or too many keys are stored.
  • Slow entries for KEYS, large HGETALL or SMEMBERS point to big keys or missing SCAN.

Example: .NET and StackExchange.Redis

This program uses cache-aside with a TTL and jitter, a pipelined batch, SCAN through server.KeysAsync and one shared multiplexer. Create it with dotnet new console and dotnet add package StackExchange.Redis --version 2.8.58.

using System.Text.Json;
using StackExchange.Redis;

// One multiplexer for the whole process: create it once and reuse it.
var options = ConfigurationOptions.Parse("localhost:6379");
options.AbortOnConnectFail = false;
options.ConnectTimeout = 5000;
using var mux = await ConnectionMultiplexer.ConnectAsync(options);
IDatabase db = mux.GetDatabase();

// Cache-aside: read the cache, on a miss load from the source and store with a TTL.
async Task<Product?> GetProductAsync(int id)
{
    string key = $"shop:product:{id}";
    RedisValue cached = await db.StringGetAsync(key);
    if (cached.HasValue)
        return JsonSerializer.Deserialize<Product>((string)cached!);

    Product? fromDb = await LoadFromDatabaseAsync(id);   // your real data source
    if (fromDb is not null)
    {
        // Add random jitter so many keys do not expire at the same second.
        var ttl = TimeSpan.FromMinutes(10) + TimeSpan.FromSeconds(Random.Shared.Next(0, 60));
        await db.StringSetAsync(key, JsonSerializer.Serialize(fromDb), ttl);
    }
    return fromDb;
}

Task<Product?> LoadFromDatabaseAsync(int id) =>
    Task.FromResult<Product?>(new Product(id, $"Item {id}", 9.99m));

Console.WriteLine((await GetProductAsync(1))?.Name);   // miss, then cached
Console.WriteLine((await GetProductAsync(1))?.Name);   // hit

// Pipelining: queue commands and wait once for all replies.
var batch = db.CreateBatch();
var tasks = Enumerable.Range(1, 100)
    .Select(i => batch.StringSetAsync($"shop:counter:{i}", i, TimeSpan.FromMinutes(5)))
    .ToArray();
batch.Execute();
await Task.WhenAll(tasks);

// SCAN instead of KEYS: Keys() uses SCAN on servers that support it.
IServer server = mux.GetServer(mux.GetEndPoints()[0]);
int count = 0;
await foreach (var k in server.KeysAsync(pattern: "shop:counter:*", pageSize: 250))
    count++;
Console.WriteLine($"counters: {count}");

record Product(int Id, string Name, decimal Price);

Status: this sample compiled with no warnings or errors on .NET 10. It was not run, because no Redis server was available in the test environment, so the console output is not shown. Run it against a local Redis and check that the second lookup prints without calling your data source.

Common mistakes and fixes

  • Memory keeps growing: keys have no TTL or maxmemory is unset. Add TTLs and a limit.
  • Writes fail with an OOM error: the policy is noeviction and memory is full. Use an allkeys-* policy for a cache.
  • Latency spikes: check SLOWLOG for KEYS and big keys.
  • Many connections: a connection is created per request. Share one multiplexer.
  • Database load spikes at regular times: many keys expire together. Add jitter.

Frequently asked questions

What are the most important Redis best practices?

Use consistent key names, set a TTL on cache keys, set maxmemory with an eviction policy, avoid big keys and the KEYS command, reuse one connection, and secure access with authentication, ACLs and TLS.

What are Redis key naming best practices?

Use a colon-separated pattern such as app:entity:id, start with a namespace, keep names short but readable, add a version when the stored shape changes, and avoid secrets or personal data in key names.

Should I use KEYS or SCAN in production?

Use SCAN. KEYS walks the whole keyspace in one command and can block other clients on a large database, while SCAN returns results in small steps with a cursor. Make the per-key work safe to repeat because SCAN can return duplicates.

Summary

Name keys consistently, choose the structure for your most common operation, give every cache key a TTL, bound memory with an eviction policy, and read through cache-aside. Avoid big keys, hot keys and KEYS, reuse one connection, pick persistence on purpose, restrict access with ACLs and TLS, and watch INFO and SLOWLOG. Tested here: the C# sample compiled on .NET 10 with StackExchange.Redis 2.8.58, and the documentation claims were checked against the official Redis docs. Not tested: running the sample against a live Redis server, the ACL command, Redis Cluster and managed services, and .NET 8 or 9.

Found this useful?

Bookmark this page and share it with your team. Get new .NET, cloud and database tutorials in your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *