redis/set

Set Key Value

Set a string value for a given key in Redis.

redis
string
basic
write

Command

SET key value

Explanation

Redis `SET` is a fundamental command used to store string values in memory. It can store simple text, numbers, or serialized objects. The command overwrites existing data if the key already exists. You can also use optional parameters like `EX` or `PX` to set expiry time in seconds or milliseconds, or `NX`/`XX` to control conditional setting.

Common Use Cases

  • Storing simple key-value pairs like usernames or session tokens
  • Initializing counters or configuration values
  • Caching temporary API responses

Best Practices

  • Use expiration (`EX` or `PX`) for transient data
  • Namespace keys (e.g., `user:100:name`) to avoid collisions
  • Use JSON or MessagePack for structured values

Common Mistakes to Avoid

  • Overwriting an existing key unintentionally
  • Storing complex data without serialization

Troubleshooting

Problem: Old value overwritten unexpectedly

Solution: Use `SETNX` or `SET key value NX` to only set if key doesn’t exist.

Problem: Data missing after restart

Solution: Ensure Redis persistence (AOF/RDB) is configured properly.

Examples

Set key 'name' to the value 'John'

SET name "John"

Set key 'counter' with numeric value 100

SET counter 100

Set a JSON-like string value

SET session:user123 '{"token":"abc123"}'