Skip to content

Files

Latest commit

95fbe9a · Apr 26, 2025

History

History
190 lines (138 loc) · 5.63 KB

03.key_value_pair_and_persistence.md

File metadata and controls

190 lines (138 loc) · 5.63 KB

Working with Key-Value Pairs and Managing Expiration & Persistence in Redis

Redis is best known as a fast, in-memory key-value data store that supports various data types and advanced features like automatic expiration and persistence. At the heart of Redis lies the concept of storing and manipulating data using keys and values.

This article will explore:

  1. Key-Value Operations in Redis
  2. Expiration: Automatic Key Management
  3. Persistence: Saving Data to Disk

📦 1. Working with Key-Value Pairs in Redis

Redis keys can be associated with different types of values, such as strings, hashes, lists, sets, or sorted sets. The key is always a binary-safe string, and it acts as the identifier for accessing or modifying the associated value.

📌 Key Characteristics:

  • Keys are case-sensitive and can be up to 512 MB.
  • Values can be of various data types.
  • Every operation is atomic.
  • You can overwrite an existing key by using SET again.

✅ Basic Key-Value Operations:

Command Description
SET key value Store a key with a string value
GET key Retrieve the value of a key
DEL key Delete a key
EXISTS key Check if a key exists
TYPE key Get the type of value stored
RENAME oldkey newkey Rename a key
KEYS pattern Find keys matching a pattern
FLUSHALL / FLUSHDB Delete all keys (global or current DB)

🔍 Example:

SET user:1001 "Jenil"
GET user:1001                     # "Jenil"
EXISTS user:1001                  # 1 (true)
DEL user:1001
EXISTS user:1001                  # 0 (false)

🔎 Wildcard Pattern Matching with KEYS:

Pattern Matches
* Any number of characters
? Exactly one character
[abc] a, b, or c
user:* All keys starting with user:
KEYS user:*       # Returns all user-related keys

⚠️ Note: Avoid KEYS in production on large datasets — use SCAN for safer iteration.


⏳ 2. Expiration in Redis

Redis allows you to set expiration times on keys, meaning they will be automatically deleted after a certain duration.

This is especially useful for:

  • Session storage
  • Temporary caches
  • One-time passwords (OTP)
  • API rate limiting

🧭 Ways to Set Expiration:

Method Description
EXPIRE key seconds Set a timeout in seconds
PEXPIRE key milliseconds Set timeout in ms
TTL key Get time-to-live in seconds
PTTL key Time-to-live in ms
SET key value EX seconds Set + expiration in one
SET key value PX milliseconds Set + ms expiration

🔍 Example:

SET otp:123456 "793421" EX 300        # OTP expires in 5 min
TTL otp:123456                        # Returns time left
EXPIRE session:krishna 1800           # 30 min session

🔁 Modifying Expiration:

  • Use PERSIST key to remove a key's expiration:

    PERSIST otp:123456
  • You can reset TTL by using EXPIRE again or re-setting the key.

🧠 How Redis Handles Expired Keys:

  • Redis does not immediately delete expired keys.
  • It uses lazy deletion (access time check) and periodic scanning (10 keys at a time in a loop).
  • This strategy avoids performance spikes but keeps memory under control.

💾 3. Persistence in Redis

Even though Redis is an in-memory store, it provides multiple options for persistence, so your data can survive server restarts or crashes.

Redis supports two primary forms of persistence:


🗂 A. RDB (Redis Database Backup) Snapshots

Creates point-in-time snapshots of your data at specified intervals.

📌 Configuration:

In redis.conf, you can define:

save 900 1       # 1 change in 15 minutes
save 300 10      # 10 changes in 5 minutes
save 60 10000    # 10,000 changes in 1 minute

📁 Output File:

  • Stored in binary format: dump.rdb
  • Lightweight, but may lose recent changes on crash.

🧾 Manual Snapshot:

SAVE         # Blocking save
BGSAVE       # Non-blocking, recommended

🧾 B. AOF (Append-Only File)

Logs every write operation to a file (appendonly.aof) in sequential order.

📌 Characteristics:

  • More durable than RDB (can recover every command).
  • Slower than RDB due to logging every write.
  • You can configure how often it syncs data to disk:
    appendfsync always     # Every command (slowest but safest)
    appendfsync everysec   # Once per second (balanced)
    appendfsync no         # OS decides (fastest, least safe)

🔄 Rewrite AOF:

Over time, the file grows. Redis can compact it:

BGREWRITEAOF

🔁 Can You Use Both RDB and AOF?

Yes. Redis allows using both together to strike a balance:

  • Use RDB for fast recovery on full data dumps.
  • Use AOF for durability of recent changes.

In case of a restart, Redis will prefer AOF if both exist.


⚙️ Summary Table

Feature RDB AOF
Durability Medium High
File Size Small Large
Performance High Slower
Recovery Speed Fast Slower
Use-case Backup Reliability

📌 Conclusion

Redis’s key-value model is extremely powerful thanks to:

  • Flexible operations on keys
  • Optional time-to-live (TTL) for temporary data
  • Persistence mechanisms to ensure data safety

Whether you’re building a cache, message queue, real-time leaderboard, or session store, understanding how to manage key lifecycles and persistence options is crucial for designing reliable systems with Redis.