Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Use dynamically created Sequelize Instance in NestJS

In order to allow multi tenancy I'm creating request scoped instances of Sequelize depending on a tenant's subdomain, e.g. team1.example.com creates an instance accessing database schema "team1". Researching this topic lead me to the example of async configuration for Sequelize using a config service, which looks like this:

import { Inject, Injectable, Scope, Request } from "@nestjs/common";
import { REQUEST } from "@nestjs/core";
import { SequelizeModuleOptions, SequelizeOptionsFactory} from "@nestjs/sequelize";

@Injectable({scope:Scope.REQUEST})
export class SequelizeConfigService implements SequelizeOptionsFactory {
    
    constructor(@Inject(REQUEST) private readonly request:Request){}

    createSequelizeOptions(): SequelizeModuleOptions {

      let domain:string[]
      let database='default'

      domain=this.request['headers']['host'].split('.')

      if(domain[0]!='localhost' && domain[0]!='127' && domain[0]!='www' && domain.length >2){
        database=domain[0]
      }

    return {
        dialect: 'mysql',
        host: 'localhost',
        port: 3306,
        username: 'localuser',
        password: 'supersecretpassword',
        database: database,
        autoLoadModels: true,
        synchronize: true,
    };
  }
}

The configuration is then used when importing Sequelize in a module:

@Module({
    imports: [
        SequelizeModule.forRootAsync({
          useClass:SequelizeConfigService
        }),
        SequelizeModule.forFeature([User])
      ],
      controllers: [UserController],
      providers: [UserService],
})
export class UserModule {}

This works fine but this mechanism creates a new instance (and thus a connection) with every request which will lead to performance issues eventually.

Is there a way to store Sequelize instances / connections which have already been created for a tenant to re-use them for subsequent requests?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!