Skip to content

Option to close physical connections past a certain age #1810

Closed

Description

@FlorianRainer

I have the following Problem.
I have a WebApplication attached API called quite frequently, this will prevent the ConnectionPool to get all connection in idle state.

According the code here https://github.com/npgsql/npgsql/blob/dev/src/Npgsql/PoolManager.cs#L495 the IdleConnectorList works like a Stack, the latest used Connection (Last added to Idle) will be used as first connection if a new connection is needed.

This results in some realy long living connections (active for hours) even if Connection Idle Lifetime is set much lower.

The resulting problem in my case is some long running backend processes on the server with quite large memory usage (maybe caused by prepared statements, but not sure)

Is there any reason to use the last used connection first?
It would be nice to get the latest created connection in idle state if possible, this would improve the connection lifecycle, but i know its less performant then just picking from a stack.

An other solution could be a new optional connectionstring parameter Connection Max Lifetime, if connections expire this max value will not be returend from pool and get pruned with the next interval.

Do you see any sense in one of this changes, or is this a special case and i need to find a workaround?

Activity

  1. roji commented on Feb 13, 2018

    @roji
    Member

    Hi @FlorianRainer.

    What you describe is actually the way it works now - check out the docs. When a connection is idle for long enough in the pool, it is automatically pruned (i.e. closed) based on the parameters you specify in the connection string. In fact, that was the very reason for making the idle list a stack - you want to return the latest-used connection since that would keep your older connections in the idle list, and therefore make them eligible for pruning.

    The bad news, however, is that for the next version I've rewritten the pool to be lock-free, since the lock was causing contention is concurrent overloaded scenarios. This rewrite removes the stack structure, so although pruning is definitely still on there's no longer a use-oldest-connections-last principle, and pruning may become a bit less efficient. You can take a look at the new implementation if you want (not yet final).

    Am going to close but would be happy to continue the conversation!

  2. FlorianRainer commented on Feb 14, 2018

    @FlorianRainer
    ContributorAuthor

    Hi @roji

    Thanks for the answer, i have already checked the pooling configuration parameters in the docs, and the functionality. Your explanation to reuse the latest-used connection is clear for me. But the problem i described is a bit different.

    If there is a periodicaly called function (single threaded) who calls a relatively long running SQL statement, with a short timing interval, the pool will return the last connection from stack. This is every time the same connection, even if there are short queries fom an other thread between. This connection is the most used and longest living connection in the pool, and never gets long enougth in idle state to get pruned.

    For me the actual code doesn't have a use-oldest-connections-last principle it has a last-used-connection-first principle. The "oldest" connection is not even tracked cause the ReleaseTimestamp is updated on every connection release.

    But however, like you have told the rewritten pool is different. i have looked at the code https://github.com/npgsql/npgsql/blob/perf/src/Npgsql/PoolManager.cs and i realy like the approach to get idle connectors from a random array position. But in this case the ThreadId is the startindex in my case for a singlethreaded usage it will return the same connection as well.

    none then less i think the "correct order" inside the pool depends on the usecase, and its overcomplicated think about this. for this reason i want to return to the Connection Max Lifetime idea.

    I think it could be an interessting feature even for other users to have an option how "old" a connection should be at maximum. Because a fresh connection every x hours can have positive effects on postgres memory usage and even on performance. the postgres backend process related to a session / connection can grow a lot, and if it hits server configuration limits it can slow down.

    if you want i can provide a diff (or pull request) for a simple implementation of this feature based on the new code in https://github.com/npgsql/npgsql/blob/perf/src/Npgsql/PoolManager.cs

    Here a preview, to get feedback from you if this can make sense or not:

    void PruneIdleConnectors(object state)

    		void PruneIdleConnectors(object state)
    		{
    			var now = DateTime.UtcNow;
    			var idleLifetime = Settings.ConnectionIdleLifetime;
    			var maxLifetime = Settings.ConnectionMaxLifetime;
    
    			for (var i = 0; i < _idle.Length; i++)
    			{
    				if (Total <= _min)
    					return;
    
    				var connector = _idle[i];
    				if (connector == null)
    					continue;
    
    				var idleLifetimeExceeded = (now - connector.ReleaseTimestamp).TotalSeconds >= idleLifetime;
    				var maxLifetimeExceeded = maxLifetime > 0 && (now - connector.CreationTimestamp).TotalSeconds >= maxLifetime;
    
    				if (!idleLifetimeExceeded && !maxLifetimeExceeded)
    					continue;
    
    				if (Interlocked.CompareExchange(ref _idle[i], null, connector) == connector)
    					CloseConnector(connector);
    			}
    		}
    

    and add the CreationTimestamp property to the Connector Object and set it on first connect.
    by using the maxLifetime only if > 0 the default value can be 0 and it will not change anything.

    what do you think about this?

  3. changed the title [-]PoolManager: IdleConnectorList Push / Pop Logic question[/-] [+]Automatically close old connections[/+] on Feb 17, 2018
  4. roji commented on Feb 17, 2018

    @roji
    Member

    If there is a periodicaly called function (single threaded) who calls a relatively long running SQL statement, with a short timing interval, the pool will return the last connection from stack. This is every time the same connection, even if there are short queries fom an other thread between. This connection is the most used and longest living connection in the pool, and never gets long enougth in idle state to get pruned.

    For me the actual code doesn't have a use-oldest-connections-last principle it has a last-used-connection-first principle. The "oldest" connection is not even tracked cause the ReleaseTimestamp is updated on every connection release.

    I think I understand - you're looking for "max connection lifetime", rather than a "max idle time". I think this option exists in SQL Server, see https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx under "Connection Lifetime". It's a very different feature indeed - when I say "use-oldest-connections-last", I'm referring to their last release times, rather than to their original physical creation time. See below for comments on the "Connection lifetime" feature.

    The idea to prune idle connections is simply that if your application used 100 connections at some point, but load decreased and is now only at 10, the other 90 should be pruned. This allows your pool to scale up and down with demand, and avoid overloading the database with useless idle connection.

    But however, like you have told the rewritten pool is different. i have looked at the code https://github.com/npgsql/npgsql/blob/perf/src/Npgsql/PoolManager.cs and i realy like the approach to get idle connectors from a random array position. But in this case the ThreadId is the startindex in my case for a singlethreaded usage it will return the same connection as well.

    That's right. Making the search start in a "random", ThreadId-dependent position was a way to actually provide something close to "thread-local storage", but without the performance penalty. The fact that the same connection is returned for the same thread is actually a good feature of this, IMHO.

    I think it could be an interessting feature even for other users to have an option how "old" a connection should be at maximum. Because a fresh connection every x hours can have positive effects on postgres memory usage and even on performance. the postgres backend process related to a session / connection can grow a lot, and if it hits server configuration limits it can slow down.

    I asked myself this question back when I redid the pool, and I have to say I didn't really understand this. Do you have any references showing that simply killing old connections is somehow better for memory/performance? Why do you say that the backend process can grow a lot? This would either imply a leak inside PostgreSQL (highly unlikely) or bad application behavior (e.g. endlessly preparing statements without deallocating them, or some similar leaky behavior). AFAIK, as long as connection state is managed properly and nothing silly is done by the application, it should be completely fine to hold a PostgreSQL physical connection for as long as you want.

    If you can show a valid reason why killing old connections improves performance, then we can definitely look at adding this feature to the pool implementation. I've renamed this issue and reopened to continue the conversation.

    FYI, in https://github.com/dotnet/corefx/issues/26714 I propose a pluggable connection pool design which would allow users to choose which pool implementation they desire, rather than to lock them into whatever implementation the provider has. This would allow pools with different feature-sets for different scenarios, and could help this kind of request.

  5. reopened this on Feb 17, 2018
  6. FlorianRainer commented on Feb 20, 2018

    @FlorianRainer
    ContributorAuthor

    Hi @roji
    Thanks for your answers.

    its a bit difficult for me to point on the concrete issue, because i think its related to more then only one fact.

    i'm using ubuntu with postgres 9.6, npgsql and dapper.
    The Npgsql part of the application is realy basic, nothing special except using enums.

    the server config is almost standard as well, but im using a lot of connections, because of some legacy reasons i need a lot of different databases. (~70+ perhaps)

    there is a c# scheduler running for every of this databases, it executes a few different queries on a large schema, and tables with more then 100.000 rows, processes updates and so on.

    some time ago my postgres processes (1x per connection / session) are growing vs 100MB each, maybe related to large sorting or temporary table usage.

    100MB * 150 threads = 15GB was a way to much.
    As workaround i have decided to restart the scheduler application every 2 hours, not every 2 days and now all ~150 processes together are using not more then 600MB

    the queries are static with paramerterized sql, nothing special.

    the performance drop comes if the postgres processes begin to use the swap.

    sorry i can't tell you more, atm.

    BTW the 'pluggable connection pool design' is a nice idea.

  7. roji commented on Feb 21, 2018

    @roji
    Member

    Hmm, OK, thanks for the additional information. Sounds like something, somewhere is leaking. Out of curiousity, do you occasionally do a DISCARD ALL, which frees up most/all session-based resources (like temporary tables, prepared statement)? Npgsql issues this by default when you close a pooled connection (unless you specify No Reset on Close), but maybe in your application you're not pooling in that particular scenario or something.

    If you're closing and opening pooled connections (and thus doing DISCARD ALL) and you're still seeing huge processes, it's definitely worth investigating. Also, make sure you're looking at actual used memory and not, say, virtual memory (which corresponds more to how much was used by the process at some point in the past, and not how much is being used right now).

    I can definitely see this being an opt-in option, especially once the pluggable connection pool design is implemented. I'll keep this open to track that.

    Note that you can work around this by clearing the pool occasionally - this will get rid of all idle connections and mark busy ones to be physically closed when they're next returned to the pool.

  8. changed the title [-]Automatically close old connections[/-] [+]Option to close old physical connections (anti-leak measure)[/+] on Feb 21, 2018
  9. FlorianRainer commented on Mar 7, 2018

    @FlorianRainer
    ContributorAuthor

    Sorry for the delay, i was out of office for 2 weeks.

    I use the default behaviour of NpgSQL, the DISCARD ALL will be called after each block of queries (max every 10 seconds), and i use pooling with the default npgsql settings.

    To provide some more informations.
    I have tested this with NpgSql 3.1.9 on .net full framework (4.6) and Postgres 9.6

    The server configuration is the default settings with some changes on memory limit suggested by pgtune
    one more thing i use pg_stat_statements shared_preload_libraries = 'pg_stat_statements'
    i know this will rise the memory usage but as far as i know only for the postgres main process and not for the backend processes.

    I will do some tests to check if the problem still exists, i have a production ready version of the application based on .net core 2.0 with npgsql 3.2.6 and it should be possible to rise the the restart time to 2-3 days and i will monitor the memory usage of the backend processes.

    i will try to test this in the next few days and i keep you up to date.

    I have already looked at the NpgsqlConnection.ClearAllPools() method, and it would be clearly better then restarting the application. but its not optimal, because all connections are dropped, even if they are only a few seconds old. For this reason i would like to drop only connections older than x time (one day in may case)

  10. FlorianRainer commented on Mar 7, 2018

    @FlorianRainer
    ContributorAuthor

    Update: i have found a similar question on postgresql.org it seems to be a "internal dictionary on objects and queries" can grow over time if we are selecting / working on large datasets and variables. Both is true for my case.

    the suggested answer was to use "shorter lived connections", and i think it could be a overall benefit to not use the same connection for days.

    https://www.postgresql.org/message-id/401084E5E73F4241A44F3C9E6FD794280378ED03B7%40exch-01

    Edit: Similar problem here, seems to be a little bit different testcase, but same kind of effect and same result. The same suggestion here to not use long living connections https://stackoverflow.com/questions/5587830/postgresql-backend-process-high-memory-usage-issue

  11. FlorianRainer commented on Mar 13, 2018

    @FlorianRainer
    ContributorAuthor

    I have logged the behaviour for some days, and the problem still exists.

    i have got some connections up for ~2 days but not all of those connections have this behaviour.
    all of those applications are executing the same code as multi tenant. The only difference is teh database it self (not structure, only data)
    my next observation was: only the connections are getting big where in some of the tables are a lot more rows then normaly will be, for this reason i think its a combination of usage of temporary tables on large results with sorting.

    but none then less its a known issue of postgres.

    i have monitored the reserved memory and shared memory, and those big backend processes are using a "normal" ammount of shared memory (like the smaller backend processes are doing as well) but the total memory is much larger. this will lead me to the conclusion: The private process memory grows to much / has a leak in this case.

    Some values for you:
    Big backend Process: VIRT: 2.2GB RES: 1.9GB SHR: 1.01GB => PRIVATE: 890MB
    Small backend Process: VIRT: 1.4GB RES: 200MB SHR: 150MB => PRIVATE: 50MB
    Both are running for ~ 2 Days

    But back to topic, none then less i think a opt in feature for connection max lifetime would be a usefull feature, because like described in the 2 links uppon it seems to be a common postgres problem, and it not seems like anyone on the postgres team has worked on this in the last years. so it may have a low priority.

  12. 19 remaining items

  13. FlorianRainer commented on Dec 13, 2019

    @FlorianRainer
    ContributorAuthor

    @NinoFloris you're talking about webserver clusters behind a proxy (LB) with one postgres database server.

    the stuff uppon is more like one or many (web)application connecting to many postgres servers.
    at least round robin DNS is stuff for realy largs scale (cloud ecc.) but can be usefull if you have for example a master / master replication without pgbouncer even in local network.

    but your'e right, none of both configurations will resolve your problem.

  14. changed the title [-]Option to close old physical connections (anti-leak measure)[/-] [+]Option to close physical connections past a certain age[/+] on Dec 28, 2019
  15. coryflucas commented on Feb 10, 2020

    @coryflucas

    Just wanted to chime in with a use case for this. With AWS Aurora PostgreSQL you can setup a cluster to automatically scale up additional reader nodes based on load/number of connections. Traffic is load balanced across the nodes using something like round robin DNS, and this feature would provide a way to eventually migrate connections over to it.

  16. roji commented on Feb 11, 2020

    @roji
    Member

    @coryflucas yeah, that's similar to the use-cases detailed above. We'll definitely try to get this done for the next version.

  17. igremmerlb commented on Jun 8, 2020

    @igremmerlb

    I wanted to chime in support for this as well. We have a distributed database across 2 datacenters. When the database node in the first datacenter is down then the load balancers will point the applications at the secondary database instance in the other datacenter, which is slower across the WAN and uses up bandwidth. It works for short term, but we need it to give up that connection and go back to the primary when it is back up. We use the ConnectionLifetime with MySQL very successfully for this situation. We have a general policy of having no connections last more than a few minutes so the load balancers can spread things out appropriately. Thanks for working on this. Much appreciated.

  18. self-assigned this
    on Sep 8, 2020
  19. linked a pull request that will close this issueAdd ConnectionMaxLifetime Feature #1856on Sep 8, 2020
  20. linked a pull request that will close this issueAdd ConnectionMaxLifetime Feature for V4 #2068on Sep 8, 2020
  21. linked a pull request that will close this issueImplement connection lifetime #3133on Sep 8, 2020
  22. roji commented on Sep 8, 2020

    @roji
    Member

    A new PR is out for this, based on @FlorianRainer's excellent previous work - this should make it for the upcoming 5.0 release.

  23. added a commit that references this issue on Sep 18, 2020
    264faa5
  24. added a commit that references this issue on Sep 18, 2020
    4617ce0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions