I'm using pg in aws lambda. If I run a query it's running on first time. Then the second try it's giving above error.
Should I leave pool without end .
const { Pool }=require("pg");
const pool=new Pool({
host:"xyz.rds.amazonaws.com",
user:"sarath",
password:"abcd",
database:"company",
port:5432
});
Database(query, data) {
return new Promise((resolve, reject) => {
pool.query(query,data,(err,res)=>{
pool.end();
if(err) return reject(err);
return resolve(res);
});
});
}
Note: It's working as expected in my local machine.
Should I leave pool without end .
Yes. Only end the pool when you no longer intend to use it. pool.query also already returns a promise:
Database(query, data) {
return pool.query(query, data);
}
@charmander it's working fine with local machine. Not on the AWS Lambda. I tried without ending the pool but function exited with error
Task timed out after 10.01 seconds
@sarathjasrin You have to end the pool, but not before you鈥檙e done making queries. Do it after the last query.
@charmander I'm ending the pool after the query run.
The problem is using the lambda. I'm calling the lambda through the API Gateway. I'm getting the result at the first call from the second call it's giving the above error.
@charmander don't close the issue.
@sarathjasrin The error message says what's wrong:
"Cannot use a pool after calling end on the pool"
You can't reuse a pool after it has been closed (i.e. after calling the .end() function). You would need to recreate the pool and discard the old one.
The simplest way to deal with pooling in a Lambda is to not do it at all. Have your database interactions create their own connections and close them when they're done. You can't maintain a pool across freeze/thaw cycles anyway as the underlying TCP sockets would be closed.
If opening/closing the connections becomes a performance issue then look into setting up an external pool like pgbouncer.
just uncomment it: //pool.end();
I haven't tried this (I don't really use Lambda); but my guess would be that you could use the callbackWaitsForEmptyEventLoop: false setting on your Lambda and leave the pool open. This way the next request can benefit from the pool being available already (potentially even with a warm client) but Lambda can send the result without waiting for the client/pool to be released. Be careful that you're not doing any other background work through, as that could be aborted.
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
I confirm: callbackWaitsForEmptyEventLoop: false is the way to go.
Most helpful comment
just uncomment it: //pool.end();