Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Redis Conditional Update in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

Code Examples

Example 1: Conditional Update Using Watch and Multi

This example demonstrates how to use the watch and multi commands to perform a conditional update. The value is updated only if it has not been modified by another client during the transaction.

CODE_BLOCK_PLACEHOLDER_0
Explanation:

Example 2: Conditional Increment with Lua Script

Using a Lua script ensures atomic execution of the conditional operation.

const redis = require('redis');
const client = redis.createClient();

client.on('error', (err) => {
  console.error('Error:', err);
});

const key = 'counter:1000';
const incrementBy = 10;
const condition = 50; // Only increment if current value is less than this

const script = `
local current = tonumber(redis.call('get', KEYS[1]))
if current < tonumber(ARGV[1]) then
  return redis.call('incrby', KEYS[1], ARGV[2])
else
  return current
end
`;

client.eval(script, 1, key, condition, incrementBy, (err, result) => {
  if (err) throw err;
  console.log('Result:', result);
  client.quit();
});

Explanation:

Best Practices

Common Mistakes

FAQs

Q: What happens if the watched key is modified by another client before exec()?
A: The transaction will fail (exec() returns null), and you should retry the operation.

Q: Why use Lua scripts for conditional updates?
A: Lua scripts ensure atomicity and can perform more complex logic than simple Redis commands, reducing the risk of race conditions.

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost