Command: TTL.EXPIRE


Overview

The TTL.EXPIRE command is used to set a Time-To-Live (TTL) on a key. Once the specified duration elapses, the key is automatically deleted from the database. This feature is helpful for scenarios involving temporary data, session expiration, or auto-cleanup mechanisms.

Description

Sets a TTL (Time-To-Live) on an existing key. The TTL determines how long the key remains in the system before it is automatically removed. Time can be specified in:

  • Default (Seconds)

  • Seconds ( s )

  • Minutes ( m )

  • Hours ( h )

  • Days ( d )

  If the key does not exist, the command returns 0.
  
  If TTL is set successfully, the command returns 1.
  

Use Cases

  • Expiring temporary session tokens after 30 minutes.

  • Automatically deleting cache entries after 2 hours.

  • Setting a key to expire in 7 days for time-limited promotions or trials.

  • Managing lifecycle of transient data.


Syntax

  TTL.EXPIRE <key> <duration>
  

Where <duration> can be:

  • A number (in seconds by default)

  • A duration with unit suffix:

    • 10s → 10 seconds

    • 15m → 15 minutes

    • 2h → 2 hours

    • 3d → 3 days

Permissions

  • User must have write permission on the specified key.

  • If ACLs are implemented in your environment, ensure the user has permission for expire or ttl operations.

Examples
Set TTL with various formats
  localhost:9219> SET mykey "Hello"
OK

localhost:9219> TTL.EXPIRE mykey 10
Ok 1

localhost:9219> TTL.EXPIRE mykey 10s
Ok 1

localhost:9219> TTL.EXPIRE mykey 10m
Ok 1

localhost:9219> TTL.EXPIRE mykey 2h
Ok 1

localhost:9219> TTL.EXPIRE mykey 1d
Ok 1
  
Trying to expire a non-existent key
  localhost:9219> TTL.EXPIRE unknownKey 30s
Ok 0
  

Behavior on Error

Error Scenario Output/Error Message
Missing key or duration argument InvalidArgsError: Key and time must be provided...
Invalid duration format InvalidArgsError: Invalid time value provided
Key does not exist Ok 0