Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
I

ioredis

> 数据库
Open source

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

15.3K stars0 likes1 views
WebsiteGitHub

About

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

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

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

ioredis is a stable project and maintenance is done on a best-effort basis for relevant issues (contributions to ioredis will still be evaluated, reviewed, and merged when they benefit the project). For new projects, node-redis is the recommended client library. node-redis is the open-source (MIT license) Redis JavaScript client library redesigned from the ground up and actively maintained. node-redis supports new (hash-field expiration) and future commands and the capabilities available in Redis Stack and Redis 8 (search, JSON, time-series, probabilistic data structures).

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:

Versions

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

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

🚀 Upgrading from v5 to v6

🚀 Upgrading from v4 to v5

Links

  • API Documentation (Redis, Cluster)
  • Changelog

Quick Start

Install

bash
npm install ioredis

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

bash
npm install --save-dev @types/node

Basic Usage

…

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

  • TTL
  • Strings
  • Hashes
  • Lists
  • Sets
  • Sorted Sets
  • Streams
  • Redis Modules e.g. RedisJSON

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:

javascript
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 pass a connection string as the first constructor argument. Use a redis:// URL or rediss:// URL when using TLS encryption:

javascript
// Connect to 127.0.0.1:6380, db 4, using password "authpassword":
new Redis("redis://:[email protected]:6380/4");

// Username can also be passed via URI.
new Redis("redis://username:[email protected]: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.

javascript
// 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);
…

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:

javascript
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:

javascript
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:

…

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:

javascript
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:

javascript
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:

javascript
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:

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

Managed HIMPORT Fieldsets (experimental)

[!WARNING] ioredis managed-fieldset support is experimental and may change in a future release. When a managed HIMPORT SET needs fieldset preparation or recovery, later commands may be sent before that SET resumes. Await the SET before issuing commands that depend on its write.

HIMPORT requires Redis 8.10 or newer. It provides a faster ingestion mechanism for loading many hashes that share the same set of field names.

Explicit pipelines containing a configured HIMPORT SET wait for required fieldset preparation on their selected connection before the batch is sent. Unconfigured fieldsets remain manually managed.

javascript
const redis = new Redis({
  himportFieldsets: [
    {
      name: "user-profile",
      fields: ["name", "email", "age"],
    },
  ],
});

await redis.himport(
  "SET",
  "user:42",
  "user-profile",
  "Ada",
  "[email protected]",
  "37"
);

For Cluster clients, pass himportFieldsets at the top level of the Cluster options, not under redisOptions. ioredis prepares managed fieldsets on current and future master connections:

javascript
const cluster = new Redis.Cluster(nodes, {
  himportFieldsets: [
    {
      name: "user-profile",
      fields: ["name", "email", "age"],
    },
  ],
});

Direct HIMPORT PREPARE, DISCARD, and DISCARDALL calls on a Cluster client fan out to all current masters, wait for every reply, and reject if any master fails. Inside an explicit pipeline, these commands remain connection-affine and are not managed.

Background preparation failures do not prevent a connection from becoming ready. Standalone and Sentinel clients report them through the error event; Cluster clients report them through node error. A dependent managed HIMPORT SET retries preparation and rejects if recovery fails.

See examples/himport.js for managed fieldsets and manual batches.

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:

…

Each chained command can also hav

Issues· 193 open

View all issuesOpen on GitHub
  • #2075

    autopipelining: commands fail during cluster topology changes due to pipeline-level MOVED handling

    Updated Sep 30, 2026
  • #1613

    Timeout errors when load increases

    staleUpdated Sep 29, 2026
  • #1615

    一个关于 redis 长链接的问题

    questionstaleUpdated Sep 29, 2026
  • #1616

    How to obtain results from pipeline without ugly indexing?

    staleUpdated Sep 25, 2026
  • #1622

    Does ioredis close connections due to timeouts at client side?

    questionstaleUpdated Sep 23, 2026
  • #1628

    quit() error "connection is closed." only for TLS connection

    staleUpdated Sep 23, 2026
  • #1630

    commandTimeout should not be enabled for blocking commands

    Updated Sep 22, 2026
  • #1638

    Unhandled error event: Error: write EPIPE, Unhandled error event: Error: write ECONNRESET

    staleUpdated Sep 16, 2026
  • #1640

    Feature Request: Pooling

    staleUpdated Sep 15, 2026
  • #1645

    No way to determine if underlying connection has been killed

    staleUpdated Sep 11, 2026

> Tags

TypeScriptnodejsredisredis-clientredis-cluster

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库