Repository navigation
Description
What are you doing?
Assume $DATABASE_URL points to a real Postgres database.
const Sequelize = require('sequelize');
function main() {
const sequelize = new Sequelize(
process.env.DATABASE_URL,
{dialect: 'postgres', operatorsAliases: false}
);
return sequelize.query(`select 1`);
}
main();Full environment details and demo available at https://github.com/Vadskye/demo-sequelize.
What do you expect to happen?
The script should finish its execution 10 seconds after the query finishes, when the connection times out and all active connections have been closed. This was the behavior with Sequelize v3.
What is actually happening?
The script hangs indefinitely after the query finishes.
Script output with DEBUG=*
sequelize:pool pool created with max/min: 5/0, no replication +0mssequelize:connection:pg connection acquired +0ms
sequelize:sql:pg executing(default) : SHOW SERVER_VERSION +0ms
sequelize:sql:pg executed(default) : SHOW SERVER_VERSION +1ms
sequelize:connection:pg connection timeout +20ms
sequelize:connection:pg connection acquired +4ms
sequelize:pool connection acquired +62ms
Executing (default): select 1
sequelize:sql:pg executing(default) : select 1 +27ms
sequelize:sql:pg executed(default) : select 1 +1ms
sequelize:pool connection released +6ms
sequelize:connection:pg connection timeout +10s
sequelize:pool connection destroy +10s
Dialect: postgres
Dialect version: 6.4.2
Database version: 9.4
Sequelize version: 4.13.8
Tested with master branch: No; there is one commit to master since the last release, and it does not affect this issue.
Activity
hussainb commentedon Oct 20, 2017
Shouldn't this be of major concern.. Any timeline on the fix?
everthis commentedon Nov 15, 2017
Is there a way to exit the process automatically without
sequelize.close()?jjm340 commentedon Nov 24, 2017
+1
rsshilli commentedon Dec 15, 2017
We're on MySQL and just upgraded from Sequelize 3 to Sequelize 4. We're using Node 6.10.3 running inside of AWS Lambdas, and this ate up 2 days of our time to track down. Our Lambdas always timeout now, but used to respond immediately using Sequelize 3.
At the very least, the upgrade docs should mention that you need to call sequelize.close() at the end of every block of promises. Also, if sequelize.close() means I can't use the sequelize instance any more, you should also mention that Sequelize 4 can't really be used effectively in AWS Lambda.
igorescobar commentedon Jan 31, 2018
Also running sequelize 4 inside of a lambda and having major issues related the problem mentioned by @rsshilli
liviuignat commentedon Mar 20, 2018
How is this possible this is still open? This looks like a REALLY major issue in Sequelize.
igorescobar commentedon Mar 20, 2018
I had to migrate to MongoDB to be able to use any kind of persistence layer on AWS Lambda structure.
stevenking86 commentedon Jun 11, 2018
Do older versions of sequelize also have this issue?
rsshilli commentedon Jun 11, 2018
@stevenking86 No, they don't. Sequelize 3 works great on Lambda.
stevenking86 commentedon Jun 11, 2018
@rsshilli thanks, going to use Sequelize 3 then!
catamphetamine commentedon Aug 4, 2018
We have been having this issue too with Amazon Lambda.
We tried two workarounds for this.
The first one:
It does work.
But it's a very hacky approach and feels a bit like a ticking bomb.
The second approach we tried (which didn't work) is based on #7144 (comment)
_onProcessExitis a non-documented hidden function.In fact, originally is was called
onProcessExitbut then was renamed to_onProcessExitin5.0.0beta, perhaps to emphasize its undocumentedness.What
_onProcessExitdoes is:So one may as well replace its call with:
To protect the code from another
_onProcessExitmethod rename.This looked like it could work, and it did work for a single Lambda invocation: the lambda executed and returned the result, but if the user hit "Refresh" button in the web browser the lambda would throw an error:
pool is draining and cannot accept work.So, in the end, the "
dran()andclear()" workaround didn't work: after callingpool.drain()the pool seems to be unusable anymore so next time when the Lambda gets reused (next request comes shortly after the previous one) it throwspool is draining and cannot accept work.https://github.com/coopernurse/node-pool#draining
Commenting out
pool.drain()and leaving justpool.clear()didn't work — the Lamba just hangs in this case and timeouts as a result.I guess there's no way in Sequelize to make it work with Lambda properly then.
The only workaround is the unsafe
context.callbackWaitsForEmptyEventLoop = falsehack.AlastairTaft commentedon Sep 12, 2018
Also using this on aws lambda with postgres and found an issue in the code where the execution would end before the connection is closed. I've fixed it in this pull request.
Other things I did which may or may not help your use case:
evict: 0, handleDisconnects: false.await db.sequelize.close(), instead ranconst pool = db.sequelize.connectionManager.pool; await pool.drain(); await pool.clear();.databaseVersion: '9.6.6',which meant that it avoids an extra query to the database on every request to figure out what version is in use.And here's my monkey patch without having to run a modified version of sequelize
sushantdhiman commentedon Sep 13, 2018
Sorry for ignoring this issue for long time.
I know this is an important breaking change but Sequelize can't do anything here.
node-poolimplementation keeps the pool alive thus preventing clean shutdown. For exampleIn v2 version of
generic-poolprocess would have exited at 15th second, but in v3 it will keep pool alive. Apart from that I suspect pool has memory leak.Do you guys have any suggestion for alternative pooling library OR we can create a pooling system for Sequelize itself (may be based on v2 version of
generic-pool)Vadskye commentedon Sep 13, 2018
Thanks for the response! That difficulty makes sense - it's not immediately obvious to me how
node-poolwould differentiate "this application has ceased all work" from "no work happens to have been done within the past N seconds". Can Sequelize just downgrade tonode-poolv2?20 remaining items
hagen commentedon Mar 13, 2019
@robophil under this method, my Lambda handler would have the following set, just after entering the handler:
In this way, the Lambda doesn't bother waiting for the pool (of 1) to empty... as it never would empty.
I'm now using
sequelize@nextwhich includes a rewritten pool sequelize-pool that resolves that issue:, so have removed both the code you've quoted, and thecallbackWaitsForEmptyEventLoopflag. Much neater, and so farsequelize@next(v5) has been working very well in prod.If it wasn't clear, I'm only using Sequelize in AWS Lambda. This workaround won't/may not apply in traditional server-based applications, where you most likely do want pooling.
AlastairTaft commentedon Mar 13, 2019
@hagen Careful removing that
callbackWaitsForEmptyEventLoopflag as that means you won't be taking advantage of the pool when a container is reused. i.e. without it you will be waiting for all connections to close before the container is reused, effectively creating a new pool on every request.robophil commentedon Mar 13, 2019
Thanks for the response @hagen. I'm running this in a lambda also.
I'll give
sequelize@nexta try and see if closes properly withsequelize.close()hagen commentedon Mar 13, 2019
Thanks @AlastairTaft. I never went to prod with v4. Although I understood what you're noting isn't actually possible under Lambda, or at least can't be obtained unless you have fairly regular invocations?
My understanding runs as follows:
The minimum pool size is 1, and v4 will keep 1 connection alive always. That also means the event loop doesn't empty. Without explicitly ending or removing the pool Sequelize creates, your Lambda will run to timeout, even after you've called back - and you will be billed until that timeout. There's no way to end your billed Lambda execution time and keep your pool alive.
If your container is reused fairly shortly after one invocation, then you'd gain the advantages of an existing pool, but both of those invocations will run to timeout. So I believe there's perf gain, but it may end up costing you dollar bucks. That and your CloudWatch logs will be full of timeout errors.
There's also a method of using Dynamo to monitor open connections, but boy, that's really taking it next level.
That is my take away at least. I'd love to be corrected!
@robophil no need for
close()insequelize@next- it'll close itself once your queries have completed.AlastairTaft commentedon Mar 13, 2019
@hagen That's an interesting point about cost. I overlooked that, and the bug in v4 must be costing people a fair amount of $. We patched to version 5.
It is possible, I think containers are kept around for at least 5 minutes, so if you get some frequent traffic you can be making use of the same pool (so long as you don't wait for idle connections to close).
robophil commentedon Apr 11, 2019
Just spotted this http://docs.sequelizejs.com/manual/upgrade-to-v5.html#pooling. Thanks for the contribution everyone.
IndigoBee commentedon Apr 21, 2019
@robophil I feel like it's not really working because I still get memory leaks coming from sequelize after upgrading to v5
selected-pixel-jameson commentedon May 24, 2019
I'm not sure if I'm doing something incorrectly, but it seems as if my connections are not being closed based on the pool settings that I have.
I'm using the latest version of Sequelize 5 and my AWS Lambda function is using the async handler so I shouldn't need to use context.callbackWaitsForEmptyEventLoop = false.
These are my pool settings.
Yet for some reason the database connections in the RDS monitoring don't go down in accordance with the pool settings. They seem to just timeout when the Lambda is terminated after 5 minutes. Note the timeout on my lambda is 30 seconds. I believe the 5 minutes is the actual termination of how ever these are virtually spun up.
Here's graph depicting my connection counts. [https://cloudup.com/cg209VEwWCy] Note that the places where the connections are maintained is when NO requests are being made at all. It's hard to tell, but the steps going down happen every 5 minutes only. They never decrease any sooner. This causes significant issues if the maximum connections of the database is ever reached because all requests going forward for the next 5 minutes will just fail outright because the database has reached its maximum connections.
Any help or guidance with this would be greatly appreciated. Thank you!!
Vadskye commentedon May 24, 2019
Since this is closed ticket that was originally about the Sequelize v4 pooling issue, it might be better to create a new issue for specifically Sequelize v5 pool issues. Since v5 has a different pooling library, I would expect that any lingering issues would probably come from a different problem and need to be resolved differently.
TESTING: Remove shared.closeDb which is not needed any more after upg…
marcogrcr commentedon Aug 26, 2020
For people experiencing issues in AWS Lambda, I have created a pull request that documents how to properly configure
sequelizefor Lambda. Hopefully you'll be able to see it in https://sequelize.org/master/manual/aws-lambda.html once it gets merged. In the meantime, please check #12642 out and provide feedback if you find any inaccuracies or space for improvement.selected-pixel-jameson commentedon Dec 2, 2020
@marcogrcr First of all, thank you for posting your findings surrounding. I have implemented your suggestions from what I can tell. That being said, I run into an issue where once my database reaches the max connections and I start getting connection errors it appears as if the connections don't get closed within my lambda functions and will just persist open until the RDS instance, from what I can tell, decides to start shutting them down. Any suggestions??
marcogrcr commentedon Dec 3, 2020
@selected-pixel-jameson As per #12642, in theory, calling
await sequelize.connectionManager.close();should close all the underlying connections. If the Lambda function times out, returns before the connections are actually closed, Lambda service will "freeze" thenodejsprocess and the connection may not be closed until the process is "defrosted" by a new request.That being said, opening/closing a connection with every request is an expensive thing to do. You should use AWS RDS Proxy to mitigate the cost opening/closing connections with every request.
pankajtiwary commentedon Mar 10, 2021
Dear All, I am using Sequelize 5.22.3 and have found very strange problem. I am also using RDS Postgres as database.
Whenever, I add connection pool setting in my sequelize configuration, It opens of hundreds of connections and that goes till 3000 connections. I have read that, there is some bug in connection pool which was later resolved.
I am just wondering if anyone has got this earlier and any solution or work around?
Thanks in Advance.
pankajtiwary commentedon Jun 8, 2021
For me, the problem is resolved. It was a problem with AppDynamics NodeJS Agent, we were using. It was keeping the Sequelize connection live, even, If it used to be closed by Sequelize connection pool library. When I upgraded( or removed Appd completely) AppDynamics agent to latest version (21.40.0), problem went away.