skip to Main Content

Trying to LOCK key for a scheduler, but ioredis is allowing me to create multiple keys with same name.

import * as redis from '../redis'

const redCli = redis.get(); // get function that starts ioredis

scheduleJob('my-job', '*/05 * * * * *', async () => {
  const key = await redCli.set('my-key', 'key-value', 'EX', 30); // 30 seconds key lifetime  
  console.log(`KEY: ${key}`); // always log 'OK'

  if (!key) {
  // log error and return. NEVER gets here.
  } 

  // ALSO TRIED:
  if (redCli.exists('my-key')...
  if (await redCli.ttl('my-key')...


  // continue the flow...
});

I create a key with 30 seconds of lifetime. And my scheduler runs every 5 seconds.
When I try to redCli.set() a key that already exists, shouldn’t return an ERROR/FALSE? Anything but ‘OK’…

2

Answers


  1. Chosen as BEST ANSWER

    Not sure why my attempts didn't work, but I solved this using get

    const cachedKey = await redisClient.get('my-key');
    
    if(cachedKey) { 
      // Key Already Exists
    }
    

  2. Like most mutating commands in Redis, the SET command in Redis is an upsert. That’s just how Redis works.

    From the docs for the SET command:

    If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search