Skip to content

Redis ​

Introduction ​

@plinthjs/redis is a Redis client with no dependencies. It speaks the Redis wire protocol (RESP) directly over a TCP socket from node:net, and gives you typed helper methods for the common data types, plus pipelines, transactions, Lua scripting, streams and pub/sub. A manager resolves named connections from configuration, so different parts of your application (cache, sessions, a subscriber) can each use their own database or credentials.

bash
pnpm add @plinthjs/redis

Reach for it when you need Redis directly: counters, queues, leaderboards, pub/sub, or as a backing store for your own cache store.

Connecting ​

Create a RedisManager with a set of named connection configurations, then ask it for a connection.

ts
import { RedisManager } from '@plinthjs/redis'

const redis = new RedisManager({
  default: 'default',
  connections: {
    default: { host: '127.0.0.1', port: 6379, db: 0, prefix: 'app:' },
    cache: { host: '127.0.0.1', port: 6379, db: 1, username: 'app', password: 'secret' },
    subscriber: { host: '127.0.0.1', port: 6379 },
  },
})

const connection = redis.connection() // the default connection
await connection.connect() // open the socket

Calling connect() is optional: the first command on a connection that is not open connects it first (and does so again after the connection was closed). Call it explicitly to fail fast at startup. connect() is safe to call more than once: concurrent calls share the same attempt.

The connection options are:

OptionMeaning
hostServer host. Defaults to 127.0.0.1.
portServer port. Defaults to 6379.
dbDatabase index to select when connecting. Defaults to 0.
passwordPassword to authenticate with when connecting.
usernameUsername for ACL authentication (Redis 6 and later). Needs password.
prefixA string prepended to every key you pass to a typed method (see below).

On connect, the client sends AUTH if a password is set, then SELECT if db is not 0.

You can also construct a connection without a manager:

ts
import { RedisConnection } from '@plinthjs/redis'

const standalone = new RedisConnection({ host: '127.0.0.1', port: 6379 })
await standalone.connect()

Multiple connections ​

redis.connection(name) returns the connection for that name, creating it on first use and caching it afterwards. Asking for a name that is not configured throws Redis connection [name] is not defined.

ts
const cache = redis.connection('cache')
await cache.connect()

redis.getDefaultConnection() // => 'default'

To build a connection yourself (for example with custom logic), register a factory:

ts
redis.extend('analytics', () => new RedisConnection({ host: 'analytics.internal', db: 4 }))

Disconnecting ​

ts
await connection.quit() // sends QUIT, then closes the socket
redis.disconnectAll() // on shutdown: destroys every connection the manager opened

quit() is the polite way to close one connection. disconnect() destroys the socket at once and rejects any command still waiting for a reply with Connection closed. After either, you can call connect() again.

Key prefixes ​

When a connection has a prefix, every typed method adds it to the keys you pass, so several applications can share one Redis database without colliding.

ts
const connection = new RedisConnection({ prefix: 'app:' })
await connection.connect()

await connection.set('greeting', 'hello', { ex: 60 }) // => 'OK'; stored as app:greeting
await connection.get('greeting') // => 'hello'

Two things to remember:

  • Raw command(), pipeline() and multi() send exactly what you give them. The prefix is not applied, so write the full key yourself ('app:greeting').
  • Methods that return keys (keys, scan, scanIterator) return them with the prefix. The match pattern you pass is prefixed for you, but the results are the stored names.

Channel names for publish, subscribe and psubscribe are never prefixed.

Strings and keys ​

ts
await connection.set('visits', 0)
await connection.incr('visits') // => 1
await connection.incrby('visits', 10) // => 11
await connection.decr('visits') // => 10
await connection.incrbyfloat('ratio', 1.5) // => 1.5

await connection.set('token', 'abc', { ex: 60 }) // expire in 60 seconds
await connection.set('token', 'abc', { px: 1500 }) // expire in 1500 ms
await connection.set('lock', '1', { nx: true, ex: 30 }) // only if absent; null when declined
await connection.setex('temp', 30, 'value') // set with a TTL
await connection.setnx('once', 'x') // => true when it was written

set accepts ex, px, nx, xx, get and keepttl, and resolves to 'OK' (or null when an nx/xx condition was not met).

Other string commands, all prefix-aware: getset, getdel, getex (read and change the expiry, with ex, px, exat, pxat or persist), append, strlen, getrange, setrange.

ts
await connection.mset({ a: 1, b: 2 })
await connection.mget('a', 'b', 'missing') // => ['1', '2', null]
await connection.msetnx({ c: 3, d: 4 }) // => true when every key was set
await connection.append('log', 'line one\n') // => the new length
await connection.getdel('token') // read and remove

Key management:

ts
await connection.exists('a', 'b') // => the number of keys that exist
await connection.del('a', 'b') // => the number removed
await connection.unlink('big') // like del, but frees memory in the background
await connection.expire('a', 60) // => true
await connection.pexpire('a', 1500)
await connection.expireat('a', 1893456000) // an absolute Unix time in seconds
await connection.ttl('a') // => seconds remaining (-1: no expiry, -2: no such key)
await connection.pttl('a') // => milliseconds remaining
await connection.persist('a') // remove the expiry
await connection.type('a') // => 'string' (or 'hash', 'list', 'set', 'zset', 'stream', 'none')
await connection.rename('a', 'b')
await connection.renamenx('a', 'b') // => false when b already exists
await connection.randomkey()
await connection.touch('a', 'b') // update last-access time
await connection.dbsize() // => the number of keys in the database

Finding keys ​

keys(pattern) returns every matching key in one go, which blocks the server while it works. Avoid it on large databases. scan walks the key space one page at a time instead.

ts
const page = await connection.scan(0, { match: 'session:*', count: 100 })
page.cursor // => '0' when the walk is finished, otherwise pass it to the next call
page.keys // => ['app:session:1', ...] (with the prefix)

scanIterator runs the whole walk for you as an async iterator:

ts
for await (const key of connection.scanIterator({ match: 'session:*', count: 100 })) {
  await connection.unlink(key.slice(connection.prefix.length))
}

Because scanned keys carry the prefix, strip it (as above, using connection.prefix) before passing them back to a prefix-aware method. scan and scanIterator also accept type to restrict the walk to one data type.

Hashes ​

ts
await connection.hset('user:1', 'name', 'Ada') // => 1 (a new field)
await connection.hset('user:1', 'visits', 0)
await connection.hget('user:1', 'name') // => 'Ada'
await connection.hgetall('user:1') // => { name: 'Ada', visits: '0' }
await connection.hmget('user:1', 'name', 'x') // => ['Ada', null]
await connection.hexists('user:1', 'name') // => true
await connection.hincrby('user:1', 'visits', 1) // => 1
await connection.hincrbyfloat('user:1', 'score', 0.5)
await connection.hkeys('user:1')
await connection.hvals('user:1')
await connection.hlen('user:1')
await connection.hsetnx('user:1', 'name', 'Grace') // => false, the field exists
await connection.hdel('user:1', 'visits') // => 1
await connection.hrandfield('user:1') // a random field name

Values always come back as strings. For large hashes, hscan (one page of { cursor, entries }) and hscanIterator (an async iterator of [field, value] pairs) walk the fields without loading them all.

Lists ​

ts
await connection.rpush('jobs', 'a', 'b', 'c') // => 3
await connection.lpush('jobs', 'z') // => 4
await connection.lrange('jobs', 0, -1) // => ['z', 'a', 'b', 'c']
await connection.lpop('jobs') // => 'z'
await connection.rpop('jobs') // => 'c'
await connection.llen('jobs') // => 2
await connection.lindex('jobs', 0) // => 'a'
await connection.lset('jobs', 0, 'A')
await connection.lrem('jobs', 1, 'b') // remove one 'b'
await connection.ltrim('jobs', 0, 99) // keep only the first 100
await connection.linsert('jobs', 'BEFORE', 'A', 'start')
await connection.lpos('jobs', 'A') // => the index of the first match, or null

lmove(source, destination, 'LEFT' | 'RIGHT', 'LEFT' | 'RIGHT') and rpoplpush(source, destination) atomically move an element from one list to another, which is the basis of a reliable work queue. lpushx and rpushx push only when the list already exists.

Sets ​

ts
await connection.sadd('tags', 'ts', 'node') // => 2
await connection.sismember('tags', 'ts') // => true
await connection.smismember('tags', 'ts', 'go') // => [true, false]
await connection.smembers('tags')
await connection.scard('tags') // => 2
await connection.srem('tags', 'node')
await connection.spop('tags') // remove and return a random member
await connection.srandmember('tags', 2) // sample without removing

await connection.sinter('a', 'b') // members in both sets
await connection.sunion('a', 'b')
await connection.sdiff('a', 'b') // in a but not b
await connection.sinterstore('dest', 'a', 'b') // => the size of the stored result
await connection.smove('a', 'b', 'member')

sunionstore, sdiffstore, sscan and sscanIterator work the same way as their counterparts.

Sorted sets ​

A sorted set keeps unique members ordered by a numeric score. Members are passed to zadd as { score, member } objects.

ts
await connection.zadd('scores', [
  { score: 10, member: 'ada' },
  { score: 7, member: 'linus' },
]) // => 2

await connection.zrevrangeWithScores('scores', 0, 9)
// => [{ member: 'ada', score: 10 }, { member: 'linus', score: 7 }]

await connection.zrange('scores', 0, -1) // => ['linus', 'ada'] (lowest score first)
await connection.zscore('scores', 'ada') // => 10
await connection.zrank('scores', 'ada') // => 1 (zero-based, ascending)
await connection.zrevrank('scores', 'ada') // => 0
await connection.zincrby('scores', 5, 'linus') // => 12
await connection.zcard('scores') // => 2
await connection.zcount('scores', 8, 20)
await connection.zpopmax('scores') // => [{ member: 'linus', score: 12 }]

zadd takes flags as a third argument: { nx, xx, gt, lt, ch }. Ranges by score or lexicographic order go through zrange options (byscore, bylex, rev, limit), or the dedicated zrangebyscore and zrevrangebyscore methods. Every range method has a WithScores variant that returns { member, score } objects.

ts
await connection.zrange('scores', '(8', '+inf', { byscore: true, limit: { offset: 0, count: 5 } })
await connection.zrangebyscoreWithScores('scores', 0, 100)

You can also use zrem, zmscore, zpopmin, zremrangebyscore, zremrangebyrank, zrangestore, zinterstore and zunionstore (the last two take { weights, aggregate }), plus zscan and zscanIterator.

Streams ​

ts
const id = await connection.xadd('events', '*', { type: 'signup', user: 1 })
// => the new entry id, such as '1700000000000-0'

await connection.xlen('events') // => 1
await connection.xrange('events') // => [{ id, fields: { type: 'signup', user: '1' } }]
await connection.xrevrange('events', '+', '-', 10) // newest first, at most 10
await connection.xread({ events: '0' }, { count: 100 })
// => [{ stream: 'app:events', entries: [...] }]
await connection.xdel('events', id)

xread reads only what is already in the stream (it does not block waiting for new entries). It resolves to an empty array when there is nothing new. Note that stream in the result carries the key prefix.

Pipelines and transactions ​

A pipeline writes several commands back to back and collects the replies in order, which saves round trips. It is about speed, not atomicity.

ts
await connection.pipeline([
  ['INCR', 'app:a'],
  ['INCR', 'app:b'],
]) // => [1, 1]

multi wraps the commands in MULTI and EXEC, so the server runs them as one atomic unit. It resolves to the EXEC reply: one entry per command, or null if a watched key changed and the transaction was discarded.

ts
await connection.multi([
  ['SET', 'app:x', '1'],
  ['INCR', 'app:x'],
]) // => ['OK', 2]

To make a transaction conditional on other keys staying unchanged, use watch, unwatch and discard:

ts
await connection.watch('balance')
const result = await connection.multi([['DECRBY', 'app:balance', 10]])
if (result === null) {
  // another client changed the key first: retry
}

Both pipeline and multi take full command argument lists, so remember that the key prefix is not applied inside them.

Lua scripts ​

eval runs a script on the server. Keys you list are prefixed for you; the reply keeps whatever shape the script returns.

ts
await connection.eval("return redis.call('GET', KEYS[1])", ['greeting']) // reads app:greeting
await connection.eval('return ARGV[1] + ARGV[2]', [], [2, 3]) // => 5

For scripts you run repeatedly, load them once and call them by digest:

ts
const sha = await connection.scriptLoad("return redis.call('INCR', KEYS[1])")
await connection.evalsha(sha, ['counter'])
await connection.scriptExists(sha) // => [true]
await connection.scriptFlush()

Pub/sub ​

A connection that subscribes enters subscriber mode and can no longer be used for ordinary commands, so give subscribers their own connection.

ts
const subscriber = redis.connection('subscriber')
await subscriber.connect()

await subscriber.subscribe('orders', (message, channel) => {
  console.log(channel, message)
})
await subscriber.psubscribe('orders.*', (message, channel, pattern) => {
  console.log(pattern, channel, message)
})

await connection.publish('orders', JSON.stringify({ id: 1 })) // => the number of receivers

await subscriber.unsubscribe('orders') // one channel
await subscriber.unsubscribe() // every channel

subscribe and psubscribe accept a single name or an array. isSubscriber tells you whether a connection is currently in subscriber mode. For broadcasting events to browsers, see Broadcasting.

Server commands and raw access ​

A few server-level helpers are typed too:

ts
await connection.ping() // => 'PONG'
await connection.ping('hi') // => 'hi'
await connection.info('memory') // => the INFO text for that section
await connection.time() // => { seconds: 1700000000, microseconds: 123456 }
await connection.flushdb() // careful: clears the selected database

For anything without a typed method, use command(), which takes the command name and arguments and resolves with the parsed reply:

ts
await connection.command('OBJECT', 'ENCODING', 'app:greeting')

Replies are decoded to strings, numbers, null, arrays or maps. asInteger, asStringArray, asStringOrNull, asRecord and toText are exported if you want to coerce a raw reply.

Handling errors ​

When Redis answers with an error, the command rejects with a RedisError. The message is the server's full error text, and prefix holds its leading code (for example ERR, WRONGTYPE or NOSCRIPT).

ts
import { RedisError } from '@plinthjs/redis'

try {
  await connection.command('GET')
} catch (error) {
  if (error instanceof RedisError) {
    console.error(error.prefix, error.message) // => 'ERR' 'ERR wrong number of arguments ...'
  }
}

If the socket closes or errors, every command still waiting rejects.

WARNING

Commands on one connection are answered in order, so a slow command (such as keys on a large database) delays the ones behind it. Use a separate connection for subscribers and for heavy operations.

Testing ​

No Redis server is needed to test code that uses a connection. Pass a socketFactory that returns your own object implementing the small SocketLike interface (write, on, end, destroy) and feed it replies in the wire format. A connection config accepts socketFactory, and so does RedisManagerOptions, which applies it to every connection it builds.

ts
import { RedisManager } from '@plinthjs/redis'
import type { SocketLike } from '@plinthjs/redis'

class FakeSocket implements SocketLike {
  writes: string[] = []
  private handlers = new Map<string, ((...args: never[]) => void)[]>()
  private replies: string[] = []

  write(data: Buffer): boolean {
    this.writes.push(data.toString())
    const next = this.replies.shift()
    if (next !== undefined) queueMicrotask(() => this.emit('data', Buffer.from(next)))
    return true
  }
  on(event: string, listener: (...args: never[]) => void): this {
    this.handlers.set(event, [...(this.handlers.get(event) ?? []), listener])
    if (event === 'connect') queueMicrotask(() => this.emit('connect'))
    return this
  }
  end(): void {}
  destroy(): void {}
  emit(event: string, ...args: unknown[]): void {
    for (const fn of this.handlers.get(event) ?? []) (fn as (...a: unknown[]) => void)(...args)
  }
  reply(...frames: string[]): void {
    this.replies.push(...frames)
  }
}

const socket = new FakeSocket()
const redis = new RedisManager({
  connections: { default: { prefix: 'app:' } },
  socketFactory: () => socket,
})

const connection = redis.connection()
await connection.connect()

socket.reply('+OK\r\n') // what the server would answer to SET
await connection.set('greeting', 'hello', { ex: 60 }) // => 'OK'
socket.writes.at(-1) // the exact bytes sent, containing 'app:greeting'

Because the fake sees the encoded bytes, you can assert both what your code sent (including the prefix) and how it handles replies, including error frames such as -ERR boom\r\n.

For application tests that only need caching behaviour, prefer the in-memory store from Cache and keep Redis for integration tests.

Released under the MIT License.