How can I take advantage of the expiration of individual hash fields?

Last updated 11, Jul 2024

Question

How can I take advantage of the expiration of individual hash fields?

Answer

Expiration of individual hash fields, which allows you to set a time-to-live (TTL) for individual fields within a hash, has been added to Redis CE 7.4. For more information, consult the documentation.

Here are some creative use cases our users have envisioned for this feature:

  1. Log Rotation with Automatic Cleanup: Imagine a hash key storing events from the past hour. Each new event added gets a TTL of one hour. This allows you to easily retrieve recent events or simply use HLEN to get the number of events within the last hour.
  2. Time-Based Fraud Detection: Users can create a hash where a new counter field is added every hour, storing the number of events in that one-hour window. Events older than a specified timeframe (e.g., 48 hours) can automatically expire. This enables efficient querying of the hash for event counts within specific timeframes over the past 48 hours.
  3. Managing Session Data: Suppose you use hash keys for customer data (name, preferences, etc.). When a customer logs in, you can create a new hash key with their name as the session token and the session data as the value. Additionally, you can add a new field within the customer's hash key, such as "session," containing the session key. When the session expires, both the session key and the "session" field in the user's data key can automatically expire, simplifying session management.
  4. Tracking Active Sessions: Store a hash key containing all active sessions. When a session becomes inactive for a specific duration, the field holding that session's information can expire, effectively removing the inactive session. You can also use HLEN to get the current number of active sessions.

This feature enhances flexibility and efficiency in managing time-sensitive data within your applications.

References

Field expiration documentation.