DEV Community

Abhay Nepal
Abhay Nepal

Posted on • Originally published at nepalabhay.hashnode.dev on

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 others 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>
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • Environment-Based Namespaces
prod:user:123:profile # Production environment dev:user:123:profile # Development environment
Enter fullscreen mode Exit fullscreen mode

Operations Using Namespaces

  • Retrieve Keys by Namespace
SCAN 0 MATCH user:123:* COUNT 100#Retrieves all keys under the user:123 namespace.
Enter fullscreen mode Exit fullscreen mode
  • 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).
Enter fullscreen mode Exit fullscreen mode
  • Key Expiry

  • Avoid KEYS Command in Production

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

Top comments (0)