← Back to Node.js, page 8

nodejs-0143 · Easy fresher

How do you use Redis from Node.js with ioredis: strings, expiry, counters, hashes, pipelines and connection handling?

Redis is an in-memory data store that is used for caches, counters, sessions, queues and pub/sub. With ioredis you create one client, call commands as promise-returning methods (set, get, incr, hset), give keys an expiry with EX, batch commands with pipeline or multi, handle the 'error' event, and close with quit(). Use key prefixes and always set a TTL on cache keys.

Full answer

What Redis is for

  • Very fast key-value operations in memory. Data types: strings, hashes, lists, sets, sorted sets, streams and more.
  • Typical uses: caching, rate limit counters, sessions, leaderboards, job queues (BullMQ), pub/sub and locks.
  • Data is mostly in memory, so it is not a main database unless persistence is configured and the data fits.

Using ioredis

  • const redis = new Redis(url). Create one client per process (and a separate one for subscribe mode). It reconnects automatically.
  • Commands match Redis names: redis.set('key', 'value', 'EX', 60) sets with a 60 second expiry. get returns a string or null. del removes keys.
  • incr and incrby are atomic, so they are safe for counters across many instances.
  • Hashes: hset('user:1', { name: 'Asha', plan: 'free' }), hgetall returns an object with string values.
  • ttl(key) shows the remaining seconds, -1 means no expiry, -2 means no key.
  • pipeline() sends many commands in one network round trip and returns results in order. multi() also wraps them in a transaction (all or nothing execution, but no rollback logic).
  • Everything is a string in Redis. Store JSON with JSON.stringify and parse it back.

Good habits

  • Key naming: app:entity:id, for example school:session:abc. Use SCAN, never KEYS, in production.
  • Set a TTL on cache keys so memory does not fill.
  • Listen to redis.on('error', ...), otherwise connection problems are printed as unhandled errors.
  • Close with await redis.quit() on shutdown.
  • Do not store huge values. Redis runs commands on one thread, so a slow command blocks all clients.
javascript
const Redis = require('ioredis');

async function main() {
  const redis = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379');
  redis.on('error', (err) => console.log('redis error:', err.message));
  const p = `demo:${process.pid}:`;                                  // unique prefix for this run

  await redis.set(p + 'greeting', 'hello', 'EX', 30);
  console.log('get:', await redis.get(p + 'greeting'), '| missing key:', await redis.get(p + 'nothing'));
  const ttl = await redis.ttl(p + 'greeting');
  console.log('ttl is between 1 and 30 seconds:', ttl > 0 && ttl <= 30);

  console.log('incr x3:', await redis.incr(p + 'visits'), await redis.incr(p + 'visits'), await redis.incr(p + 'visits'));

  await redis.hset(p + 'user:1', { name: 'Asha', plan: 'free' });
  console.log('hash:', JSON.stringify(await redis.hgetall(p + 'user:1')));

  await redis.set(p + 'json', JSON.stringify({ marks: [78, 91] }));
  console.log('json value:', JSON.parse(await redis.get(p + 'json')).marks.join(','));

  // pipeline: one round trip, results come back in order as [error, value] pairs
  const results = await redis.pipeline().incr(p + 'visits').get(p + 'greeting').exists(p + 'nothing').exec();
  console.log('pipeline:', JSON.stringify(results.map(([err, value]) => value)));

  // NX: set only if the key does not exist (the base of a lock)
  console.log('set NX first:', await redis.set(p + 'lock', 'a', 'EX', 5, 'NX'), '| second:', await redis.set(p + 'lock', 'b', 'EX', 5, 'NX'));

  const keys = await redis.keys(p + '*');          // fine in a demo, use SCAN in production
  await redis.del(...keys);
  console.log('cleaned up', keys.length, 'keys');
  await redis.quit();
}
main();

The script needs a running Redis server (REDIS_URL, default localhost:6379). It uses a unique key prefix and deletes its keys at the end. Install first with npm install ioredis (run here with ioredis 6.1.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): get: hello | missing key: null ttl is between 1 and 30 seconds: true incr x3: 1 2 3 hash: {"name":"Asha","plan":"free"} json value: 78,91 pipeline: [4,"hello",0] set NX first: OK | second: null cleaned up 5 keys

Key points

  • Redis is a fast in-memory store for caches, counters, sessions and queues.
  • ioredis commands are promise methods; one client per process.
  • set with EX gives an expiry, and incr is atomic.
  • pipeline batches commands into one round trip.
  • Prefix keys, set TTLs and handle the 'error' event.

Common mistakes

  • Using KEYS in production code.
  • Caching without a TTL.
  • Creating a client per request.
  • Reading and then writing a counter instead of using INCR.
  • No 'error' listener on the client.

Follow-ups

  • What is the difference between pipeline and multi?
  • Why is Redis single-threaded and still fast?
  • How do you persist Redis data, and when should you not rely on it?

Tips

  • Name four uses of Redis.
  • Mention atomic incr and EX.
  • Say that every value is a string.