Redis keys are not expiring - Laravel, Predis

For those who uses Laravel, it is possible to use EX param (expire resolution) + ttl. In below example EX means that TTL is expressed in seconds (see Redis docs: So the result of below will be that $val stored under $key will be removed after 35 seconds.

Redis::set($key, $val, 'EX', 35);

In predis u can use the same, actually Laravel uses predis under the hood.

Some other process might call SET to update the key-value pair, in this case, the expiration will be removed.

// set expiration
EXPIRE key expiration_in_seconds
// update key-value pair with no expiration
SET key new_value
// now, expiration has been reset, and the key won't be expired any more

In order to keep the expiration, when you update the key-value pair, you should call SET with expiration parameters.

// get TTL, i.e. how much time left before the key will be expired
TTL key
// update with expiration parameter
SET key new_value EX ttl

You can wrap the two commands into a lua script to make it atomic. And you also need to take care of the case that key doesn't exist when you call TTL. See the document for details.