keyv vs ioredis vs redis vs @keyv/redis vs cache-manager-redis-store vs redis-om
Redis Client Libraries for Node.js Comparison
1 Year
keyvioredisredis@keyv/rediscache-manager-redis-storeredis-omSimilar Packages:
What's Redis Client Libraries for Node.js?

These libraries provide various interfaces and functionalities for interacting with Redis, a powerful in-memory data structure store, often used as a database, cache, and message broker. Each library offers unique features tailored for different use cases, from simple key-value storage to complex data management and caching strategies. Understanding their capabilities helps developers choose the right tool for their specific needs in web development.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
keyv49,346,5052,90493.4 kB13 days agoMIT
ioredis7,171,06614,862717 kB3772 months agoMIT
redis5,217,36017,206247 kB3647 days agoMIT
@keyv/redis397,4462,90472.8 kB1a month agoMIT
cache-manager-redis-store216,46417137.7 kB21-MIT
redis-om16,2341,227391 kB578 months agoMIT
Feature Comparison: keyv vs ioredis vs redis vs @keyv/redis vs cache-manager-redis-store vs redis-om

Client Features

  • keyv:

    keyv provides a simple key-value store interface with support for multiple backends, including Redis. It is designed for ease of use and includes features like TTL and automatic expiration of keys.

  • ioredis:

    ioredis offers advanced features such as support for Redis clustering, Lua scripting, and transactions. It also supports promises and async/await syntax, making it a powerful choice for complex applications.

  • redis:

    The redis package is the official Redis client for Node.js, providing comprehensive access to Redis features. It supports callbacks and promises, making it versatile for different coding styles.

  • @keyv/redis:

    @keyv/redis provides a simple API for storing and retrieving key-value pairs with support for various backends, including Redis. It is designed for ease of use and minimal configuration, making it suitable for lightweight applications.

  • cache-manager-redis-store:

    cache-manager-redis-store integrates with cache-manager to provide a Redis store. It allows for easy caching with a unified interface, supporting features like TTL (time-to-live) and cache invalidation.

  • redis-om:

    redis-om acts as an object mapper for Redis, allowing developers to work with complex data structures and perform operations like indexing and querying, making it suitable for applications that require structured data management.

Performance

  • keyv:

    keyv is optimized for performance with minimal overhead, making it a good choice for applications that require fast key-value storage without complex features.

  • ioredis:

    ioredis is designed for high performance, especially in clustered environments. Its support for pipelining and batch operations allows for efficient data handling in high-throughput applications.

  • redis:

    The redis client is highly performant and optimized for direct communication with Redis, ensuring low latency and high throughput for data operations.

  • @keyv/redis:

    @keyv/redis is lightweight and optimized for speed, making it suitable for applications that require quick access to cached data without heavy overhead.

  • cache-manager-redis-store:

    cache-manager-redis-store is efficient for caching scenarios, leveraging Redis's fast in-memory capabilities to improve application performance by reducing database load.

  • redis-om:

    redis-om is built for performance when managing complex data structures, allowing for efficient querying and indexing, which can enhance application speed.

Ease of Use

  • keyv:

    keyv is user-friendly and designed for simplicity, making it easy for developers to implement key-value storage without deep knowledge of Redis.

  • ioredis:

    ioredis has a steeper learning curve due to its extensive feature set, but it provides comprehensive documentation to help developers understand its capabilities.

  • redis:

    The redis package is well-documented, making it accessible for developers familiar with Redis concepts, though it may require more setup than simpler libraries.

  • @keyv/redis:

    @keyv/redis is straightforward to use, with a simple API that allows developers to quickly implement caching without extensive configuration.

  • cache-manager-redis-store:

    cache-manager-redis-store is easy to integrate with existing cache-manager setups, providing a familiar interface for developers already using cache-manager.

  • redis-om:

    redis-om provides a structured approach to data management, which may require a learning curve for developers unfamiliar with object mapping but is well-documented for ease of use.

Community and Support

  • keyv:

    keyv is actively maintained and has a supportive community, providing resources and documentation for developers to troubleshoot and implement solutions.

  • ioredis:

    ioredis has a large and active community, with extensive documentation and support available, making it a reliable choice for developers.

  • redis:

    The redis package has a strong community and is the official client, ensuring robust support and frequent updates from the maintainers.

  • @keyv/redis:

    @keyv/redis has a growing community and is actively maintained, providing good support through GitHub and community forums.

  • cache-manager-redis-store:

    cache-manager-redis-store benefits from the broader cache-manager community, ensuring ongoing support and updates as part of the cache-manager ecosystem.

  • redis-om:

    redis-om is actively developed with a growing community, offering support and documentation for developers looking to implement object mapping with Redis.

Use Cases

  • keyv:

    keyv is great for small to medium applications needing a straightforward key-value store, such as caching user preferences or temporary data.

  • ioredis:

    ioredis is well-suited for applications that require advanced Redis features, such as real-time data processing, pub/sub messaging, and high-performance caching in clustered environments.

  • redis:

    The redis package is suitable for any application needing direct access to Redis features, including data persistence, caching, and real-time analytics.

  • @keyv/redis:

    @keyv/redis is ideal for applications that require simple caching solutions, such as session storage or temporary data storage without complex requirements.

  • cache-manager-redis-store:

    cache-manager-redis-store is perfect for applications that need a unified caching strategy across multiple stores, particularly for caching API responses or database queries.

  • redis-om:

    redis-om is designed for applications that require structured data management, such as e-commerce platforms or content management systems where complex data relationships exist.

How to Choose: keyv vs ioredis vs redis vs @keyv/redis vs cache-manager-redis-store vs redis-om
  • keyv:

    Use keyv if you want a simple and straightforward key-value store with support for various backends, including Redis. It is great for small to medium-sized applications that need an easy-to-use caching solution.

  • ioredis:

    Opt for ioredis if you need a robust and feature-rich Redis client that supports clustering and promises. It is suitable for applications that require high performance and advanced Redis features, such as transactions and Lua scripting.

  • redis:

    Choose redis if you want the official Redis client for Node.js, which provides a comprehensive set of features and is well-maintained. It is suitable for applications that require direct access to Redis functionalities without additional abstractions.

  • @keyv/redis:

    Choose @keyv/redis if you need a simple key-value store that supports multiple backends and want to easily switch between them. It is ideal for applications that require a lightweight caching solution with minimal configuration.

  • cache-manager-redis-store:

    Select cache-manager-redis-store if you are using the cache-manager library and need a Redis store for caching. This package is perfect for applications that require a unified caching interface with support for multiple stores.

  • redis-om:

    Select redis-om if you are working with Redis as an object mapper and need to manage complex data structures. It is ideal for applications that require a more structured approach to data management in Redis.

README for keyv

keyv

Simple key-value storage with support for multiple backends

build codecov npm npm

Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store.

Features

There are a few existing modules similar to Keyv, however Keyv is different because it:

  • Isn't bloated
  • Has a simple Promise based API
  • Suitable as a TTL based cache or persistent key-value store
  • Easily embeddable inside another module
  • Works with any storage that implements the Map API
  • Handles all JSON types plus Buffer
  • Supports namespaces
  • Wide range of efficient, well tested storage adapters
  • Connection errors are passed through (db failures won't kill your app)
  • Supports the current active LTS version of Node.js or higher

Table of Contents

Usage

Install Keyv.

npm install --save keyv

By default everything is stored in memory, you can optionally also install a storage adapter.

npm install --save @keyv/redis
npm install --save @keyv/valkey
npm install --save @keyv/mongo
npm install --save @keyv/sqlite
npm install --save @keyv/postgres
npm install --save @keyv/mysql
npm install --save @keyv/etcd
npm install --save @keyv/memcache

First, create a new Keyv instance.

import Keyv from 'keyv';

Type-safe Usage

You can create a Keyv instance with a generic type to enforce type safety for the values stored. Additionally, both the get and set methods support specifying custom types for specific use cases.

Example with Instance-level Generic Type:

const keyv = new Keyv<number>(); // Instance handles only numbers
await keyv.set('key1', 123);
const value = await keyv.get('key1'); // value is inferred as number

Example with Method-level Generic Type:

You can also specify a type directly in the get or set methods, allowing flexibility for different types of values within the same instance.

const keyv = new Keyv(); // Generic type not specified at instance level

await keyv.set<string>('key2', 'some string'); // Method-level type for this value
const strValue = await keyv.get<string>('key2'); // Explicitly typed as string

await keyv.set<number>('key3', 456); // Storing a number in the same instance
const numValue = await keyv.get<number>('key3'); // Explicitly typed as number

This makes Keyv highly adaptable to different data types while maintaining type safety.

Using Storage Adapters

Once you have created your Keyv instance you can use it as a simple key-value store with in-memory by default. To use a storage adapter, create an instance of the adapter and pass it to the Keyv constructor. Here are some examples:

// redis
import KeyvRedis from '@keyv/redis';

const keyv = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'));

You can also pass in a storage adapter with other options such as ttl and namespace (example using sqlite):

//sqlite
import KeyvSqlite from '@keyv/sqlite';

const keyvSqlite = new KeyvSqlite('sqlite://path/to/database.sqlite');
const keyv = new Keyv({ store: keyvSqlite, ttl: 5000, namespace: 'cache' });

To handle an event you can do the following:

// Handle DB connection errors
keyv.on('error', err => console.log('Connection Error', err));

Now lets do an end-to-end example using Keyv and the Redis storage adapter:

import Keyv from 'keyv';
import KeyvRedis from '@keyv/redis';

const keyvRedis = new KeyvRedis('redis://user:pass@localhost:6379');
const keyv = new Keyv({ store: keyvRedis });

await keyv.set('foo', 'expires in 1 second', 1000); // true
await keyv.set('foo', 'never expires'); // true
await keyv.get('foo'); // 'never expires'
await keyv.delete('foo'); // true
await keyv.clear(); // undefined

It's is just that simple! Keyv is designed to be simple and easy to use.

Namespaces

You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database.

const users = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'users' });
const cache = new Keyv(new KeyvRedis('redis://user:pass@localhost:6379'), { namespace: 'cache' });

await users.set('foo', 'users'); // true
await cache.set('foo', 'cache'); // true
await users.get('foo'); // 'users'
await cache.get('foo'); // 'cache'
await users.clear(); // undefined
await users.get('foo'); // undefined
await cache.get('foo'); // 'cache'

Events

Keyv is a custom EventEmitter and will emit an 'error' event if there is an error. If there is no listener for the 'error' event, an uncaught exception will be thrown. To disable the 'error' event, pass emitErrors: false in the constructor options.

const keyv = new Keyv({ emitErrors: false });

In addition it will emit clear and disconnect events when the corresponding methods are called.

const keyv = new Keyv();
const handleConnectionError = err => console.log('Connection Error', err);
const handleClear = () => console.log('Cache Cleared');
const handleDisconnect = () => console.log('Disconnected');

keyv.on('error', handleConnectionError);
keyv.on('clear', handleClear);
keyv.on('disconnect', handleDisconnect);

Hooks

Keyv supports hooks for get, set, and delete methods. Hooks are useful for logging, debugging, and other custom functionality. Here is a list of all the hooks:

PRE_GET
POST_GET
PRE_GET_MANY
POST_GET_MANY
PRE_SET
POST_SET
PRE_DELETE
POST_DELETE

You can access this by importing KeyvHooks from the main Keyv package.

import Keyv, { KeyvHooks } from 'keyv';
//PRE_SET hook
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => console.log(`Setting key ${data.key} to ${data.value}`));

//POST_SET hook
const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.POST_SET, (key, value) => console.log(`Set key ${key} to ${value}`));

In these examples you can also manipulate the value before it is set. For example, you could add a prefix to all keys.

const keyv = new Keyv();
keyv.hooks.addHandler(KeyvHooks.PRE_SET, (data) => {
  console.log(`Manipulating key ${data.key} and ${data.value}`);
  data.key = `prefix-${data.key}`;
  data.value = `prefix-${data.value}`;
});

Now this key will have prefix- added to it before it is set.

In PRE_DELETE and POST_DELETE hooks, the value could be a single item or an Array. This is based on the fact that delete can accept a single key or an Array of keys.

Custom Serializers

Keyv uses buffer for data serialization to ensure consistency across different backends.

You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON.

const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse });

Warning: Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine.

If you do not want to use serialization you can set the serialize and deserialize functions to undefined. This will also turn off compression.

const keyv = new Keyv();
keyv.serialize = undefined;
keyv.deserialize = undefined;

Official Storage Adapters

The official storage adapters are covered by over 150 integration tests to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available.

Database | Adapter | Native TTL ---|---|--- Redis | @keyv/redis | Yes Valkey | @keyv/valkey | Yes MongoDB | @keyv/mongo | Yes SQLite | @keyv/sqlite | No PostgreSQL | @keyv/postgres | No MySQL | @keyv/mysql | No Etcd | @keyv/etcd | Yes Memcache | @keyv/memcache | Yes

Third-party Storage Adapters

You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally.

import Keyv from 'keyv';
import myAdapter from 'my-adapter';

const keyv = new Keyv({ store: myAdapter });

Any store that follows the Map api will work.

new Keyv({ store: new Map() });

For example, quick-lru is a completely unrelated module that implements the Map API.

import Keyv from 'keyv';
import QuickLRU from 'quick-lru';

const lru = new QuickLRU({ maxSize: 1000 });
const keyv = new Keyv({ store: lru });

The following are third-party storage adapters compatible with Keyv:

Compression

Keyv supports gzip, brotli and lz4 compression. To enable compression, pass the compress option to the constructor.

import Keyv from 'keyv';
import KeyvGzip from '@keyv/compress-gzip';

const keyvGzip = new KeyvGzip();
const keyv = new Keyv({ compression: keyvGzip });
import Keyv from 'keyv';
import KeyvBrotli from '@keyv/compress-brotli';

const keyvBrotli = new KeyvBrotli();
const keyv = new Keyv({ compression: keyvBrotli });
import Keyv from 'keyv';
import KeyvLz4 from '@keyv/compress-lz4';

const keyvLz4 = new KeyvLz4();
const keyv = new Keyv({ compression: keyvLz4 });

You can also pass a custom compression function to the compression option. Following the pattern of the official compression adapters.

Want to build your own CompressionAdapter?

Great! Keyv is designed to be easily extended. You can build your own compression adapter by following the pattern of the official compression adapters based on this interface:

interface CompressionAdapter {
	async compress(value: any, options?: any);
	async decompress(value: any, options?: any);
	async serialize(value: any);
	async deserialize(value: any);
}

In addition to the interface, you can test it with our compression test suite using @keyv/test-suite:

import { keyvCompresstionTests } from '@keyv/test-suite';
import KeyvGzip from '@keyv/compress-gzip';

keyvCompresstionTests(test, new KeyvGzip());

API

new Keyv([storage-adapter], [options]) or new Keyv([options])

Returns a new Keyv instance.

The Keyv instance is also an EventEmitter that will emit an 'error' event if the storage adapter connection fails.

storage-adapter

Type: KeyvStorageAdapter
Default: undefined

The connection string URI.

Merged into the options object as options.uri.

.namespace

Type: String Default: 'keyv'

This is the namespace for the current instance. When you set it it will set it also on the storage adapter. This is the preferred way to set the namespace over .opts.namespace.

options

Type: Object

The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options.

options.namespace

Type: String
Default: 'keyv'

Namespace for the current instance.

options.ttl

Type: Number
Default: undefined

Default TTL. Can be overridden by specififying a TTL on .set().

options.compression

Type: @keyv/compress-<compression_package_name>
Default: undefined

Compression package to use. See Compression for more details.

options.serialize

Type: Function
Default: JSON.stringify

A custom serialization function.

options.deserialize

Type: Function
Default: JSON.parse

A custom deserialization function.

options.store

Type: Storage adapter instance
Default: new Map()

The storage adapter instance to be used by Keyv.

Keyv Instance

Keys must always be strings. Values can be of any type.

.set(key, value, [ttl])

Set a value.

By default keys are persistent. You can set an expiry TTL in milliseconds.

Returns a promise which resolves to true.

.setMany(entries)

Set multiple values using KeyvEntrys { key: string, value: any, ttl?: number }.

.get(key, [options])

Returns a promise which resolves to the retrieved value.

.getMany(keys, [options])

Returns a promise which resolves to an array of retrieved values.

options.raw

Type: Boolean
Default: false

If set to true the raw DB object Keyv stores internally will be returned instead of just the value.

This contains the TTL timestamp.

.delete(key)

Deletes an entry.

Returns a promise which resolves to true if the key existed, false if not.

.deleteMany(keys)

Deletes multiple entries. Returns a promise which resolves to an array of booleans indicating if the key existed or not.

.clear()

Delete all entries in the current namespace.

Returns a promise which is resolved when the entries have been cleared.

.iterator()

Iterate over all entries of the current namespace.

Returns a iterable that can be iterated by for-of loops. For example:

// please note that the "await" keyword should be used here
for await (const [key, value] of this.keyv.iterator()) {
  console.log(key, value);
};

API - Properties

.namespace

Type: String

The namespace for the current instance. This will define the namespace for the current instance and the storage adapter. If you set the namespace to undefined it will no longer do key prefixing.

const keyv = new Keyv({ namespace: 'my-namespace' });
console.log(keyv.namespace); // 'my-namespace'

here is an example of setting the namespace to undefined:

const keyv = new Keyv();
console.log(keyv.namespace); // 'keyv' which is default
keyv.namespace = undefined;
console.log(keyv.namespace); // undefined

.ttl

Type: Number
Default: undefined

Default TTL. Can be overridden by specififying a TTL on .set(). If set to undefined it will never expire.

const keyv = new Keyv({ ttl: 5000 });
console.log(keyv.ttl); // 5000
keyv.ttl = undefined;
console.log(keyv.ttl); // undefined (never expires)

.store

Type: Storage adapter instance
Default: new Map()

The storage adapter instance to be used by Keyv. This will wire up the iterator, events, and more when a set happens. If it is not a valid Map or Storage Adapter it will throw an error.

import KeyvSqlite from '@keyv/sqlite';
const keyv = new Keyv();
console.log(keyv.store instanceof Map); // true
keyv.store = new KeyvSqlite('sqlite://path/to/database.sqlite');
console.log(keyv.store instanceof KeyvSqlite); // true

.serialize

Type: Function
Default: JSON.stringify

A custom serialization function used for any value.

const keyv = new Keyv();
console.log(keyv.serialize); // JSON.stringify
keyv.serialize = value => value.toString();
console.log(keyv.serialize); // value => value.toString()

.deserialize

Type: Function
Default: JSON.parse

A custom deserialization function used for any value.

const keyv = new Keyv();
console.log(keyv.deserialize); // JSON.parse
keyv.deserialize = value => parseInt(value);
console.log(keyv.deserialize); // value => parseInt(value)

.compression

Type: CompressionAdapter
Default: undefined

this is the compression package to use. See Compression for more details. If it is undefined it will not compress (default).

import KeyvGzip from '@keyv/compress-gzip';

const keyv = new Keyv();
console.log(keyv.compression); // undefined
keyv.compression = new KeyvGzip();
console.log(keyv.compression); // KeyvGzip

.useKeyPrefix

Type: Boolean
Default: true

If set to true Keyv will prefix all keys with the namespace. This is useful if you want to avoid collisions with other data in your storage.

const keyv = new Keyv({ useKeyPrefix: false });
console.log(keyv.useKeyPrefix); // false
keyv.useKeyPrefix = true;
console.log(keyv.useKeyPrefix); // true

How to Contribute

We welcome contributions to Keyv! 🎉 Here are some guides to get you started with contributing:

License

MIT © Jared Wray