Skip to content

Instantly share code, notes, and snippets.

@jakobo
Last active May 28, 2020 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakobo/05d82e84725de923499f4b79c20da5dd to your computer and use it in GitHub Desktop.
Save jakobo/05d82e84725de923499f4b79c20da5dd to your computer and use it in GitHub Desktop.
Connection Pooling for Redis
// Copyright 2020 Aibex, Inc <oss@aibex.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Redis from "ioredis";
import genericPool from "generic-pool";
const RedisPool = {};
RedisPool.defaultClient = (...o) => new Redis(...o);
RedisPool.create = (poolOptions = {}, ...ioredis) => {
const factory = {
create: () => {
if (typeof ioredis[0] === "function") {
return ioredis[0]();
}
return RedisPool.defaultClient(...ioredis);
},
destroy: (c) => {
if (typeof ioredis[1] === "function") {
return ioredis[1](c);
}
return c.quit();
},
};
const pool = genericPool.createPool(factory, poolOptions);
return new Proxy(
{},
{
// no setting
set: () => {},
// eslint-disable-next-line no-unused-vars
get: (target, prop, receiver) => {
// enable client.use(cb) for using a pooled resource
if (prop === "use") {
return async (fn) => {
const client = await pool.acquire();
await fn(client);
pool.release(client);
};
}
// enable client.instance() for a one-off instance
if (prop === "instance") {
return factory.create();
}
// all other calls are proxied ioredis items
// make all redis calls async, acquire a client, then call
const interceptor = async (...args) => {
const client = await pool.acquire();
const res = client[prop](...args);
pool.release(client);
return res;
};
return interceptor;
},
}
);
};
@jakobo
Copy link
Author

jakobo commented May 28, 2020

Redis Connection Pooler

Because sometimes, that's what you needed

Why?

I'll go straight to the Redis docs here:

While Redis commands tend to be very fast, some commands are designed to be blocking, meaning that they will not return an answer until certain conditions are met. For example, blocking reads on Streams (XREAD) will wait for new entries to get into the stream when used with the BLOCK option (without it, XREAD would immediately return with an empty result-set). Keep in mind that these operations block the client, not the server. Redis will still be able to respond to commands sent through other connections.

And if you are a fan of JavaScript, you're also scared of the phrase "designed to be blocking". You can't tie up your redis client while waiting for a blocking operating to resolve. That's why connection poolers exist in the first place.

What Makes This Special

  • Use all/every redis call including builtins and custom commands
  • get/set/etc automatically use the pool
  • pipeline/multi support via minimal surface API(use)

How

At the heart of the pool is an ES6 Proxy that exposes two custom properties: use and instance. Every other property results in a function, just like ioredis. These functions are wrapped in an interceptor that acquires a client, uses the client to call the requested method, releases the client, then returns the result. This is the magic that makes set, get, and others work without any knowledge of the pool object itself.

Usage

const client = RedisPool.create(defaultPoolOptions, ...ioredisOptions);
  • defaultPoolOptions - [object] any option provided to generic-pool can be provided here
  • ioredisOptions - [...variadic number | string | object | function] any options provided to the ioredis constructor can be used here. Additionally, you may pass a pair of functions in for creating/destroying pooled instances if you'd like to use Cluster, streaming, Sentinel, or others.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment