Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Redis · Command

SETEX

SETEX stores a string at a key and gives it a timeout in seconds. It is deprecated in favor of SET with the EX option.

Since
2.0.0

How it works

SETEX writes a string to the specified key and assigns an expiration measured in seconds. It replaces an existing value and is functionally the same as SET with the EX option; invalid seconds cause an error.

Syntax

SETEX key seconds value

Parameters

NameTypeDescription
keykeyThe name of the key.
secondslongThe time to live, in seconds.
valuestringThe value to set.

Returns

Simple string reply: OK when the operation succeeds.

Key points

  • SETEX stores a string and schedules the key to expire after the requested number of seconds.
  • Its behavior can be expressed with SET followed by the EX expiration option.
  • The key argument identifies the Redis key to create or replace.
  • The seconds argument specifies how long the key remains available.
  • The value argument supplies the string stored by the command.
  • SETEX creates the target key when no key with that name currently exists.

Common mistakes

  • SETEX is deprecated; use SET with EX for new code or migrations.
  • The seconds argument must be valid; otherwise Redis returns an error.

Example: Cache a value with a timeout

redis-cli SETEX cache:user:42 60 '{"name":"Ada"}'
redis-cli TTL cache:user:42
redis-cli GET cache:user:42

Stores a JSON string for 60 seconds, then checks its remaining lifetime and reads the value.

When to use it

Expiring cache entries

Cache a serialized response with a bounded lifetime so stale data disappears automatically.

Temporary credentials

Store a short-lived token or session value without requiring a separate expiration command.

Self-expiring coordination data

Set a safety timeout on a transient coordination key.

Interview questions

QWhat does SETEX do and what is its complexity?

SETEX takes a key, a lifetime in seconds, and a string value. It sets the value and expiration together in one operation, with O(1) complexity.

Follow-up: How should new code express the same operation? Use SET key value EX seconds, which is the documented replacement.

QWhat are SETEX's arguments?

The syntax is SETEX key seconds value. The seconds argument is the key's time to live, and the value is the string stored under the key.

Follow-up: What happens if seconds is invalid? Redis returns an error rather than applying the command.

QWhat happens when the key already exists?

An existing key is overwritten with the supplied string and receives the specified expiration. The command creates the key when it does not already exist.

Follow-up: How can the remaining lifetime be inspected? Use TTL on the key after SETEX.

  • SET
  • TTL
  • GET
  • PSETEX

Source: Setex | Docs. Checked 2026-10-16.