title: How do I implement a Redis equivalent of a "unique index" while avoiding race conditions?
body: <p>I'm experimenting with using Redis as persistent storage. I want to store users in Redis, but I want the user ID as well as the user email address to be "unique".</p>
  
  <p>Here's where I'm at:</p>
  
  <pre><code>MULTI
  SET users:1 "&lt;user encoded as JSON&gt;"
  HSET users-indexes:email user-email@gmail.com 1
  EXEC
  </code></pre>
  
  <p>I'm using transactions because I don't want the database to end up in an invalid state if Redis crashes.</p>
  
  <p>Currently this will simply silently overwrite existing values. I need the transaction to fail/roll-back if the email address already exists in the hash.</p>
  
  <p>I could use <code>HSETNX</code> to prevent the index from being overwritten, but the user object would already be overwritten at that point. I could check if the email address exists in the index in advance, but then I'd have a race condition with other clients.</p>
  
  <p>I could add a write lock to my application, which would solve my problem as long as the only Redis client is a single instance of my application, otherwise there would still be a race condition.</p>
  
  <p>A pretty perfect solution in my scenario would be locking the Redis database temporarily while users are being created. Users are created so rarely that it wouldn't be a significant performance impact. That doesn't seem to be possible though.</p>
  
  <p>Am I missing a simple solution?</p>