Nodejs How should I use caching for this behavoir?

7 Views Asked by At

I have a connection string and I have to cache it. Why ? When I make a query call the first call takes 200ms because he connect, then all other do 20ms. If I not cache it all query calls take 200ms because he connects every time.

let cached = global.couchbase

if (!cached) {
  cached = global.couchbase = { conn: null }
}

async function createCouchbaseCluster() {
// return the cache when exists
  if (cached.conn) {
    return cached.conn
  }

    cached.conn = await couchbase.connect('xxx', {
      username: 'xxx',
      password: 'xxxxx',
    })
  

  return cached.conn
}

export async function connectToDatabase() {
  const cluster = await createCouchbaseCluster()
  const bucket = cluster.bucket('sf_bucket');
  const scope = bucket.scope('sf_scope');

  let dbConnection = {
    cluster,
    bucket,
    db,
  }

  return dbConnection;
}

server.ts

app.get("/products", async (req, res) => {
  const { db } = await connectToDatabase();
  try {
    const d = await db.query('SELECT click FROM products WHERE META().id = $1 LIMIT 1;', {
      parameters: ['products856648']
    });
      res.send(d);
  } catch (error) {
    console.error(error)
  }
})

Is there another solution/better solution to cache it or do this code better ? What happens when I have 10k users and all con are in cache ? Does it not slow my nodejs app ?

Another problem is the first execution is 200ms, the second 20ms and all others but after 1 min the first executing is again 140ms then again 20ms

0

There are 0 best solutions below