Redis Conventions To Follow

Namespaces Convention

In Redis, namespaces are not a built-in feature, but a naming convention used to logically organize and manage keys. The namespace concept is achieved by using prefixes in key names, separating parts with a delimiter like a colon (:). This approach helps group related keys, avoid naming collisions, and improve readability.

Why Use Namespaces in Redis?

  1. Organization: Helps categorize keys by context or functionality.

  2. Collision Avoidance: Prevents different parts of the application from accidentally overwriting each other’s keys.

  3. Pattern Matching: Simplifies key retrieval using pattern-based commands like SCAN or KEYS.

  4. Multi-Tenancy: Allows segregating keys for different users or environments.

The convention typically follows this structure:

<application>:<module>:<key>
  • Application Name: Identifies the application or service using the Redis instance.

  • Module/Feature: Represents the feature or module within the application.

  • Key: The specific key being stored.

Examples

  • Single-Tenant Application
user:123:profile # Stores profile data for user ID 123 
user:123:settings # Stores settings data for user ID 123 
order:456:details # Stores details for order ID 456
  • Multi-Tenant Application
tenant1:user:123:profile # Profile data for user 123 in tenant1 
tenant2:order:456:details # Order details for order 456 in tenant2
  • Environment-Based Namespaces
prod:user:123:profile # Production environment 
dev:user:123:profile # Development environment

Operations Using Namespaces

  • Retrieve Keys by Namespace
SCAN 0 MATCH user:123:* COUNT 100
#Retrieves all keys under the user:123 namespace.
  • Delete Keys by Namespace
SCAN 0 MATCH user:123:* | xargs redis-cli DEL
#Deletes all keys within a specific namespace (careful with this in production).
  • Key Expiry

      #Apply expiration (EXPIRE) to namespace-specific keys
      EXPIRE user:123:profile 3600
    
  • Avoid KEYS Command in Production

    Use SCAN instead, as KEYS blocks the server during its operation.