-1

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?

Adrian Seeley
  • 2,262
  • 2
  • 29
  • 37

2 Answers2

3

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).

antirez
  • 18,314
  • 5
  • 50
  • 44
2

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.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
  • I'm currently storing locks as ms since epoch, and when a server encounters a lock it will check to see if it's dead (over >15sec), delete it if it is, then try to acquire the lock again. – Adrian Seeley Jul 16 '14 at 17:49