question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

New DB connection on every request?

See original GitHub issue

Hi @sandeepsuvit.

I was doing some stress tests as we prepare to go live, and maybe I did something wrong, but it seems like for every new request, it’s creating a new database connection

image
    TenancyModule.forRoot({
      tenantIdentifier: 'X-TENANT-ID',
      options: () => { },
      uri: (tenantId: string) => {
        console.log('connecting!?', tenantId);
        return process.env.TENANT_MONGO_DB_CONNECTION_STRING.replace(
          '{{TENANT_ID}}',
          tenantId,
        );
      },
    }),

image

I ran a script that calls a URL, the URL return a 500 code, which is okay. But wheneve r I ran the script, the connection to my MongoDB Atlas instance skyrockets.

Would you know why? I saw that it’s supposed to cache it: https://github.com/needle-innovision/nestjs-tenancy/issues/12. But now I’m puzzled, and trying to find the root cause of the problem.

Issue Analytics

  • State:open
  • Created 9 months ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
sandeepsuvitcommented, Dec 27, 2022

@raphaelarias @elmapaul apologies for replying late on this since I only work on this during my spare time. Also @raphaelarias regarding your query the connections are stored on a map and reused if found. Refer to this line in the code.

// Check if tenantId exist in the connection map
    const exists = connMap.has(tenantId);
    
    // Return the connection if exist
    if (exists) {
      const connection = connMap.get(tenantId) as Connection;

      if (moduleOptions.forceCreateCollections) {
        // For transactional support the Models/Collections has exist in the
        // tenant database, otherwise it will throw error
        await Promise.all(
          Object.entries(connection.models).map(([k, m]) =>
            m.createCollection(),
          ),
        );
      }

      return connection;
    }

    // Otherwise create a new connection
    const uri = await Promise.resolve(moduleOptions.uri(tenantId));
    // Connection options
    const connectionOptions: ConnectionOptions = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      ...moduleOptions.options(),
    };

    // Create the connection
    const connection = createConnection(uri, connectionOptions);

    // Attach connection to the models passed in the map
    modelDefMap.forEach(async (definition: any) => {
      const { name, schema, collection } = definition;

      const modelCreated: Model<unknown> = connection.model(
        name,
        schema,
        collection,
      );

      if (moduleOptions.forceCreateCollections) {
        // For transactional support the Models/Collections has exist in the
        // tenant database, otherwise it will throw error
        await modelCreated.createCollection();
      }
    });

    // Add the new connection to the map
    connMap.set(tenantId, connection);

    return connection;
0reactions
elmapaulcommented, Dec 26, 2022

@raphaelarias I really respect your concern, cz wondering as well how it will behave in prod mode with N users/connections. So pity, this library is not actively supported. No complains, just a thought.

Quick tip: you can easily wrap up your all messages in one with edit 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Should we open a new db connection for every new request
There is a basic connection pool in the database/sql package so it reuse database connections. So, you can open when you need and...
Read more >
Improve database performance with connection pooling
When a new request to access data from the backend service comes in, the pool manager checks if the pool contains any unused...
Read more >
Creating database connections - Do it once or for each query?
-1 The answer is rather misleading. Creating a connection per query is a very bad idea. What you probably mean is "retrieve a...
Read more >
Should I keep a database connection open to handle every ...
For example a database such as MongoDB. I doubt that it is unnecessary to open and close a connection for every request. So...
Read more >
Connection Strategies for Database Applications
A database connection is a physical communication pathway between a client process and a database instance. A database session is a logical entity...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found