Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ioredis

luin18.9mMIT5.4.2TypeScript support: included

A robust, performance-focused and full-featured Redis client for Node.js.

redis, cluster, sentinel, pipelining

readme

ioredis

Build Status Coverage Status Commitizen friendly semantic-release

Discord Twitch YouTube Twitter

A robust, performance-focused and full-featured Redis client for Node.js.

Supports Redis >= 2.6.12. Completely compatible with Redis 7.x.

Features

ioredis is a robust, full-featured Redis client that is used in the world's biggest online commerce company Alibaba and many other awesome companies.

  1. Full-featured. It supports Cluster, Sentinel, Streams, Pipelining, and of course Lua scripting, Redis Functions, Pub/Sub (with the support of binary messages).
  2. High performance 🚀.
  3. Delightful API 😄. It works with Node callbacks and Native promises.
  4. Transformation of command arguments and replies.
  5. Transparent key prefixing.
  6. Abstraction for Lua scripting, allowing you to define custom commands.
  7. Supports binary data.
  8. Supports TLS 🔒.
  9. Supports offline queue and ready checking.
  10. Supports ES6 types, such as Map and Set.
  11. Supports GEO commands 📍.
  12. Supports Redis ACL.
  13. Sophisticated error handling strategy.
  14. Supports NAT mapping.
  15. Supports autopipelining.

100% written in TypeScript and official declarations are provided:

TypeScript Screenshot

Versions

Version Branch Node.js Version Redis Version
5.x.x (latest) main >= 12 2.6.12 ~ latest
4.x.x v4 >= 6 2.6.12 ~ 7

Refer to CHANGELOG.md for features and bug fixes introduced in v5.

🚀 Upgrading from v4 to v5

Links


Quick Start

Install

npm install ioredis

In a TypeScript project, you may want to add TypeScript declarations for Node.js:

npm install --save-dev @types/node

Basic Usage

// Import ioredis.
// You can also use `import { Redis } from "ioredis"`
// if your project is a TypeScript project,
// Note that `import Redis from "ioredis"` is still supported,
// but will be deprecated in the next major version.
const Redis = require("ioredis");

// Create a Redis instance.
// By default, it will connect to localhost:6379.
// We are going to cover how to specify connection options soon.
const redis = new Redis();

redis.set("mykey", "value"); // Returns a promise which resolves to "OK" when the command succeeds.

// ioredis supports the node.js callback style
redis.get("mykey", (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result); // Prints "value"
  }
});

// Or ioredis returns a promise if the last argument isn't a function
redis.get("mykey").then((result) => {
  console.log(result); // Prints "value"
});

redis.zadd("sortedSet", 1, "one", 2, "dos", 4, "quatro", 3, "three");
redis.zrange("sortedSet", 0, 2, "WITHSCORES").then((elements) => {
  // ["one", "1", "dos", "2", "three", "3"] as if the command was `redis> ZRANGE sortedSet 0 2 WITHSCORES`
  console.log(elements);
});

// All arguments are passed directly to the redis server,
// so technically ioredis supports all Redis commands.
// The format is: redis[SOME_REDIS_COMMAND_IN_LOWERCASE](ARGUMENTS_ARE_JOINED_INTO_COMMAND_STRING)
// so the following statement is equivalent to the CLI: `redis> SET mykey hello EX 10`
redis.set("mykey", "hello", "EX", 10);

See the examples/ folder for more examples. For example:

All Redis commands are supported. See the documentation for details.

Connect to Redis

When a new Redis instance is created, a connection to Redis will be created at the same time. You can specify which Redis to connect to by:

new Redis(); // Connect to 127.0.0.1:6379
new Redis(6380); // 127.0.0.1:6380
new Redis(6379, "192.168.1.1"); // 192.168.1.1:6379
new Redis("/tmp/redis.sock");
new Redis({
  port: 6379, // Redis port
  host: "127.0.0.1", // Redis host
  username: "default", // needs Redis >= 6
  password: "my-top-secret",
  db: 0, // Defaults to 0
});

You can also specify connection options as a redis:// URL or rediss:// URL when using TLS encryption:

// Connect to 127.0.0.1:6380, db 4, using password "authpassword":
new Redis("redis://:authpassword@127.0.0.1:6380/4");

// Username can also be passed via URI.
new Redis("redis://username:authpassword@127.0.0.1:6380/4");

See API Documentation for all available options.

Pub/Sub

Redis provides several commands for developers to implement the Publish–subscribe pattern. There are two roles in this pattern: publisher and subscriber. Publishers are not programmed to send their messages to specific subscribers. Rather, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

By leveraging Node.js's built-in events module, ioredis makes pub/sub very straightforward to use. Below is a simple example that consists of two files, one is publisher.js that publishes messages to a channel, the other is subscriber.js that listens for messages on specific channels.

// publisher.js

const Redis = require("ioredis");
const redis = new Redis();

setInterval(() => {
  const message = { foo: Math.random() };
  // Publish to my-channel-1 or my-channel-2 randomly.
  const channel = `my-channel-${1 + Math.round(Math.random())}`;

  // Message can be either a string or a buffer
  redis.publish(channel, JSON.stringify(message));
  console.log("Published %s to %s", message, channel);
}, 1000);
// subscriber.js

const Redis = require("ioredis");
const redis = new Redis();

redis.subscribe("my-channel-1", "my-channel-2", (err, count) => {
  if (err) {
    // Just like other commands, subscribe() can fail for some reasons,
    // ex network issues.
    console.error("Failed to subscribe: %s", err.message);
  } else {
    // `count` represents the number of channels this client are currently subscribed to.
    console.log(
      `Subscribed successfully! This client is currently subscribed to ${count} channels.`
    );
  }
});

redis.on("message", (channel, message) => {
  console.log(`Received ${message} from ${channel}`);
});

// There's also an event called 'messageBuffer', which is the same as 'message' except
// it returns buffers instead of strings.
// It's useful when the messages are binary data.
redis.on("messageBuffer", (channel, message) => {
  // Both `channel` and `message` are buffers.
  console.log(channel, message);
});

It's worth noticing that a connection (aka a Redis instance) can't play both roles at the same time. More specifically, when a client issues subscribe() or psubscribe(), it enters the "subscriber" mode. From that point, only commands that modify the subscription set are valid. Namely, they are: subscribe, psubscribe, unsubscribe, punsubscribe, ping, and quit. When the subscription set is empty (via unsubscribe/punsubscribe), the connection is put back into the regular mode.

If you want to do pub/sub in the same file/process, you should create a separate connection:

const Redis = require("ioredis");
const sub = new Redis();
const pub = new Redis();

sub.subscribe(/* ... */); // From now, `sub` enters the subscriber mode.
sub.on("message" /* ... */);

setInterval(() => {
  // `pub` can be used to publish messages, or send other regular commands (e.g. `hgetall`)
  // because it's not in the subscriber mode.
  pub.publish(/* ... */);
}, 1000);

PSUBSCRIBE is also supported in a similar way when you want to subscribe all channels whose name matches a pattern:

redis.psubscribe("pat?ern", (err, count) => {});

// Event names are "pmessage"/"pmessageBuffer" instead of "message/messageBuffer".
redis.on("pmessage", (pattern, channel, message) => {});
redis.on("pmessageBuffer", (pattern, channel, message) => {});

Streams

Redis v5 introduces a new data type called streams. It doubles as a communication channel for building streaming architectures and as a log-like data structure for persisting data. With ioredis, the usage can be pretty straightforward. Say we have a producer publishes messages to a stream with redis.xadd("mystream", "*", "randomValue", Math.random()) (You may find the official documentation of Streams as a starter to understand the parameters used), to consume the messages, we'll have a consumer with the following code:

const Redis = require("ioredis");
const redis = new Redis();

const processMessage = (message) => {
  console.log("Id: %s. Data: %O", message[0], message[1]);
};

async function listenForMessage(lastId = "$") {
  // `results` is an array, each element of which corresponds to a key.
  // Because we only listen to one key (mystream) here, `results` only contains
  // a single element. See more: https://redis.io/commands/xread#return-value
  const results = await redis.xread("block", 0, "STREAMS", "mystream", lastId);
  const [key, messages] = results[0]; // `key` equals to "mystream"

  messages.forEach(processMessage);

  // Pass the last id of the results to the next round.
  await listenForMessage(messages[messages.length - 1][0]);
}

listenForMessage();

Expiration

Redis can set a timeout to expire your key, after the timeout has expired the key will be automatically deleted. (You can find the official Expire documentation to understand better the different parameters you can use), to set your key to expire in 60 seconds, we will have the following code:

redis.set("key", "data", "EX", 60);
// Equivalent to redis command "SET key data EX 60", because on ioredis set method,
// all arguments are passed directly to the redis server.

Handle Binary Data

Binary data support is out of the box. Pass buffers to send binary data:

redis.set("foo", Buffer.from([0x62, 0x75, 0x66]));

Every command that returns a bulk string has a variant command with a Buffer suffix. The variant command returns a buffer instead of a UTF-8 string:

const result = await redis.getBuffer("foo");
// result is `<Buffer 62 75 66>`

It's worth noticing that you don't need the Buffer suffix variant in order to send binary data. That means in most case you should just use redis.set() instead of redis.setBuffer() unless you want to get the old value with the GET parameter:

const result = await redis.setBuffer("foo", "new value", "GET");
// result is `<Buffer 62 75 66>` as `GET` indicates returning the old value.

Pipelining

If you want to send a batch of commands (e.g. > 5), you can use pipelining to queue the commands in memory and then send them to Redis all at once. This way the performance improves by 50%~300% (See benchmark section).

redis.pipeline() creates a Pipeline instance. You can call any Redis commands on it just like the Redis instance. The commands are queued in memory and flushed to Redis by calling the exec method:

const pipeline = redis.pipeline();
pipeline.set("foo", "bar");
pipeline.del("cc");
pipeline.exec((err, results) => {
  // `err` is always null, and `results` is an array of responses
  // corresponding to the sequence of queued commands.
  // Each response follows the format `[err, result]`.
});

// You can even chain the commands:
redis
  .pipeline()
  .set("foo", "bar")
  .del("cc")
  .exec((err, results) => {});

// `exec` also returns a Promise:
const promise = redis.pipeline().set("foo", "bar").get("foo").exec();
promise.then((result) => {
  // result === [[null, 'OK'], [null, 'bar']]
});

Each chained command can also have a callback, which will be invoked when the command gets a reply:

redis
  .pipeline()
  .set("foo", "bar")
  .get("foo", (err, result) => {
    // result === 'bar'
  })
  .exec((err, result) => {
    // result[1][1] === 'bar'
  });

In addition to adding commands to the pipeline queue individually, you can also pass an array of commands and arguments to the constructor:

redis
  .pipeline([
    ["set", "foo", "bar"],
    ["get", "foo"],
  ])
  .exec(() => {
    /* ... */
  });

#length property shows how many commands in the pipeline:

const length = redis.pipeline().set("foo", "bar").get("foo").length;
// length === 2

Transaction

Most of the time, the transaction commands multi & exec are used together with pipeline. Therefore, when multi is called, a Pipeline instance is created automatically by default, so you can use multi just like pipeline:

redis
  .multi()
  .set("foo", "bar")
  .get("foo")
  .exec((err, results) => {
    // results === [[null, 'OK'], [null, 'bar']]
  });

If there's a syntax error in the transaction's command chain (e.g. wrong number of arguments, wrong command name, etc), then none of the commands would be executed, and an error is returned:

redis
  .multi()
  .set("foo")
  .set("foo", "new value")
  .exec((err, results) => {
    // err:
    //  { [ReplyError: EXECABORT Transaction discarded because of previous errors.]
    //    name: 'ReplyError',
    //    message: 'EXECABORT Transaction discarded because of previous errors.',
    //    command: { name: 'exec', args: [] },
    //    previousErrors:
    //     [ { [ReplyError: ERR wrong number of arguments for 'set' command]
    //         name: 'ReplyError',
    //         message: 'ERR wrong number of arguments for \'set\' command',
    //         command: [Object] } ] }
  });

In terms of the interface, multi differs from pipeline in that when specifying a callback to each chained command, the queueing state is passed to the callback instead of the result of the command:

redis
  .multi()
  .set("foo", "bar", (err, result) => {
    // result === 'QUEUED'
  })
  .exec(/* ... */);

If you want to use transaction without pipeline, pass { pipeline: false } to multi, and every command will be sent to Redis immediately without waiting for an exec invocation:

redis.multi({ pipeline: false });
redis.set("foo", "bar");
redis.get("foo");
redis.exec((err, result) => {
  // result === [[null, 'OK'], [null, 'bar']]
});

The constructor of multi also accepts a batch of commands:

redis
  .multi([
    ["set", "foo", "bar"],
    ["get", "foo"],
  ])
  .exec(() => {
    /* ... */
  });

Inline transactions are supported by pipeline, which means you can group a subset of commands in the pipeline into a transaction:

redis
  .pipeline()
  .get("foo")
  .multi()
  .set("foo", "bar")
  .get("foo")
  .exec()
  .get("foo")
  .exec();

Lua Scripting

ioredis supports all of the scripting commands such as EVAL, EVALSHA and SCRIPT. However, it's tedious to use in real world scenarios since developers have to take care of script caching and to detect when to use EVAL and when to use EVALSHA. ioredis exposes a defineCommand method to make scripting much easier to use:

const redis = new Redis();

// This will define a command myecho:
redis.defineCommand("myecho", {
  numberOfKeys: 2,
  lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
});

// Now `myecho` can be used just like any other ordinary command,
// and ioredis will try to use `EVALSHA` internally when possible for better performance.
redis.myecho("k1", "k2", "a1", "a2", (err, result) => {
  // result === ['k1', 'k2', 'a1', 'a2']
});

// `myechoBuffer` is also defined automatically to return buffers instead of strings:
redis.myechoBuffer("k1", "k2", "a1", "a2", (err, result) => {
  // result[0] equals to Buffer.from('k1');
});

// And of course it works with pipeline:
redis.pipeline().set("foo", "bar").myecho("k1", "k2", "a1", "a2").exec();

Dynamic Keys

If the number of keys can't be determined when defining a command, you can omit the numberOfKeys property and pass the number of keys as the first argument when you call the command:

redis.defineCommand("echoDynamicKeyNumber", {
  lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
});

// Now you have to pass the number of keys as the first argument every time
// you invoke the `echoDynamicKeyNumber` command:
redis.echoDynamicKeyNumber(2, "k1", "k2", "a1", "a2", (err, result) => {
  // result === ['k1', 'k2', 'a1', 'a2']
});

As Constructor Options

Besides defineCommand(), you can also define custom commands with the scripts constructor option:

const redis = new Redis({
  scripts: {
    myecho: {
      numberOfKeys: 2,
      lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
    },
  },
});

TypeScript Usages

You can refer to the example for how to declare your custom commands.

Transparent Key Prefixing

This feature allows you to specify a string that will automatically be prepended to all the keys in a command, which makes it easier to manage your key namespaces.

Warning This feature won't apply to commands like KEYS and SCAN that take patterns rather than actual keys(#239), and this feature also won't apply to the replies of commands even if they are key names (#325).

const fooRedis = new Redis({ keyPrefix: "foo:" });
fooRedis.set("bar", "baz"); // Actually sends SET foo:bar baz

fooRedis.defineCommand("myecho", {
  numberOfKeys: 2,
  lua: "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
});

// Works well with pipelining/transaction
fooRedis
  .pipeline()
  // Sends SORT foo:list BY foo:weight_*->fieldname
  .sort("list", "BY", "weight_*->fieldname")
  // Supports custom commands
  // Sends EVALSHA xxx foo:k1 foo:k2 a1 a2
  .myecho("k1", "k2", "a1", "a2")
  .exec();

Transforming Arguments & Replies

Most Redis commands take one or more Strings as arguments, and replies are sent back as a single String or an Array of Strings. However, sometimes you may want something different. For instance, it would be more convenient if the HGETALL command returns a hash (e.g. { key: val1, key2: v2 }) rather than an array of key values (e.g. [key1, val1, key2, val2]).

ioredis has a flexible system for transforming arguments and replies. There are two types of transformers, argument transformer and reply transformer:

const Redis = require("ioredis");

// Here's the built-in argument transformer converting
// hmset('key', { k1: 'v1', k2: 'v2' })
// or
// hmset('key', new Map([['k1', 'v1'], ['k2', 'v2']]))
// into
// hmset('key', 'k1', 'v1', 'k2', 'v2')
Redis.Command.setArgumentTransformer("hmset", (args) => {
  if (args.length === 2) {
    if (args[1] instanceof Map) {
      // utils is a internal module of ioredis
      return [args[0], ...utils.convertMapToArray(args[1])];
    }
    if (typeof args[1] === "object" && args[1] !== null) {
      return [args[0], ...utils.convertObjectToArray(args[1])];
    }
  }
  return args;
});

// Here's the built-in reply transformer converting the HGETALL reply
// ['k1', 'v1', 'k2', 'v2']
// into
// { k1: 'v1', 'k2': 'v2' }
Redis.Command.setReplyTransformer("hgetall", (result) => {
  if (Array.isArray(result)) {
    const obj = {};
    for (let i = 0; i < result.length; i += 2) {
      obj[result[i]] = result[i + 1];
    }
    return obj;
  }
  return result;
});

There are three built-in transformers, two argument transformers for hmset & mset and a reply transformer for hgetall. Transformers for hmset and hgetall were mentioned above, and the transformer for mset is similar to the one for hmset:

redis.mset({ k1: "v1", k2: "v2" });
redis.get("k1", (err, result) => {
  // result === 'v1';
});

redis.mset(
  new Map([
    ["k3", "v3"],
    ["k4", "v4"],
  ])
);
redis.get("k3", (err, result) => {
  // result === 'v3';
});

Another useful example of a reply transformer is one that changes hgetall to return array of arrays instead of objects which avoids an unwanted conversation of hash keys to strings when dealing with binary hash keys:

Redis.Command.setReplyTransformer("hgetall", (result) => {
  const arr = [];
  for (let i = 0; i < result.length; i += 2) {
    arr.push([result[i], result[i + 1]]);
  }
  return arr;
});
redis.hset("h1", Buffer.from([0x01]), Buffer.from([0x02]));
redis.hset("h1", Buffer.from([0x03]), Buffer.from([0x04]));
redis.hgetallBuffer("h1", (err, result) => {
  // result === [ [ <Buffer 01>, <Buffer 02> ], [ <Buffer 03>, <Buffer 04> ] ];
});

Monitor

Redis supports the MONITOR command, which lets you see all commands received by the Redis server across all client connections, including from other client libraries and other computers.

The monitor method returns a monitor instance. After you send the MONITOR command, no other commands are valid on that connection. ioredis will emit a monitor event for every new monitor message that comes across. The callback for the monitor event takes a timestamp from the Redis server and an array of command arguments.

Here is a simple example:

redis.monitor((err, monitor) => {
  monitor.on("monitor", (time, args, source, database) => {});
});

Here is another example illustrating an async function and monitor.disconnect():

async () => {
  const monitor = await redis.monitor();
  monitor.on("monitor", console.log);
  // Any other tasks
  monitor.disconnect();
};

Streamify Scanning

Redis 2.8 added the SCAN command to incrementally iterate through the keys in the database. It's different from KEYS in that SCAN only returns a small number of elements each call, so it can be used in production without the downside of blocking the server for a long time. However, it requires recording the cursor on the client side each time the SCAN command is called in order to iterate through all the keys correctly. Since it's a relatively common use case, ioredis provides a streaming interface for the SCAN command to make things much easier. A readable stream can be created by calling scanStream:

const redis = new Redis();
// Create a readable stream (object mode)
const stream = redis.scanStream();
stream.on("data", (resultKeys) => {
  // `resultKeys` is an array of strings representing key names.
  // Note that resultKeys may contain 0 keys, and that it will sometimes
  // contain duplicates due to SCAN's implementation in Redis.
  for (let i = 0; i < resultKeys.length; i++) {
    console.log(resultKeys[i]);
  }
});
stream.on("end", () => {
  console.log("all keys have been visited");
});

scanStream accepts an option, with which you can specify the MATCH pattern, the TYPE filter, and the COUNT argument:

const stream = redis.scanStream({
  // only returns keys following the pattern of `user:*`
  match: "user:*",
  // only return objects that match a given type,
  // (requires Redis >= 6.0)
  type: "zset",
  // returns approximately 100 elements per call
  count: 100,
});

Just like other commands, scanStream has a binary version scanBufferStream, which returns an array of buffers. It's useful when the key names are not utf8 strings.

There are also hscanStream, zscanStream and sscanStream to iterate through elements in a hash, zset and set. The interface of each is similar to scanStream except the first argument is the key name:

const stream = redis.hscanStream("myhash", {
  match: "age:??",
});

You can learn more from the Redis documentation.

Useful Tips It's pretty common that doing an async task in the data handler. We'd like the scanning process to be paused until the async task to be finished. Stream#pause() and Stream#resume() do the trick. For example if we want to migrate data in Redis to MySQL:

const stream = redis.scanStream();
stream.on("data", (resultKeys) => {
  // Pause the stream from scanning more keys until we've migrated the current keys.
  stream.pause();

  Promise.all(resultKeys.map(migrateKeyToMySQL)).then(() => {
    // Resume the stream here.
    stream.resume();
  });
});

stream.on("end", () => {
  console.log("done migration");
});

Auto-reconnect

By default, ioredis will try to reconnect when the connection to Redis is lost except when the connection is closed manually by redis.disconnect() or redis.quit().

It's very flexible to control how long to wait to reconnect after disconnection using the retryStrategy option:

const redis = new Redis({
  // This is the default value of `retryStrategy`
  retryStrategy(times) {
    const delay = Math.min(times * 50, 2000);
    return delay;
  },
});

retryStrategy is a function that will be called when the connection is lost. The argument times means this is the nth reconnection being made and the return value represents how long (in ms) to wait to reconnect. When the return value isn't a number, ioredis will stop trying to reconnect, and the connection will be lost forever if the user doesn't call redis.connect() manually.

When reconnected, the client will auto subscribe to channels that the previous connection subscribed to. This behavior can be disabled by setting the autoResubscribe option to false.

And if the previous connection has some unfulfilled commands (most likely blocking commands such as brpop and blpop), the client will resend them when reconnected. This behavior can be disabled by setting the autoResendUnfulfilledCommands option to false.

By default, all pending commands will be flushed with an error every 20 retry attempts. That makes sure commands won't wait forever when the connection is down. You can change this behavior by setting maxRetriesPerRequest:

const redis = new Redis({
  maxRetriesPerRequest: 1,
});

Set maxRetriesPerRequest to null to disable this behavior, and every command will wait forever until the connection is alive again (which is the default behavior before ioredis v4).

Reconnect on Error

Besides auto-reconnect when the connection is closed, ioredis supports reconnecting on certain Redis errors using the reconnectOnError option. Here's an example that will reconnect when receiving READONLY error:

const redis = new Redis({
  reconnectOnError(err) {
    const targetError = "READONLY";
    if (err.message.includes(targetError)) {
      // Only reconnect when the error contains "READONLY"
      return true; // or `return 1;`
    }
  },
});

This feature is useful when using Amazon ElastiCache instances with Auto-failover disabled. On these instances, test your reconnectOnError handler by manually promoting the replica node to the primary role using the AWS console. The following writes fail with the error READONLY. Using reconnectOnError, we can force the connection to reconnect on this error in order to connect to the new master. Furthermore, if the reconnectOnError returns 2, ioredis will resend the failed command after reconnecting.

On ElastiCache instances with Auto-failover enabled, reconnectOnError does not execute. Instead of returning a Redis error, AWS closes all connections to the master endpoint until the new primary node is ready. ioredis reconnects via retryStrategy instead of reconnectOnError after about a minute. On ElastiCache instances with Auto-failover enabled, test failover events with the Failover primary option in the AWS console.

Connection Events

The Redis instance will emit some events about the state of the connection to the Redis server.

Event Description
connect emits when a connection is established to the Redis server.
ready If enableReadyCheck is true, client will emit ready when the server reports that it is ready to receive commands (e.g. finish loading data from disk).
Otherwise, ready will be emitted immediately right after the connect event.
error emits when an error occurs while connecting.
However, ioredis emits all error events silently (only emits when there's at least one listener) so that your application won't crash if you're not listening to the error event.
close emits when an established Redis server connection has closed.
reconnecting emits after close when a reconnection will be made. The argument of the event is the time (in ms) before reconnecting.
end emits after close when no more reconnections will be made, or the connection is failed to establish.
wait emits when lazyConnect is set and will wait for the first command to be called before connecting.

You can also check out the Redis#status property to get the current connection status.

Besides the above connection events, there are several other custom events:

Event Description
select emits when the database changed. The argument is the new db number.

Offline Queue

When a command can't be processed by Redis (being sent before the ready event), by default, it's added to the offline queue and will be executed when it can be processed. You can disable this feature by setting the enableOfflineQueue option to false:

const redis = new Redis({ enableOfflineQueue: false });

TLS Options

Redis doesn't support TLS natively, however if the redis server you want to connect to is hosted behind a TLS proxy (e.g. stunnel) or is offered by a PaaS service that supports TLS connection (e.g. Redis.com), you can set the tls option:

const redis = new Redis({
  host: "localhost",
  tls: {
    // Refer to `tls.connect()` section in
    // https://nodejs.org/api/tls.html
    // for all supported options
    ca: fs.readFileSync("cert.pem"),
  },
});

Alternatively, specify the connection through a rediss:// URL.

const redis = new Redis("rediss://redis.my-service.com");

If you do not want to use a connection string, you can also specify an empty tls: {} object:

const redis = new Redis({
  host: "redis.my-service.com",
  tls: {},
});

TLS Profiles

Warning TLS profiles described in this section are going to be deprecated in the next major version. Please provide TLS options explicitly.

To make it easier to configure we provide a few pre-configured TLS profiles that can be specified by setting the tls option to the profile's name or specifying a tls.profile option in case you need to customize some values of the profile.

Profiles:

  • RedisCloudFixed: Contains the CA for Redis.com Cloud fixed subscriptions
  • RedisCloudFlexible: Contains the CA for Redis.com Cloud flexible subscriptions
const redis = new Redis({
  host: "localhost",
  tls: "RedisCloudFixed",
});

const redisWithClientCertificate = new Redis({
  host: "localhost",
  tls: {
    profile: "RedisCloudFixed",
    key: "123",
  },
});

Sentinel

ioredis supports Sentinel out of the box. It works transparently as all features that work when you connect to a single node also work when you connect to a sentinel group. Make sure to run Redis >= 2.8.12 if you want to use this feature. Sentinels have a default port of 26379.

To connect using Sentinel, use:

const redis = new Redis({
  sentinels: [
    { host: "localhost", port: 26379 },
    { host: "localhost", port: 26380 },
  ],
  name: "mymaster",
});

redis.set("foo", "bar");

The arguments passed to the constructor are different from the ones you use to connect to a single node, where:

  • name identifies a group of Redis instances composed of a master and one or more slaves (mymaster in the example);
  • sentinelPassword (optional) password for Sentinel instances.
  • sentinels are a list of sentinels to connect to. The list does not need to enumerate all your sentinel instances, but a few so that if one is down the client will try the next one.
  • role (optional) with a value of slave will return a random slave from the Sentinel group.
  • preferredSlaves (optional) can be used to prefer a particular slave or set of slaves based on priority. It accepts a function or array.
  • enableTLSForSentinelMode (optional) set to true if connecting to sentinel instances that are encrypted

ioredis guarantees that the node you connected to is always a master even after a failover. When a failover happens, instead of trying to reconnect to the failed node (which will be demoted to slave when it's available again), ioredis will ask sentinels for the new master node and connect to it. All commands sent during the failover are queued and will be executed when the new connection is established so that none of the commands will be lost.

It's possible to connect to a slave instead of a master by specifying the option role with the value of slave and ioredis will try to connect to a random slave of the specified master, with the guarantee that the connected node is always a slave. If the current node is promoted to master due to a failover, ioredis will disconnect from it and ask the sentinels for another slave node to connect to.

If you specify the option preferredSlaves along with role: 'slave' ioredis will attempt to use this value when selecting the slave from the pool of available slaves. The value of preferredSlaves should either be a function that accepts an array of available slaves and returns a single result, or an array of slave values priorities by the lowest prio value first with a default value of 1.

// available slaves format
const availableSlaves = [{ ip: "127.0.0.1", port: "31231", flags: "slave" }];

// preferredSlaves array format
let preferredSlaves = [
  { ip: "127.0.0.1", port: "31231", prio: 1 },
  { ip: "127.0.0.1", port: "31232", prio: 2 },
];

// preferredSlaves function format
preferredSlaves = function (availableSlaves) {
  for (let i = 0; i < availableSlaves.length; i++) {
    const slave = availableSlaves[i];
    if (slave.ip === "127.0.0.1") {
      if (slave.port === "31234") {
        return slave;
      }
    }
  }
  // if no preferred slaves are available a random one is used
  return false;
};

const redis = new Redis({
  sentinels: [
    { host: "127.0.0.1", port: 26379 },
    { host: "127.0.0.1", port: 26380 },
  ],
  name: "mymaster",
  role: "slave",
  preferredSlaves: preferredSlaves,
});

Besides the retryStrategy option, there's also a sentinelRetryStrategy in Sentinel mode which will be invoked when all the sentinel nodes are unreachable during connecting. If sentinelRetryStrategy returns a valid delay time, ioredis will try to reconnect from scratch. The default value of sentinelRetryStrategy is:

function (times) {
  const delay = Math.min(times * 10, 1000);
  return delay;
}

Cluster

Redis Cluster provides a way to run a Redis installation where data is automatically sharded across multiple Redis nodes. You can connect to a Redis Cluster like this:

const Redis = require("ioredis");

const cluster = new Redis.Cluster([
  {
    port: 6380,
    host: "127.0.0.1",
  },
  {
    port: 6381,
    host: "127.0.0.1",
  },
]);

cluster.set("foo", "bar");
cluster.get("foo", (err, res) => {
  // res === 'bar'
});

Cluster constructor accepts two arguments, where:

  1. The first argument is a list of nodes of the cluster you want to connect to. Just like Sentinel, the list does not need to enumerate all your cluster nodes, but a few so that if one is unreachable the client will try the next one, and the client will discover other nodes automatically when at least one node is connected.
  2. The second argument is the options, where:

    • clusterRetryStrategy: When none of the startup nodes are reachable, clusterRetryStrategy will be invoked. When a number is returned, ioredis will try to reconnect to the startup nodes from scratch after the specified delay (in ms). Otherwise, an error of "None of startup nodes is available" will be returned. The default value of this option is:

      function (times) {
        const delay = Math.min(100 + times * 2, 2000);
        return delay;
      }

      It's possible to modify the startupNodes property in order to switch to another set of nodes here:

      function (times) {
        this.startupNodes = [{ port: 6790, host: '127.0.0.1' }];
        return Math.min(100 + times * 2, 2000);
      }
    • dnsLookup: Alternative DNS lookup function (dns.lookup() is used by default). It may be useful to override this in special cases, such as when AWS ElastiCache used with TLS enabled.

    • enableOfflineQueue: Similar to the enableOfflineQueue option of Redis class.
    • enableReadyCheck: When enabled, "ready" event will only be emitted when CLUSTER INFO command reporting the cluster is ready for handling commands. Otherwise, it will be emitted immediately after "connect" is emitted.
    • scaleReads: Config where to send the read queries. See below for more details.
    • maxRedirections: When a cluster related error (e.g. MOVED, ASK and CLUSTERDOWN etc.) is received, the client will redirect the command to another node. This option limits the max redirections allowed when sending a command. The default value is 16.
    • retryDelayOnFailover: If the target node is disconnected when sending a command, ioredis will retry after the specified delay. The default value is 100. You should make sure retryDelayOnFailover * maxRedirections > cluster-node-timeout to insure that no command will fail during a failover.
    • retryDelayOnClusterDown: When a cluster is down, all commands will be rejected with the error of CLUSTERDOWN. If this option is a number (by default, it is 100), the client will resend the commands after the specified time (in ms).
    • retryDelayOnTryAgain: If this option is a number (by default, it is 100), the client will resend the commands rejected with TRYAGAIN error after the specified time (in ms).
    • retryDelayOnMoved: By default, this value is 0 (in ms), which means when a MOVED error is received, the client will resend the command instantly to the node returned together with the MOVED error. However, sometimes it takes time for a cluster to become state stabilized after a failover, so adding a delay before resending can prevent a ping pong effect.
    • redisOptions: Default options passed to the constructor of Redis when connecting to a node.
    • slotsRefreshTimeout: Milliseconds before a timeout occurs while refreshing slots from the cluster (default 1000).
    • slotsRefreshInterval: Milliseconds between every automatic slots refresh (by default, it is disabled).

Read-Write Splitting

A typical redis cluster contains three or more masters and several slaves for each master. It's possible to scale out redis cluster by sending read queries to slaves and write queries to masters by setting the scaleReads option.

scaleReads is "master" by default, which means ioredis will never send any queries to slaves. There are other three available options:

  1. "all": Send write queries to masters and read queries to masters or slaves randomly.
  2. "slave": Send write queries to masters and read queries to slaves.
  3. a custom function(nodes, command): node: Will choose the custom function to select to which node to send read queries (write queries keep being sent to master). The first node in nodes is always the master serving the relevant slots. If the function returns an array of nodes, a random node of that list will be selected.

For example:

const cluster = new Redis.Cluster(
  [
    /* nodes */
  ],
  {
    scaleReads: "slave",
  }
);
cluster.set("foo", "bar"); // This query will be sent to one of the masters.
cluster.get("foo", (err, res) => {
  // This query will be sent to one of the slaves.
});

NB In the code snippet above, the res may not be equal to "bar" because of the lag of replication between the master and slaves.

Running Commands to Multiple Nodes

Every command will be sent to exactly one node. For commands containing keys, (e.g. GET, SET and HGETALL), ioredis sends them to the node that serving the keys, and for other commands not containing keys, (e.g. INFO, KEYS and FLUSHDB), ioredis sends them to a random node.

Sometimes you may want to send a command to multiple nodes (masters or slaves) of the cluster, you can get the nodes via Cluster#nodes() method.

Cluster#nodes() accepts a parameter role, which can be "master", "slave" and "all" (default), and returns an array of Redis instance. For example:

// Send `FLUSHDB` command to all slaves:
const slaves = cluster.nodes("slave");
Promise.all(slaves.map((node) => node.flushdb()));

// Get keys of all the masters:
const masters = cluster.nodes("master");
Promise.all(
  masters
    .map((node) => node.keys())
    .then((keys) => {
      // keys: [['key1', 'key2'], ['key3', 'key4']]
    })
);

NAT Mapping

Sometimes the cluster is hosted within a internal network that can only be accessed via a NAT (Network Address Translation) instance. See Accessing ElastiCache from outside AWS as an example.

You can specify nat mapping rules via natMap option:

const cluster = new Redis.Cluster(
  [
    {
      host: "203.0.113.73",
      port: 30001,
    },
  ],
  {
    natMap: {
      "10.0.1.230:30001": { host: "203.0.113.73", port: 30001 },
      "10.0.1.231:30001": { host: "203.0.113.73", port: 30002 },
      "10.0.1.232:30001": { host: "203.0.113.73", port: 30003 },
    },
  }
);

This option is also useful when the cluster is running inside a Docker container.

Transaction and Pipeline in Cluster Mode

Almost all features that are supported by Redis are also supported by Redis.Cluster, e.g. custom commands, transaction and pipeline. However there are some differences when using transaction and pipeline in Cluster mode:

  1. All keys in a pipeline should belong to slots served by the same node, since ioredis sends all commands in a pipeline to the same node.
  2. You can't use multi without pipeline (aka cluster.multi({ pipeline: false })). This is because when you call cluster.multi({ pipeline: false }), ioredis doesn't know which node the multi command should be sent to.

When any commands in a pipeline receives a MOVED or ASK error, ioredis will resend the whole pipeline to the specified node automatically if all of the following conditions are satisfied:

  1. All errors received in the pipeline are the same. For example, we won't resend the pipeline if we got two MOVED errors pointing to different nodes.
  2. All commands executed successfully are readonly commands. This makes sure that resending the pipeline won't have side effects.

Pub/Sub

Pub/Sub in cluster mode works exactly as the same as in standalone mode. Internally, when a node of the cluster receives a message, it will broadcast the message to the other nodes. ioredis makes sure that each message will only be received once by strictly subscribing one node at the same time.

const nodes = [
  /* nodes */
];
const pub = new Redis.Cluster(nodes);
const sub = new Redis.Cluster(nodes);
sub.on("message", (channel, message) => {
  console.log(channel, message);
});

sub.subscribe("news", () => {
  pub.publish("news", "highlights");
});

Events

Event Description
connect emits when a connection is established to the Redis server.
ready emits when CLUSTER INFO reporting the cluster is able to receive commands (if enableReadyCheck is true) or immediately after connect event (if enableReadyCheck is false).
error emits when an error occurs while connecting with a property of lastNodeError representing the last node error received. This event is emitted silently (only emitting if there's at least one listener).
close emits when an established Redis server connection has closed.
reconnecting emits after close when a reconnection will be made. The argument of the event is the time (in ms) before reconnecting.
end emits after close when no more reconnections will be made.
+node emits when a new node is connected.
-node emits when a node is disconnected.
node error emits when an error occurs when connecting to a node. The second argument indicates the address of the node.

Password

Setting the password option to access password-protected clusters:

const Redis = require("ioredis");
const cluster = new Redis.Cluster(nodes, {
  redisOptions: {
    password: "your-cluster-password",
  },
});

If some of nodes in the cluster using a different password, you should specify them in the first parameter:

const Redis = require("ioredis");
const cluster = new Redis.Cluster(
  [
    // Use password "password-for-30001" for 30001
    { port: 30001, password: "password-for-30001" },
    // Don't use password when accessing 30002
    { port: 30002, password: null },
    // Other nodes will use "fallback-password"
  ],
  {
    redisOptions: {
      password: "fallback-password",
    },
  }
);

Special Note: Aws Elasticache Clusters with TLS

AWS ElastiCache for Redis (Clustered Mode) supports TLS encryption. If you use this, you may encounter errors with invalid certificates. To resolve this issue, construct the Cluster with the dnsLookup option as follows:

const cluster = new Redis.Cluster(
  [
    {
      host: "clustercfg.myCluster.abcdefg.xyz.cache.amazonaws.com",
      port: 6379,
    },
  ],
  {
    dnsLookup: (address, callback) => callback(null, address),
    redisOptions: {
      tls: {},
    },
  }
);

Autopipelining

In standard mode, when you issue multiple commands, ioredis sends them to the server one by one. As described in Redis pipeline documentation, this is a suboptimal use of the network link, especially when such link is not very performant.

The TCP and network overhead negatively affects performance. Commands are stuck in the send queue until the previous ones are correctly delivered to the server. This is a problem known as Head-Of-Line blocking (HOL).

ioredis supports a feature called “auto pipelining”. It can be enabled by setting the option enableAutoPipelining to true. No other code change is necessary.

In auto pipelining mode, all commands issued during an event loop are enqueued in a pipeline automatically managed by ioredis. At the end of the iteration, the pipeline is executed and thus all commands are sent to the server at the same time.

This feature can dramatically improve throughput and avoids HOL blocking. In our benchmarks, the improvement was between 35% and 50%.

While an automatic pipeline is executing, all new commands will be enqueued in a new pipeline which will be executed as soon as the previous finishes.

When using Redis Cluster, one pipeline per node is created. Commands are assigned to pipelines according to which node serves the slot.

A pipeline will thus contain commands using different slots but that ultimately are assigned to the same node.

Note that the same slot limitation within a single command still holds, as it is a Redis limitation.

Example of Automatic Pipeline Enqueuing

This sample code uses ioredis with automatic pipeline enabled.

const Redis = require("./built");
const http = require("http");

const db = new Redis({ enableAutoPipelining: true });

const server = http.createServer((request, response) => {
  const key = new URL(request.url, "https://localhost:3000/").searchParams.get(
    "key"
  );

  db.get(key, (err, value) => {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.end(value);
  });
});

server.listen(3000);

When Node receives requests, it schedules them to be processed in one or more iterations of the events loop.

All commands issued by requests processing during one iteration of the loop will be wrapped in a pipeline automatically created by ioredis.

In the example above, the pipeline will have the following contents:

GET key1
GET key2
GET key3
...
GET keyN

When all events in the current loop have been processed, the pipeline is executed and thus all commands are sent to the server at the same time.

While waiting for pipeline response from Redis, Node will still be able to process requests. All commands issued by request handler will be enqueued in a new automatically created pipeline. This pipeline will not be sent to the server yet.

As soon as a previous automatic pipeline has received all responses from the server, the new pipeline is immediately sent without waiting for the events loop iteration to finish.

This approach increases the utilization of the network link, reduces the TCP overhead and idle times and therefore improves throughput.

Benchmarks

Here's some of the results of our tests for a single node.

Each iteration of the test runs 1000 random commands on the server.

| | Samples | Result | Tolerance | | ------------------------- | ------- | ------------- | --------- | | default | 1000 | 174.62 op/sec | ± 0.45 % | | enableAutoPipelining=true | 1500 | 233.33 op/sec | ± 0.88 % |

And here's the same test for a cluster of 3 masters and 3 replicas:

| | Samples | Result | Tolerance | | ------------------------- | ------- | ------------- | --------- | | default | 1000 | 164.05 op/sec | ± 0.42 % | | enableAutoPipelining=true | 3000 | 235.31 op/sec | ± 0.94 % |

Error Handling

All the errors returned by the Redis server are instances of ReplyError, which can be accessed via Redis:

const Redis = require("ioredis");
const redis = new Redis();
// This command causes a reply error since the SET command requires two arguments.
redis.set("foo", (err) => {
  err instanceof Redis.ReplyError;
});

This is the error stack of the ReplyError:

ReplyError: ERR wrong number of arguments for 'set' command
    at ReplyParser._parseResult (/app/node_modules/ioredis/lib/parsers/javascript.js:60:14)
    at ReplyParser.execute (/app/node_modules/ioredis/lib/parsers/javascript.js:178:20)
    at Socket.<anonymous> (/app/node_modules/ioredis/lib/redis/event_handler.js:99:22)
    at Socket.emit (events.js:97:17)
    at readableAddChunk (_stream_readable.js:143:16)
    at Socket.Readable.push (_stream_readable.js:106:10)
    at TCP.onread (net.js:509:20)

By default, the error stack doesn't make any sense because the whole stack happens in the ioredis module itself, not in your code. So it's not easy to find out where the error happens in your code. ioredis provides an option showFriendlyErrorStack to solve the problem. When you enable showFriendlyErrorStack, ioredis will optimize the error stack for you:

const Redis = require("ioredis");
const redis = new Redis({ showFriendlyErrorStack: true });
redis.set("foo");

And the output will be:

ReplyError: ERR wrong number of arguments for 'set' command
    at Object.<anonymous> (/app/index.js:3:7)
    at Module._compile (module.js:446:26)
    at Object.Module._extensions..js (module.js:464:10)
    at Module.load (module.js:341:32)
    at Function.Module._load (module.js:296:12)
    at Function.Module.runMain (module.js:487:10)
    at startup (node.js:111:16)
    at node.js:799:3

This time the stack tells you that the error happens on the third line in your code. Pretty sweet! However, it would decrease the performance significantly to optimize the error stack. So by default, this option is disabled and can only be used for debugging purposes. You shouldn't use this feature in a production environment.

Running tests

Start a Redis server on 127.0.0.1:6379, and then:

npm test

FLUSH ALL will be invoked after each test, so make sure there's no valuable data in it before running tests.

If your testing environment does not let you spin up a Redis server ioredis-mock is a drop-in replacement you can use in your tests. It aims to behave identically to ioredis connected to a Redis server so that your integration tests is easier to write and of better quality.

Debug

You can set the DEBUG env to ioredis:* to print debug info:

$ DEBUG=ioredis:* node app.js

Join in!

I'm happy to receive bug reports, fixes, documentation enhancements, and any other improvements.

And since I'm not a native English speaker, if you find any grammar mistakes in the documentation, please also let me know. :)

Contributors

This project exists thanks to all the people who contribute:

License

MIT

FOSSA Status

changelog

5.4.2 (2024-12-20)

Bug Fixes

  • Connection instability when using socketTimeout parameter (#1937) (ca5e940), closes #1919

5.4.1 (2024-04-17)

Bug Fixes

5.4.0 (2024-04-16)

Bug Fixes

  • when refreshSlotsCache is callback concurrently, call the callback only when the refresh process is done (#1881) (804ee07)

Features

5.3.2 (2023-04-15)

Bug Fixes

5.3.1 (2023-02-12)

Bug Fixes

  • Fix commands not resend on reconnect in edge cases (#1720) (fe52ff1), closes #1718
  • Fix db parameter not working with auto pipelining (#1721) (d9b1bf1)

5.3.0 (2023-01-25)

Bug Fixes

Features

5.2.6 (2023-01-25)

Bug Fixes

  • remove extraneous TCP/IPC properties from RedisOptions TS type (#1707) (9af7b1c)

5.2.5 (2023-01-14)

Bug Fixes

  • Named export to support ESM imports in Typescript (#1695) (cdded57)

    With this change, users would be able to import Redis with import { Redis} from 'ioredis'. This makes it possible to import Redis in an ESM project. The original way (import Redis from 'ioredis') will still be supported but will be deprecated in the next major version.

5.2.4 (2022-11-02)

Bug Fixes

  • passing in family parameter in URL in node 18 (#1673) (6f1ab9f)

5.2.3 (2022-08-23)

Bug Fixes

5.2.2 (2022-07-23)

Bug Fixes

  • srandmember with count argument should return array of strings (#1620) (5f813f3)

5.2.1 (2022-07-16)

Bug Fixes

  • always allow selecting a new node for cluster mode subscriptions when the current one fails (#1589) (1c8cb85)

5.2.0 (2022-07-11)

Features

5.1.0 (2022-06-25)

Features

  • add command typings for Redis 7.0.2. Also fix a typing issue for hgetallBuffer. (#1611) (fa77c07)

5.0.6 (2022-05-31)

Bug Fixes

5.0.5 (2022-05-17)

Bug Fixes

  • improve typing for redis.multi (#1580) (f9f875b)
  • send correct command during auto-pipelining of .call() operations (#1579) (e41c3dc)

5.0.4 (2022-04-09)

Bug Fixes

  • Expose ChainableCommander and other types (#1560) (df04dd8)

5.0.3 (2022-03-31)

Bug Fixes

  • add named exports to keep compatible with @types/ioredis (#1552) (a89a900)
  • Fix failover detector with sentinel and tls streams (ac00a00)
  • handle NOPERM error for monitor (93b873d), closes #1498
  • Hook up the keepAlive after a successful connect (14f03a4), closes #1339

5.0.2 (2022-03-30)

Bug Fixes

  • allow option maxRetriesPerRequest to be null (#1553) (d62a808), closes #1550
  • support TypeScript interface as parameters of hmset and mset (#1545) (3444791), closes #1536

5.0.1 (2022-03-26)

Bug Fixes

  • improve typing compatibility with @types/ioredis (#1542) (3bf300a)

5.0.0 (2022-03-26)

In the update of v5, we've made ioredis even more stable and developer-friendly while minimizing the number of breaking changes, so you can spend more time enjoying your life 😄.

Please refer to the guideline to upgrade your projects: 🚀 Upgrading from v4 to v5.

Bug Fixes

  • add @ioredis/interface-generator to dev deps (aa3b3e9)
  • add missing declaration for callBuffer (08c9072)
  • add the missing typing for Redis#call() (747dd30)
  • better support for CJS importing (687d3eb)
  • disable slotsRefreshInterval by default (370fa62)
  • Fix the NOSCRIPT behavior when using pipelines (bc1b168)
  • improve typing for auto pipelining (4e8c567)
  • improve typing for pipeline (d18f3fe)
  • keyPrefix should work with Buffer (6942cec), closes #1486
  • make fields private when possible (d5c2f20)
  • parameter declaration of Redis#duplicate (a29d9c4)
  • pipeline fails when cluster is not ready (af60bb0), closes #1460
  • remove dropBufferSupport option (04e68ac)
  • remove unused Command#isCustomCommand (46ade6b)
  • rename interfaces by dropping prefix I (d1d9dba)
  • Reset loaded script hashes to force a reload of scripts after reconnect of redis (60c2af9)
  • support passing keyPrefix via redisOptions (6b0dc1e)

Features

  • add @since to method comments (13eff8e)
  • add declarations for methods (1e10c95)
  • add tests for cluster (1eba58b)
  • always parse username passed via URI (c6f41f6)
  • drop support of Node.js 10 (f9a5071)
  • drop support of third-party Promise libraries (2001ec6)
  • expose official declarations (7a436b1)
  • improve typings for cluster (06782e6)
  • improve typings for pipeline (334242b)
  • improve typings for smismember (487c3a0)
  • improve typings for transformers (94c1e24)
  • improve typings for xread (96cc335)
  • Pipeline-based script loading (8df6ee2)
  • prepare v5 stable release (#1538) (fe32ce7)
  • Refactor code with modern settings (a8ffa80)
  • skip ready check on NOPERM error (b530a0b), closes #1293
  • support commands added in Redis v7 (53ca412)
  • support defining custom commands via constructor options (f293b97)
  • support Redis Functions introduced in Redis 7.0 (32eb381)

BREAKING CHANGES

  • slotsRefreshInterval is disabled by default, previously, the default value was 5000.
  • allowUsernameInURI is removed and ioredis will always use the username passed via URI. Previously, the username part in new Redis("redis://username:authpassword@127.0.0.1:6380/4") was ignored unless allowUsernameInURI is specified: new Redis("redis://username:authpassword@127.0.0.1:6380/4?allowUsernameInURI=true"). Now, if you don't want to send username to Redis, just leave the username part empty: new Redis("redis://:authpassword@127.0.0.1:6380/4")
  • Redis#serverInfo is removed. This field is never documented so you very likely have never used it.
  • Support for third-party Promise libraries is dropped. Related methods (exports.Promise = require('bluebird')) are kept but they don't take any effects. The native Promise will always be used.
  • We now require Node.js v12 or newer.
  • Redis can't be called as a function anymore as it's now a class. Please change Redis() to new Redis(). Note that Redis() was already deprecated in the previous version.

5.0.0-beta.4 (2022-03-19)

Bug Fixes

  • add missing declaration for callBuffer (08c9072)
  • keyPrefix should work with Buffer (6942cec), closes #1486

5.0.0-beta.3 (2022-03-19)

Bug Fixes

  • pipeline fails when cluster is not ready (af60bb0), closes #1460

5.0.0-beta.2 (2022-03-16)

Features

  • improve typings for smismember (487c3a0)
  • improve typings for xread (96cc335)

5.0.0-beta.1 (2022-03-14)

Bug Fixes

  • add @ioredis/interface-generator to dev deps (aa3b3e9)
  • add the missing typing for Redis#call() (747dd30)
  • better support for CJS importing (687d3eb)
  • disable slotsRefreshInterval by default (370fa62)
  • Fix the NOSCRIPT behavior when using pipelines (bc1b168)
  • improve typing for auto pipelining (4e8c567)
  • improve typing for pipeline (d18f3fe)
  • make fields private when possible (d5c2f20)
  • parameter declaration of Redis#duplicate (a29d9c4)
  • remove dropBufferSupport option (04e68ac)
  • remove unused Command#isCustomCommand (46ade6b)
  • rename interfaces by dropping prefix I (d1d9dba)
  • Reset loaded script hashes to force a reload of scripts after reconnect of redis (60c2af9)
  • support passing keyPrefix via redisOptions (6b0dc1e)

Features

  • add @since to method comments (13eff8e)
  • add declarations for methods (1e10c95)
  • add tests for cluster (1eba58b)
  • always parse username passed via URI (c6f41f6)
  • drop support of Node.js 10 (f9a5071)
  • drop support of third-party Promise libraries (2001ec6)
  • expose official declarations (7a436b1)
  • improve typings for cluster (06782e6)
  • improve typings for pipeline (334242b)
  • improve typings for transformers (94c1e24)
  • Pipeline-based script loading (8df6ee2)
  • Refactor code with modern settings (a8ffa80)
  • skip ready check on NOPERM error (b530a0b), closes #1293
  • support commands added in Redis v7 (53ca412)
  • support defining custom commands via constructor options (f293b97)
  • support Redis Functions introduced in Redis 7.0 (32eb381)

BREAKING CHANGES

  • slotsRefreshInterval is disabled by default, previously, the default value was 5000.
  • allowUsernameInURI is removed and ioredis will always use the username passed via URI. Previously, the username part in new Redis("redis://username:authpassword@127.0.0.1:6380/4") was ignored unless allowUsernameInURI is specified: new Redis("redis://username:authpassword@127.0.0.1:6380/4?allowUsernameInURI=true"). Now, if you don't want to send username to Redis, just leave the username part empty: new Redis("redis://:authpassword@127.0.0.1:6380/4")
  • Redis#serverInfo is removed. This field is never documented so you very likely have never used it.
  • Support for third-party Promise libraries is dropped. Related methods (exports.Promise = require('bluebird')) are kept but they don't take any effects. The native Promise will always be used.
  • We now require Node.js v12 or newer.
  • Redis can't be called as a function anymore as it's now a class. Please change Redis() to new Redis(). Note that Redis() was already deprecated in the previous version.

4.28.5 (2022-02-06)

Bug Fixes

  • Reset loaded script hashes to force a reload of scripts after reconnect of redis (#1497) (f357a31)

4.28.4 (2022-02-02)

Bug Fixes

4.28.3 (2022-01-11)

Bug Fixes

  • fix exceptions on messages of client side cache (#1479) (02adca4)

4.28.2 (2021-12-01)

Bug Fixes

4.28.1 (2021-11-23)

Bug Fixes

  • handle possible unhandled promise rejection with autopipelining+cluster (#1467) (6ad285a), closes #1466

4.28.0 (2021-10-13)

Features

  • tls: add TLS profiles for easier configuration (#1441) (4680211)

4.27.11 (2021-10-11)

Bug Fixes

  • make export interface compatible with jest (#1445) (2728dbe)

4.27.10 (2021-10-04)

Bug Fixes

4.27.9 (2021-08-30)

Bug Fixes

  • Fix undefined property warning in executeAutoPipeline (#1425) (f898672)
  • improve proto checking for hgetall [skip ci] (#1418) (cba83cb)

4.27.8 (2021-08-18)

Bug Fixes

4.27.7 (2021-08-01)

Bug Fixes

4.27.6 (2021-06-13)

Bug Fixes

4.27.5 (2021-06-05)

Bug Fixes

  • SENTINEL: actively failover detection under an option (#1363) (f02e383)

4.27.4 (2021-06-04)

Performance Improvements

4.27.3 (2021-05-22)

Bug Fixes

4.27.2 (2021-05-04)

Bug Fixes

  • cluster: avoid ClusterAllFailedError in certain cases (aa9c5b1), closes #1330

4.27.1 (2021-04-24)

Bug Fixes

  • clears commandTimeout timer as each respective command gets fulfilled (#1336) (d65f8b2)

4.27.0 (2021-04-24)

Features

  • sentinel: detect failover from +switch-master messages (#1328) (a464151)

4.26.0 (2021-04-08)

Bug Fixes

  • cluster: subscriber connection leaks (81b9be0), closes #1325

Features

  • cluster: apply provided connection name to internal connections (2e388db)

4.25.0 (2021-04-02)

Features

4.24.6 (2021-03-31)

Bug Fixes

  • force disconnect after a timeout if socket is still half-open (#1318) (6cacd17)

4.24.5 (2021-03-27)

Bug Fixes

4.24.4 (2021-03-24)

Bug Fixes

  • minor compatibility issues caused by TypeScript upgrade (#1309) (c96139a), closes #1308

4.24.3 (2021-03-21)

Bug Fixes

  • support parallel script execution in pipelines (#1304) (c917719)

4.24.2 (2021-03-14)

Bug Fixes

4.24.1 (2021-03-14)

Bug Fixes

  • cluster: reconnect when failing to refresh slots cache for all nodes (8524eea)

4.24.0 (2021-03-14)

Features

  • cluster: support retrying MOVED with a delay (#1254) (8599981)

4.23.1 (2021-03-14)

Bug Fixes

4.23.0 (2021-02-25)

Features

4.22.0 (2021-02-06)

Features

4.21.0 (2021-02-06)

Features

4.20.0 (2021-02-05)

Features

4.19.5 (2021-01-14)

Bug Fixes

4.19.4 (2020-12-13)

Bug Fixes

4.19.3 (2020-12-13)

Bug Fixes

  • auth command should be not allowed in auto pipeline. (#1242) (bafdd4b)

4.19.2 (2020-10-31)

Bug Fixes

  • Fix autopipeline and downgrade p-map to support Node 6. [#1216] (1bc8ca0)

4.19.1 (2020-10-28)

Bug Fixes

  • Make sure script caches interval is cleared. [#1215] (d94f97d)

4.19.0 (2020-10-23)

Bug Fixes

  • Ensure delayed callbacks are always invoked. (d6e78c3)

Features

  • Add autopipeline for commands and allow multi slot pipelines. (aba3c74), closes #536

4.18.0 (2020-07-25)

Features

  • supports commands in Redis 6.0.6 (c016265)

4.17.3 (2020-05-30)

Bug Fixes

  • race conditions in Redis#disconnect() can cancel reconnection unexpectedly (6fad73b), closes #1138 #1007

4.17.2 (2020-05-30)

Bug Fixes

  • _readyCheck INFO parser's handling of colon characters (#1127) (38a09e1)

4.17.1 (2020-05-16)

Bug Fixes

  • revert parsing username via URI due to potential breaking changes (#1134) (225ef45)

4.17.0 (2020-05-16)

Features

4.16.3 (2020-04-21)

Bug Fixes

  • scripts may not be loaded correctly in pipeline (#1107) (072d460)

4.16.2 (2020-04-11)

Bug Fixes

  • dismiss security alerts for dev dependencies [skip release] (758b3f2)
  • handle connection after connect event was emitted (#1095) (16a0610), closes #977

4.16.1 (2020-03-28)

Bug Fixes

4.16.0 (2020-02-19)

Features

  • ability force custom scripts to be readOnly and execute on slaves (#1057) (a24c3ab)

4.15.1 (2019-12-25)

Bug Fixes

  • ignore empty hosts returned by CLUSTER SLOTS (#1025) (d79a8ef)
  • prevent exception when send custom command (04cad7f)

4.15.0 (2019-11-29)

Features

  • support multiple fields for hset (51b1478)

4.14.4 (2019-11-22)

Bug Fixes

  • improved performance of Pipeline.exec (#991) (86470a8)

4.14.3 (2019-11-07)

Bug Fixes

  • update funding information (c83cb05)

4.14.2 (2019-10-23)

Bug Fixes

  • security deps updates [skip ci] (a7095d7)

4.14.1 (2019-08-27)

Bug Fixes

4.14.0 (2019-07-31)

Features

4.13.1 (2019-07-22)

Bug Fixes

  • keep sentinels of options immutable (bacb7e1), closes #936

4.13.0 (2019-07-19)

Bug Fixes

  • cluster: suppress errors emitted from internal clients (9a113ca), closes #896 #899

Features

4.12.2 (2019-07-16)

Bug Fixes

  • cluster: prefer master when there're two same node for a slot (8fb9f97)
  • cluster: remove node immediately when slots are redistributed (ecc13ad), closes #930

4.12.1 (2019-07-15)

Bug Fixes

  • handle connecting immediately after "end" event (#929) (7bcd8a8), closes #928

4.12.0 (2019-07-14)

Features

4.11.2 (2019-07-13)

Bug Fixes

  • ETIMEDOUT error with Bluebird when connecting. (#925) (4bce38b), closes #918

4.11.1 (2019-06-26)

Bug Fixes

4.11.0 (2019-06-25)

Features

4.10.4 (2019-06-11)

Bug Fixes

  • cluster: passing frozen natMap option causes crash (3bc6165), closes #887

4.10.3 (2019-06-08)

Bug Fixes

  • cluster: reorder defaults arguments to prioritize user options (#889) (8da8d78)

4.10.2 (2019-06-08)

Bug Fixes

  • pipeline with transactions causes unhandled warnings (#884) (bbfd2fc), closes #883

4.10.1 (2019-06-08)

Bug Fixes

  • upgrade deps to resolve security vulnerabilities warnings (#885) (98c27cf)

4.10.0 (2019-05-23)

Features

4.9.5 (2019-05-15)

Bug Fixes

4.9.4 (2019-05-13)

Bug Fixes

4.9.3 (2019-05-07)

Bug Fixes

  • more meaningful errors when using pipeline after exec(). (#858) (0c3ef01)

4.9.2 (2019-05-03)

Bug Fixes

4.9.1 (2019-03-22)

Bug Fixes

4.9.0 (2019-03-18)

Features

  • sentinel: support Sentinel instances with authentication. (#817) (2437eae)

4.8.0 (2019-03-12)

Features

4.7.0 (2019-03-12)

Features

  • add updateSentinels option to control new sentinel values being added to the original list (#814) (50a9db7), closes #798

4.6.3 (2019-02-03)

Bug Fixes

  • add second arg to "node error" to know which node failed (#793) (6049f6c), closes #774

4.6.2 (2019-02-02)

Bug Fixes

  • subscriber initialization when using Cluster (#792) (32c48ef), closes #791

4.6.1 (2019-01-29)

Bug Fixes

  • Cluster: ignore connection errors for subscriber. (#790) (f368c8a), closes #768

4.6.0 (2019-01-21)

Features

  • add maxLoadingRetryTime option when redis server not ready (#784) (0e7713f)

4.5.1 (2019-01-13)

Performance Improvements

  • add checking and loading scripts uniqueness in pipeline (#781) (66075ba)

4.5.0 (2019-01-07)

Features

  • allow TLS when using Sentinel (ebef8f5)

4.4.0 (2019-01-04)

Features

  • support setting connectTimeout in Electron (#770) (2d591b7)

4.3.1 (2018-12-16)

Bug Fixes

  • cluster: handle connection errors by reconnection (#762) (21138af), closes #753

4.3.0 (2018-12-09)

Features

4.2.3 (2018-11-24)

Bug Fixes

4.2.2 (2018-10-20)

4.2.1 (2018-10-19)

4.2.0 (2018-10-17)

Features

4.1.0 (2018-10-15)

Bug Fixes

  • cluster: quit() ignores errors caused by disconnected connection (#720) (fb3eb76)
  • cluster: robust solution for pub/sub in cluster (#697) (13a5bc4), closes #696
  • cluster: stop subscriber when disconnecting (fb27b66)

Features

  • cluster: re-select subscriber when the currenct one is failed (c091f2e)

Performance Improvements

  • remove lodash deps for smaller memory footprint (80f4a45)
  • cluster: make disconnecting from cluster faster (#721) (ce46d6b)

4.0.2 (2018-10-09)

Bug Fixes

  • cluster: subscription regards password setting (47e2ab5), closes #718

Performance Improvements

  • reduce package bundle size (eb68e9a)

4.0.1 (2018-10-08)

Bug Fixes

  • cluster: robust solution for pub/sub in cluster (#697) (13a5bc4), closes #696

4.0.0 (2018-08-14)

This is a major release and contain breaking changes. Please read this changelog before upgrading.

Changes since 4.0.0-3:

Bug Fixes

  • port is ignored when path set to null (d40a99e), closes #668

Features

  • export Pipeline for inheritances enabling (#675) (ca58249)
  • export ScanStream at package level (#667) (5eb4198)

Changes since 3.x

Bug Fixes

  • Sentinel: unreachable errors when sentinals are healthy (7bf6fea)
  • resolve warning for Buffer() in Node.js 10 (6144c56)
  • don't add cluster.info to the failover queue before ready (491546d)
  • solves vulnerabilities dependencies (2950b79)
  • Cluster: issues when setting enableOfflineQueue to false (#649) (cfe4258)

Performance Improvements

  • upgrade redis-parser for better performance.

Features

  • use native Promise instead of Bluebird, and allow users to switch back. (da60b8b)
  • add maxRetriesPerRequest option to limit the retries attempts per command (1babc13)
  • Redis#connect() will be resolved when status is ready (#648) (f0c600b)
  • add debug details for connection pool (9ec16b6)
  • wait for ready state before resolving cluster.connect() (7517a73)

BREAKING CHANGES

  • Drop support for < node v6
  • Use native Promise instead of Bluebird. This change makes all the code that rely on the features provided by Bluebird not working anymore. For example, redis.get('foo').timeout(500) now should be failed since the native Promise doesn't support the timeout method. You can switch back to the Bluebird implementation by setting Redis.Promise:
const Redis = require('ioredis')
Redis.Promise = require('bluebird')

const redis = new Redis()

// Use bluebird
assert.equal(redis.get().constructor, require('bluebird'))

// You can change the Promise implementation at any time:
Redis.Promise = global.Promise
assert.equal(redis.get().constructor, global.Promise)
  • Redis#connect() will be resolved when status is ready instead of connect:
const redis = new Redis({ lazyConnect: true })
redis.connect().then(() => {
  assert(redis.status === 'ready')
})
  • Cluster#connect() will be resolved when the connection status become ready instead of connect.
  • The maxRetriesPerRequest is set to 20 instead of null (same behavior as ioredis v3) by default. So when a redis server is down, pending commands won't wait forever until the connection become alive, instead, they only wait about 10s (depends on the retryStrategy option)
  • The new keyword is required explicitly. Calling Redis as a function like Redis(/* options /)is deprecated and will not be supported in the next major version, usenew Redis(/ options */)` instead.

4.0.0-3 (2018-07-22)

Bug Fixes

  • Sentinel: unreachable errors when sentinals are healthy (7bf6fea)
  • resolve warning for Buffer() in Node.js 10 (6144c56)

4.0.0-2 (2018-07-07)

Upgrade redis-parser to v3. See release notes on redis-parser repo for details.

4.0.0-1 (2018-07-02)

Bug Fixes

  • remove unnecessary bluebird usage (2502b1b)

4.0.0-0 (2018-07-01)

Bug Fixes

  • Deprecated Redis() in favor of new Redis() (8e7c6f1)
  • don't add cluster.info to the failover queue before ready (491546d)
  • solves vulnerabilities dependencies (2950b79)
  • Cluster: issues when setting enableOfflineQueue to false (#649) (cfe4258)

Features

  • use native Promise instead of Bluebird, and allow users to switch back. (da60b8b)
  • add maxRetriesPerRequest option to limit the retries attempts per command (1babc13)
  • Redis#connect() will be resolved when status is ready (#648) (f0c600b)
  • add debug details for connection pool (9ec16b6)
  • wait for ready state before resolving cluster.connect() (7517a73)

BREAKING CHANGES

  • Drop support for < node v6
  • Use native Promise instead of Bluebird. This change makes all the code that rely on the features provided by Bluebird not working anymore. For example, redis.get('foo').timeout(500) now should be failed since the native Promise doesn't support the timeout method. You can switch back to the Bluebird implementation by setting Redis.Promise:
const Redis = require('ioredis')
Redis.Promise = require('bluebird')

const redis = new Redis()

// Use bluebird
assert.equal(redis.get().constructor, require('bluebird'))

// You can change the Promise implementation at any time:
Redis.Promise = global.Promise
assert.equal(redis.get().constructor, global.Promise)
  • Redis#connect() will be resolved when status is ready instead of connect:
const redis = new Redis({ lazyConnect: true })
redis.connect().then(() => {
  assert(redis.status === 'ready')
})
  • Cluster#connect() will be resolved when the connection status become ready instead of connect.
  • The maxRetriesPerRequest is set to 20 instead of null (same behavior as ioredis v3) by default. So when a redis server is down, pending commands won't wait forever until the connection become alive, instead, they only wait about 10s (depends on the retryStrategy option)
  • The new keyword is required explicitly. Calling Redis as a function like Redis(/* options */) is deprecated and will not be supported in the next major version, use new Redis(/* options */) instead.

3.2.2 (2017-11-30)

3.2.1 (2017-10-04)

Bug Fixes

  • Cluster: empty key name was sent to random nodes (e42f30f)

3.2.0 (2017-10-01)

Features

  • truncate large/long debug output arguments (#523) (cf18554)

3.1.4 (2017-08-13)

We mistakenly used Object.assign to replace lodash.assign in v3.1.3, which is not supported by the old Node.js version (0.10.x). This change was a BC change and shouldn't happen without changing the major version, so we added lodash.assign back.

3.1.3 (2017-08-13)

Bug Fixes

  • allow convertObjectToArray to handle objects with no prototype (#507) (8e17920)

3.1.2 (2017-07-26)

Bug Fixes

  • stop mutating the arguments when calling multi (#480) (a380030)

3.1.1 (2017-05-31)

Bug Fixes

  • show error name the error stack for Node.js 8 (a628aa7)

3.1.0 (2017-05-30)

Bug Fixes

  • non-owned properties cause empty args for mset & hmset (#469) (e7b6352)

Features

  • cluster: add option to control timeout on cluster slots refresh (#475) (493d095)

3.0.0 (2017-05-18)

Features

  • pipeline: add #length to get the command count (a6060cb), closes #461
  • sentinel: allow connection to IPv6-only sentinels (#463) (a389f3c)

3.0.0-2 (2017-05-03)

Bug Fixes

  • restore the default connectTimeout to 10000 (dc8256e)

3.0.0-1 (2017-04-16)

Features

  • add debug logs for resolved sentinel nodes (8f3d3f7)
  • report error on Sentinel connection refused (#445) (#446) (286a5bc)
  • set default port of sentinels to 26379. (#441) (539fe41)

BREAKING CHANGES

  • The default port of sentinels are now 26379 instead of 6379. This shouldn't break your app in most case since few setups has the sentinel server running on 6379, but if it's your case and the port isn't set explicitly, please go to update it.

3.0.0-0 (2017-01-26)

This is a performance-focused release. We finially switch to the new version of JavaScript parser and drop the support for hiredis (Thanks to the lovely community!). Also, we switch to denque to improve the queueing performance.

Let us know if there's any issue when using this pre-release.

Other Changes

  • increase the default reconnection interval (c5fefb7), closes #414

BREAKING CHANGES

  • Although the interface doesn't change after upgrading the js parser, there may be still some potential internal differences that may break the applications which rely on them. Also, force a major version bump emphasizes the dropping of the hiredis.

2.5.0 (2017-01-06)

Features

  • quit immediately when in reconnecting state (#410) (a6f04f2)

2.4.3 (2016-12-15)

Bug Fixes

  • wait all the commands in a pipeline before sending #411 (#413) (bfa879a)

2.4.2 (2016-12-04)

Bug Fixes

  • handle error when creating tls connection (904f433)

2.4.1 (2016-12-04)

Performance Improvements

  • by default call setNoDelay on the stream (#406) (990a221)

2.4.0 (2016-09-24)

Features

2.3.1 (2016-09-24)

Bug Fixes

  • prevent sentinel from getting duplicated nodes (0338677)

2.3.0 (2016-08-11)

Bug Fixes

  • reject with general error in Redis#connect (#354) (8f7a436)

Features

2.2.0 (2016-06-28)

Bug Fixes

  • cluster: ensure node exists before being redirected via an ASK (#341) (5d9d0d3)

Features

  • cluster: add Cluster#quit() to quit cluster gracefully. (#339) (68c4ccc), closes #315

2.1.0 (2016-06-22)

Bug Fixes

  • remove unnecessary unhandled error warnings (#322) (a1ff2f6)

Features

  • sentinel: update sentinels after getting master (e3f14b2)

Performance Improvements

  • cluster: improve the performance of calculating slots (#323) (3ab4e8a)

2.0.1 (2016-06-01)

Bug Fixes

  • fix transaction with dropBufferSupport:true(47a2d9a)

2.0.0 (2016-05-29)

Refer to Breaking Changes between V1 and V2 for all breaking changes.

Changes since 2.0.0-rc4:

Features

  • include source and database in monitor events (#308) (a0d5b25)

Performance Improvements

  • improve the performance of checking flags (#312) (236da27)

2.0.0-rc4 (2016-05-08)

Bug Fixes

  • reconnect when ready check failed(3561fab)
  • remove data handler when flushing command queue(b1c761c)
  • won't emit error again when password is wrong(dfdebfe)

Features

  • add dropBufferSupport option to improve the performance (#293)(1a8700c)
  • add support for Node.js v6 (#295)(a87f405)
  • emit authentication related errors with "error" event(9dc25b4)
  • print logs for unhandled error event(097fdbc)

BREAKING CHANGES

  • Authentication related errors are emited with "error" event, instead of "authError" event

2.0.0-rc3 (2016-05-02)

Bug Fixes

  • fix wrong host not causing error (25c300e), closes #287
  • reconnect when getting fatal error (#292) (1cf2ac1)

Features

  • deps: upgrade redis-commands package (df08250)

2.0.0-rc2 (2016-04-10)

Bug Fixes

Features

  • add stringNumbers option to return numbers as JavaScript strings (#282) (2a33fc7), closes #273

2.0.0-rc1 (2016-03-18)

Features

  • dependencies: upgrade all dependencies to the newest version (3fdafc8).

2.0.0-alpha3 (2016-03-13)

Bug Fixes

  • auth: emit authError when the server requiring a password (c5ca754)

Features

  • cluster: add enableReadyCheck option for cluster (b63cdc7)
  • cluster: redirect on TRYAGAIN error (b1a4b62)
  • cluster: support update startupNodes in clusterRetryStrategy (4a46766)
  • transaction: transform replies of transactions (e0b1883), closes #158

BREAKING CHANGES

  1. Reply transformers is supported inside transactions.
  2. Pipeline#execBuffer() is deprecated. Use Pipeline#exec() instead.

2.0.0-alpha2 (2016-02-29)

Bug Fixes

  • cluster: fix memory leaking in sendCommand method (410af51)

Features

  • cluster: add the option for a custom node selector in scaleReads (6795b1e)

2.0.0-alpha1 (2016-02-10)

Bug Fixes

  • cluster: avoid command.reject being overwritten twice (d0a0017)
  • cluster: fix not connecting to the unknown nodes (0dcb768)
  • cluster: set retryDelayOnFailover from 2000ms to 200ms (72fd804)

Features

  • cluster: support scaling reads to slaves (98bdec2), closes #170
  • redis: support readonly mode for cluster (0a4186e)

BREAKING CHANGES

  • cluster: Cluster#masterNodes and Cluster#nodes is removed. Use Cluster#nodes('masters') and Cluster#nodes('all') instead.
  • cluster: Cluster#to() is removed. Use Promise.all(Cluster#nodes().map(function (node) {})) instead.
  • cluster: Option readOnly is removed. Check out scaleReads option.

1.15.1 (2016-02-19)

  • select db on connect event to prevent subscribe errors (829bf26), closes #255

1.15.0 (2016-01-31)

Bug Fixes

  • "MOVED" err not crashing process when slot was not assigned (6974d4d)
  • remove extra typeof in .to cluster helper (a7b0bfe)

Features

  • revisit of .to(nodeGroup) command (ba12e47)

v1.14.0 - January 4, 2016

  • Support returning buffers for transactions (#223).

v1.13.2 - December 30, 2015

  • Add argument transformer for msetnx to support Map (#218).

v1.13.1 - December 20, 2015

  • Fix mset transformer not supporting keyPrefix (#217).

v1.13.0 - December 13, 2015

  • [Cluster] Select a random node when the target node is closed.
  • [Cluster] maxRedirections also works for CLUSTERDOWN.

v1.12.2 - December 6, 2015

  • [Cluster] Fix failover queue not being processed. Shahar Mor.

v1.12.1 - December 5, 2015

  • [Cluster] Add queue support for failover and CLUSTERDOWN handling. Shahar Mor.
  • Emits "error" when connection is down for scanStream (#199).

v1.11.1 - November 26, 2015

  • [Sentinel] Emits "error" when all sentinels are unreachable (#200).

v1.11.0 - November 19, 2015

  • Emits "select" event when the database changed.
  • [Cluster] Supports scanStream (#175).
  • Update debug module to 2.2.0
  • Update bluebird module to 2.9.34

v1.10.0 - October 24, 2015

  • [Cluster] Support redis schema url.
  • [Cluster] Support specifying password for each node.
  • Add an option for setting connection name. cgiovanacci.
  • Switch to the previous db before re-subscribing channels.
  • Listen to the "secureConnect" event when connect via TLS. Jeffrey Jen.
  • Improve parser performance.

v1.9.1 - October 2, 2015

  • Emits "authError" event when the password is wrong(#164).
  • Fixed wrong debug output when using sentinels. Colm Hally
  • Discard slave if flagged with s_down or o_down. mtlima

v1.9.0 - September 18, 2015

  • Support TLS.
  • Support reconnecting on the specified error.

v1.8.0 - September 9, 2015

  • Add keepAlive option(defaults to true).
  • Fix compatible issues of Buffer with Node.js 4.0.

v1.7.6 - September 1, 2015

  • Fix errors when sending command to a failed cluster(#56).

v1.7.5 - August 16, 2015

  • Fix for allNodes array containing nodes not serving the specified slot. henstock

v1.7.4 - August 13, 2015

v1.7.3 - August 3, 2015

v1.7.2 - July 30, 2015

v1.7.1 - July 26, 2015

  • Re-subscribe previous channels after reconnection(#110).

v1.7.0 - July 23, 2015

v1.6.1 - July 12, 2015

  • Fix Redis.Command not being exported correctly(#100).

v1.6.0 - July 11, 2015

  • Add a streaming interface to SCAN commands.
  • Support GEO commands.

v1.5.12 - July 7, 2015

  • Fix the order of received commands(#91).

v1.5.11 - July 7, 2015

  • Allow omitting callback in exec.

v1.5.10 - July 6, 2015

  • Add send_command method for compatibility(#90).

v1.5.9 - July 4, 2015

  • Fix connection error emitting before listening to error event(#80).

v1.5.8 - July 3, 2015

v1.5.7 - July 1, 2015

  • Fix subscriptions lost after reconnection(#85).

v1.5.6 - June 28, 2015

  • Silent error when redis server has cluster support disabled(#82).

v1.5.5 - June 25, 2015

  • Fix storing wrong redis host internally.

v1.5.4 - June 25, 2015

  • Fix masterNodes not being removed correctly.

v1.5.3 - June 24, 2015

  • Fix sometimes monitor leads command queue error.

v1.5.2 - June 24, 2015

  • Fix enableReadyCheck is always false in monitor mode(#77).

v1.5.1 - June 16, 2015

  • Fix getting NaN db index(#74).

v1.5.0 - June 13, 2015

  • Uses double ended queue instead of Array for better performance.
  • Resolves a bug with cluster where a subscribe is sent to a disconnected node(#63). Ari Aosved.
  • Adds ReadOnly mode for Cluster mode(#69). Nakul Ganesh.
  • Adds Redis.print(#71). Frank Murphy.

v1.4.0 - June 3, 2015

  • Continue monitoring after reconnection(#52).
  • Support pub/sub in Cluster mode(#54).
  • Auto-reconnect when none of startup nodes is ready(#56).

v1.3.6 - May 22, 2015

  • Support Node.js 0.10.16
  • Fix unfulfilled commands being sent to the wrong db(#42).

v1.3.5 - May 21, 2015

  • Fix possible memory leak warning of Cluster.
  • Stop reconnecting when disconnected manually.

v1.3.4 - May 21, 2015

  • Add missing Promise definition in node 0.10.x.

v1.3.3 - May 19, 2015

  • Fix possible memory leak warning.

v1.3.2 - May 18, 2015

  • The constructor of pipeline/multi accepts a batch of commands.

v1.3.1 - May 16, 2015

  • Improve the performance of sending commands(#35). @AVVS.

v1.3.0 - May 15, 2015

  • Support pipeline redirection in Cluster mode.

v1.2.7 - May 15, 2015

  • Redis#connect returns a promise.

v1.2.6 - May 13, 2015

  • Fix showFriendlyErrorStack not working in pipeline.

v1.2.5 - May 12, 2015

  • Fix errors when sending commands after connection being closed.

v1.2.4 - May 9, 2015

  • Try a random node when the target slot isn't served by the cluster.
  • Remove refreshAfterFails option.
  • Try random node when refresh slots.

v1.2.3 - May 9, 2015

  • Fix errors when numberOfKeys is 0.

v1.2.2 - May 8, 2015

  • Add retryDelayOnClusterDown option to handle CLUSTERDOWN error.
  • Fix multi commands sometimes doesn't return a promise.

v1.2.1 - May 7, 2015

  • Fix sendCommand sometimes doesn't return a promise.

v1.2.0 - May 4, 2015

  • Add autoResendUnfulfilledCommands option.

v1.1.4 - May 3, 2015

  • Support get built-in commands.

v1.1.3 - May 2, 2015

  • Fix buffer supporting in pipeline. @AVVS.

v1.1.2 - May 2, 2015

  • Fix error of sending command to wrong node when slot is 0.

v1.1.1 - May 2, 2015

  • Support Transaction and pipelining in cluster mode.

v1.1.0 - May 1, 2015

  • Support cluster auto reconnection.
  • Add maxRedirections option to Cluster.
  • Remove roleRetryDelay option in favor of sentinelRetryStrategy.
  • Improve compatibility with node_redis.
  • More stable sentinel connection.

v1.0.13 - April 27, 2015

  • Support SORT, ZUNIONSTORE and ZINTERSTORE in Cluster.

v1.0.12 - April 27, 2015

  • Support for defining custom commands in Cluster.
  • Use native array instead of fastqueue for better performance.

v1.0.11 - April 26, 2015

  • Add showFriendlyErrorStack option for outputing friendly error stack.

v1.0.10 - April 25, 2015

  • Improve performance for calculating slots.

v1.0.9 - April 25, 2015

  • Support single node commands in cluster mode.

v1.0.8 - April 25, 2015

  • Add promise supports in Cluster.

v1.0.7 - April 25, 2015

  • Add autoResubscribe option to prevent auto re-subscribe.
  • Add Redis#end for compatibility.
  • Add Redis.createClient(was Redis#createClient).

v1.0.6 - April 24, 2015

  • Support setting connect timeout.