NodeJs & Redis singleton performance and optimization

Viewed 32

1- Is it good practice to use a single Redis instance (Singleton pattern) in the entire NodeJS app?.

2- Will this single Redis connection act as a bottleneck when the server receives more than 10K req/s or 100K req/s?

import { createClient, RedisClientType } from "redis";

class Redis {
  private static instance: Redis;
  private static client: RedisClientType;

  private constructor() {}

  public init(url: string) {
    Redis.client = createClient({ url });
    return Redis.client;
  }

  static getInstance() {
    if (!Redis.instance) Redis.instance = new Redis();
    return Redis.instance;
  }

  public getRedisClient() {
    return Redis.client;
  }
}

export default Redis.getInstance();
1 Answers

A good practice is to use the minimal hardware possible and have the maximum reliability. These two constrains should lead you to a happy medium where you are comfortable.

  1. Is it a serious problem if the cache is not reachable ?
  2. Is it a serious problem if the cache is deleted ?
  3. ...

You can use a single redis instance if it does not have to support more than ~100-200k op/s and does not have to be 100% reliable.

  1. You can have the data duplicated on the cold storage of the host if you want some kind of persistency.
  2. You can use swap to increase redis memory capabilities (only with NVMe, anything other yield very (very) poor performances).
Related