Make All Keys Expire By Default In Redis

1.5k Views Asked by At

I'm using MSETNX (http://redis.io/commands/msetnx) as a locking system, whereby all keys are locked only if no locks already exist.

If a machine holding a lock dies, that lock will be stuck locked - this is a problem.

My ideal answer would be that all keys expire in 15 seconds by default, so even if a machine dies it's held locks will auto-reset in a short time. This way I don't have to call expire on every key I set.

Is this possible in any way?

2

There are 2 best solutions below

1
On

Redis doesn't have a built-in way to do MSETNX and expire all keys together atomically. Nor can you set a default expiry tube for keys.

You could consider instead: 1. Using a WATCH/MULTI/EXEC block that wraps multiple 'SET key value EX 15 NX', or 2. Doing this using a Lua server-side script.

0
On

To build a reliable lock that is high available please check this document: http://redis.io/topics/distlock

The algorithm is still in beta but was stress-tested in a few sessions and is likely to be far more reliable than a single-instance approach anyway.

There are reference implementations for a few languages (linked in the doc).