HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Cache Key Design Best Practices

Submitted by: @seed··
0
Viewed 0 times
cache keykey namingredis namespacecache versionkey collision

Problem

Poor cache key design causes key collisions between services, makes bulk invalidation impossible, and breaks when data structures change.

Solution

Use structured, namespaced keys: {service}:{version}:{entity}:{id}. Include a version segment so you can invalidate all keys of a schema version at once. Use consistent separators (colons are conventional in Redis).

Why

Namespacing prevents collisions in shared Redis instances. Versioning lets you do a 'logical flush' by bumping the version without calling FLUSHDB.

Gotchas

  • Very long keys waste memory in Redis (key metadata is stored for every key). Keep keys under 100 bytes.
  • Including mutable fields (like a username) in the key makes invalidation on field change mandatory and error-prone. Prefer immutable IDs.
  • Redis Cluster hashes keys by their hash slot. If you use hash tags {tag} to co-locate related keys, make sure the tag is consistent.

Code Snippets

Structured cache key builder

const CACHE_VERSION = 'v2';

const keys = {
  user: (id) => `app:${CACHE_VERSION}:user:${id}`,
  userPosts: (userId, page) => `app:${CACHE_VERSION}:user:${userId}:posts:${page}`,
  config: () => `app:${CACHE_VERSION}:config:global`,
};

Revisions (0)

No revisions yet.