Skip to content

Connection cleanup should happen asynchronously #268

Closed

Description

@Emill

I'm trying to performance test Entity Framework using Wireshark and notice something annoying.

Between each query, there are two extra unneeded roundtrips to the server.
The first one:

DISCARD ALL

The other one:

SET extra_float_digits=3;
SET ssl_renegotiation_limit=0;
select 'Npgsql111141'

The first one is for "closing" a connection in the connection pool and the next one opens the connection in the connection pool again.

For some reason, Microsoft decided that in EF a new connection is used in each query, so it is more important to have low connection pool overhead for EF applications than other applications that uses a single connection for many queries.

I found that the select query is for pinging the server to see if the connection still is available. When I compared with Entity Framework/SQL Server, there are no extra packets sent to the db backend except the single original query when a connection in the pool is reused. So while EF/Npgsql needs three round trips to execute a single query, EF/SQL Server only needs only one. That will probably be a huge performance difference if the db server is far located from the client.

Indeed, Microsoft thinks it's not worth it to check if a connection works before using it, for performance reasons. See ADO.NET documentation: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx under Removing Connections.

The connection pooler removes a connection from the pool after it has been idle for approximately 4-8 minutes, or if the pooler detects that the connection with the server has been severed. Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid. Invalid connections are removed from the connection pool only when they are closed or reclaimed.

If a connection exists to a server that has disappeared, this connection can be drawn from the pool even if the connection pooler has not detected the severed connection and marked it as invalid. This is the case because the overhead of checking that the connection is still valid would eliminate the benefits of having a pooler by causing another round trip to the server to occur. When this occurs, the first attempt to use the connection will detect that the connection has been severed, and an exception is thrown.

There are some discussion in #74 (comment) that an extra query requires 1 ms. That might be the case if the db server is on the same machine as the client, but not if the db server is on a machine far away. If you still think it is important to ping the server to see if it's active, maybe have a timestamp when the last packet arrived. If it is less than some seconds (or maybe minutes) after that when the connection is reused, it can be considered healthy and no need to ping, otherwise send a ping message.

I assume the DISCARD ALL and SET queries are meant to reset the state if the user has sent queries that changes settings. I also looked how SQL Server does this, they have a flag bit in their packet header RESETCONNECTION that is made for connection pooling purposes:

"This signals the server to clean up the environment state of the connection back to the default environment setting, effectively simulating a logout and a subsequent login, and provides server support for connection pooling."

If there is no such flag for the postgresql protocol format, maybe it's possible to track these kind of changes instead and only run these two round trips if they are needed? I notice that for each completed query, there is a response message (CompletedResponse) which also includes a string containing what kind of query it was (SELECT, INSERT, SET, DISCARD ALL etc.). Now that string is mostly discarded, check https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlState.cs#L415. I think a better way would be to see if it was a SET, then put a flag in the connection that this one should run a DISCARD ALL when it's put back to the pool. If there wasn't any SET command, DISCARD ALL and the restore query don't have to run. Maybe there are more kind of commands that must be caught, such as PREPARE (to make the name available again). Maybe also DECLARE, LISTEN, CREATE TABLE (to discard temporary tables). What do you think about something like that? I don't really know about "Advisory locks". And what will happen if a connection is closed that has a pending transaction?:

I tried

db.Open();
Npgsql.NpgsqlCommand cmd = new Npgsql.NpgsqlCommand("begin", db);
cmd.ExecuteNonQuery();
db.Close();

and the PostgreSQL backend sent an error "DISCARD ALL cannot run inside a transaction block". But that was catched and discarded by https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlConnectorPool.cs#L516 and the connection was terminated and a new was created. I notice that in the response packets from db backend, there is a status flag telling that a transaction is going on. However, that information is currently discarded: https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlState.BackendResponse.cs#L304. Upon releasing a connection, the flag sent in the latest response packet should be checked, and if it is T, it should execute a rollback (and maybe throw an exception telling that there is an uncommitted transaction?).

One last thing: Shouldn't statement_timeout also be reset after DISCARD ALL?

Activity

  1. franciscojunior commented on Jul 8, 2014

    @franciscojunior
    Member

    Thank you for your thoroughly analysis of Npgsql, @Emill ! I'll make my observations inline.

    I found that the select query is for pinging the server to see if the connection still is available.

    Correct. A first we used a simple "select 1" but later we noticed that this could be confused with a garbage value in the buffer of the connection which could lead us to believe it was a valid connection when in fact it wasn't. (Indeed, we received a bug report about exactly that.) Then I decided to use two random values to check that.

    If you still think it is important to ping the server to see if it's active, maybe have a timestamp when the last packet arrived. If it is less than some seconds (or maybe minutes) after that when the connection is reused, it can be considered healthy and no need to ping, otherwise send a ping message.

    I think this is a very nice idea.
    Maybe we could add a connectionstring setting where the user can specify after how many idle seconds Npgsql should check if the connection is ok. This way, if she doesn't want Npgsql to check the connection, she can specify a value of 9999, or we can even document that a value of 0 or -1 would mean Npgsql shouldn't ping the connection?

    I assume the DISCARD ALL and SET queries are meant to reset the state if the user has sent queries that changes settings.

    Correct.

    I also looked how SQL Server does this, they have a flag bit in their packet header RESETCONNECTION that is made for connection pooling purposes:

    As far as I know, Postgresql doesn't have something like that at the protocol level.

    think a better way would be to see if it was a SET, then put a flag in the connection that this one should run a DISCARD ALL when it's put back to the pool. If there wasn't any SET command, DISCARD ALL and the restore query don't have to run. Maybe there are more kind of commands that must be caught, such as PREPARE (to make the name available again). Maybe also DECLARE, LISTEN, CREATE TABLE (to discard temporary tables). What do you think about something like that?

    I need to think more about that. Right now, the issue I'm thinking about is how we would balance the time spent and the performance impact this would have checking for those command types ( as we would need to do a search string for each completedresponse throughout the connection lifetime ) and the time needed to send and execute the discard all command.

    But maybe the most important (and more visible to the user) as you said is the time spent in the round trip of the discard all command ( and in some cases, like #158 illustrates, it takes even more ), and all my concern about time spent in checking the completedresponse strings is no such big deal.

    Maybe we could solve that by doing the connection cleanup and returning to the pool in asynchronously? This would return control back immediately to the user and she would be able to use another connection from the pool when needed? A background thread would do all the hard work of releasing all the resources?

    But that was catched and discarded by https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlConnectorPool.cs#L516 and the connection was terminated and a new was created. I notice that in the response packets from db backend, there is a status flag telling that a transaction is going on. However, that information is currently discarded: https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlState.BackendResponse.cs#L304. Upon releasing a connection, the flag sent in the latest response packet should be checked, and if it is T, it should execute a rollback (and maybe throw an exception telling that there is an uncommitted transaction?).

    Nice catch!

    I agree with you. I think Npgsql should execute a rollback and return the connection to the pool.
    I don't think we should thrown an exception though. As the user asked the connection to be closed, I don't think she would expect an exception to be thrown.

    SqlConnection.Close() method documentation (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close%28v=vs.110%29.aspx) says it does exactly that. It rollbacks any pending transaction. Although it says that it may also throw exception, but doesn't say when. The exception documentation seems to be copied from the open method: The connection-level error that occurred while opening the connection Opening? `:)

    One last thing: Shouldn't statement_timeout also be reset after DISCARD ALL?

    Nice catch!

    Although Npgsql handles the reset of the statement_timeout if needed, this only works as long as the user doesn't change the timeout manually with a set command. :)

    There is a lot of work to do in Npgsql!

    Thank you very much again for your comments, @Emill. They help us to take Npgsql to another level.

  2. Emill commented on Jul 8, 2014

    @Emill
    ContributorAuthor

    Hi again

    I think this is a very nice idea.
    Maybe we could add a connectionstring setting where the user can specify after how many idle seconds Npgsql should check if the connection is ok. This way, if she doesn't want Npgsql to check the connection, she can specify a value of 9999, or we can even document that a value of 0 or -1 would mean Npgsql shouldn't ping the connection?

    Sounds good.

    But maybe the most important (and more visible to the user) as you said is the time spent in the round trip of the discard all command ( and in some cases, like #158 illustrates, it takes even more ), and all my concern about time spent in checking the completedresponse strings is no such big deal.

    Correct. To match a string of about 3-12 characters should be negligible (takes some nanoseconds on a GHz-processor?) to the time spent even sending that tcp packet that contains this response. It can be done in linear time using a Trie/DFA if one wants to match against many strings at once ;)

    Are there more than these seven commands that needs a DISCARD ALL + SET to happen at close + reopen?

    SET
    DISCARD ...
    RESET ...
    CREATE TABLE
    PREPARE
    LISTEN
    DECLARE
    

    I'm worried about what happens if a user includes pg_advisory_lock(...) in a sql query which is then never unlocked. It seems hard to catch this without having to search through the sql query to find out if these kind of locks are used :/
    Maybe include an option in the connection string to ignore proper release of these kind of locks (which either means the user has to explicitly release the advisory locks, or use the option in the connection string that always runs a DISCARD ALL)? If so, that option should be on by default in the DDEX connection wizard for Entity Framework, since you can't use advisory locks anyway in EF because sessions are always closed and reopened between each query. I really think it's worth to try to eliminate these two roundtrips, especially for Entity Framework...

    Maybe we could solve that by doing the connection cleanup and returning to the pool in asynchronously? This would return control back immediately to the user and she would be able to use another connection from the pool when needed? A background thread would do all the hard work of releasing all the resources?

    That can probably be done in addition, but then that connection won't be immediately available right after it is closed, which means a new connection must be opened, which might also degrade performance (or just wait until the discard and restore commands are done, but then we're back where we started). But if there are unused ready-to-use connections in the pool, then it's probably great ;)

    One last thing: Shouldn't statement_timeout also be reset after DISCARD ALL?

    Nice catch!

    Although Npgsql handles the reset of the statement_timeout if needed, this only works as long as the user doesn't change the timeout manually with a set command. :)

    The problem is that the timeout value the user specified in the connection string will only be used by the db backend the first time the connection is used in the pool. After executing DISCARD ALL, the timeout will be reset to PostgreSQL's default value. So next time there will be no timeout.

  3. franciscojunior commented on Jul 9, 2014

    @franciscojunior
    Member

    Sounds good.

    Great!

    Correct. To match a string of about 3-12 characters should be negligible (takes some nanoseconds on a GHz-processor?) to the time spent even sending that tcp packet that contains this response. It can be done in linear time using a Trie/DFA if one wants to match against many strings at once ;)

    Agreed. We can make some performance tests to measure how much impact this would have.

    Are there more than these seven commands that needs a DISCARD ALL + SET to happen at close + reopen?

    I think you have get them all.

    I'm worried about what happens if a user includes pg_advisory_lock(...) in a sql query which is then never unlocked. It seems hard to catch this without having to search through the sql query to find out if these kind of locks are used :/

    I think this is a legitimate worry but I'm almost sure no Npgsql user uses this feature because before having discard all support, Npgsql used to send only unlisten * to reset a connection and we didn't have any problem.

    Maybe include an option in the connection string to ignore proper release of these kind of locks (which either means the user has to explicitly release the advisory locks, or use the option in the connection string that always runs a DISCARD ALL)? If so, that option should be on by default in the DDEX connection wizard for Entity Framework, since you can't use advisory locks anyway in EF because sessions are always closed and reopened between each query. I really think it's worth to try to eliminate these two roundtrips, especially for Entity Framework...

    I agree with you that we need to remove those unecessary roundtrips. But I'm concerned we can end up adding a lot of complexity because of it.

    I was thinking about another approach. What if we find a way to send the discard all and initialization queries when the user sends the first request through the connection? I think that as the user is already sending a query, we wouldn't be adding any tcp overhead.

    Or maybe when the connection is being terminated?

    Today we have queries sent when the connection is terminated and when the connection is open. By merging all the commands to be send at once, we could eliminate a lot of tcp overhead. Together with async support which we are already discussing in #121 , we could get the idea of having the initialization being done in another thread for free :)

    That can probably be done in addition, but then that connection won't be immediately available right after it is closed, which means a new connection must be opened, which might also degrade performance (or just wait until the discard and restore commands are done, but then we're back where we started). But if there are unused ready-to-use connections in the pool, then it's probably great ;)

    I think that almost 100% of the time there will be more than one ready-to-use connection in the pool. Also, there is a parameter in the connection string MinPoolSize which allows the user to specify how many connections she wants to be available at least in the pool.

    We would need to make more performance tests to check the impact of such idea would have to connection pool intensive usage scenarios.

    The problem is that the timeout value the user specified in the connection string will only be used by the db backend the first time the connection is used in the pool. After executing DISCARD ALL, the timeout will be reset to PostgreSQL's default value. So next time there will be no timeout.

    Agreed. We would need to specify the timeout in our initial queries too.

  4. roji commented on Jul 9, 2014

    @roji
    Member

    @Emill and @franciscojunior, sorry to jump in in the middle. I also don't know EF very well.

    @Emill, it seems odd (to say the least) that in Entity Framework each query uses a new connection, are you sure this isn't an inefficiency in our implementation or something? Do you see the same thing happening when doing EF with MSSQL? According to my understand this pattern in this article is supposed to be used when performance is an issue and you want to maintain an open connection: http://msdn.microsoft.com/en-us/library/vstudio/bb738701(v=vs.100).aspx?

    Even if the close/open cycle is required, doesn't it make sense to simply move all the roundtrips to the close, rather than performing logic at the open? Connections would thus close in the background in their spare time, and some other connection would be immediately returned from the connection pool to EF?

  5. Emill commented on Jul 9, 2014

    @Emill
    ContributorAuthor

    Hi @roji. Closing/opening connection is built into EF and is not about db provider inefficiency. From http://msdn.microsoft.com/en-us/library/vstudio/bb896325(v=vs.100).aspx: "The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete."
    Since there is no extra packets sent for closing/opening a connection in MS SQL, Microsoft probably thought that didn't matter that much.

    I didn't know about http://msdn.microsoft.com/en-us/library/vstudio/bb738701(v=vs.100).aspx, but I tested that and it did the trick :)
    However, since most people don't know about it (at least I think so) I think it's still a good idea to try to minimize roundtrips. Also, even when the db context is created, a new connection is taken from the pool and now require one extra packet when opening and one when closing, which still means worse performance.

    Today we have queries sent when the connection is terminated and when the connection is open. By merging all the commands to be send at once, we could eliminate a lot of tcp overhead.

    I was thinking about another approach. What if we find a way to send the discard all and initialization queries when the user sends the first request through the connection? I think that as the user is already sending a query, we wouldn't be adding any tcp overhead.

    If multiple queries can be sent (and returned) in one single tcp packet (and one return packet), that would be great. It would probably be a good idea to prepend them to the first query for a connection. As mentioned in #74 (comment), a DISCARD ALL command cannot be sent in a multi-statement for some odd reason...

    A problem now (at least in the non-async implementation) is that while waiting for the response for the DISCARD ALL command, the thread is blocked, as it is executed by ExecuteBlind (https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlCommand.PrepareExecute.cs#L71). So the SET queries are not run until the result has been received (and discarded). The SET queries (that are sent together with the "ping" message) also blocks the thread by waiting for the response, so the user's query will also be delayed until the response is received. This means we have two extra roundtrips.

    I agree with you that we need to remove those unecessary roundtrips. But I'm concerned we can end up adding a lot of complexity because of it.

    With async it's probably easier to implement sending multiple commands and ignore the result than it is with sync. I think the method with checking result commands doesn't need to be that complex. First, some strings must be matched, a flag in the connection object must be set if a problematic command was run, and upon disconnect/connect, simply check if the flag is set or not. If it's set, run DISCARD ALL/SET and if not, run nothing.

  6. Emill commented on Jul 10, 2014

    @Emill
    ContributorAuthor

    Hi again. I tried to send the DISCARD ALL/SET queries after the connection has been re-opened, but I don't flush or wait for the result. I have a counter that counts how many response packages should be discarded later. That seems to work :)

    I uploaded my code to Emill@462a5f4, please check it out.

    In Wireshark, I see that all queries are sent in the same packet to the server. However, the server responses with three different packets. I don't think it matters so much because we're only waiting for the last one.

    I only tested for db backend 9.3.
    The only test case that failed was NpgsqlErrorRepro2 in ConnectionTests. It seems to use LargeObjectManager which uses a custom parser for the protocol (Fastpath)?

    However, it can still be improved by checking if a discard/set have to be done at all ;)

  7. roji commented on Jul 10, 2014

    @roji
    Member

    @Emill, thanks for all the clarifications! Everything seems to make sense.

    I admit I'm a bit afraid of parsing command texts for the purposes of determining whether the DISCARD ALL/SET queries are needed, mainly because it seems a bit brittle. Are we sure we know about all the Postgresql commands that could have side-effects (which would need to be reset)? If tomorrow Postgresql add a new command, we would have to somehow track that and add it...

    But I agree that synchronously blocking the thread every time an EF query is performed is unacceptable. I'm actively working on async support in #121, and as you said asynchronously closing would make this go away without the brittleness of the parsing approach.

    Do you think it's acceptable to defer this issue until async is implemented and handle it that way?

  8. Emill commented on Jul 10, 2014

    @Emill
    ContributorAuthor

    HI @roji. As I noticed in Emill@462a5f4, it is possible to remove the roundtrips while still executing the commands, so doing it this way or the async way will solve the problem with unneeded roundtrips, so the string matching method is probably overkill and might as you say be troublesome if PostgreSQL one day adds a new command.

  9. roji commented on Jul 10, 2014

    @roji
    Member

    Great. One comment though: in your commit it seems that you execute the DISCARD and friends, and don't wait for the responses. Unless I'm mistaken, that means that you return the connection to the pool although it hasn't been properly "reset" yet, right? In other words, in an extreme situation someone requesting a connection could get a connection that is in the middle of these commands?

    IMHO the bullet-proof way to handle this would be to asynchronously execute the reset commands, and only when these complete, return them to the connection pool...

  10. Emill commented on Jul 10, 2014

    @Emill
    ContributorAuthor

    The connection is not properly resest now either completely. The SET queries are run in the IsValid method, which is run when the connection is taken out from the pool. So even now all available connectors in the pool are "in the middle of the commands".

    In my attempt, also the discard command is deferred until the connection is opened again.

  11. roji commented on Jul 10, 2014

    @roji
    Member

    OK. I guess this needs a closer look.

    I'll look into this after making progress on #121, let's keep this open in the meantime. For EF performance, I suggest using the method described in http://msdn.microsoft.com/en-us/library/vstudio/bb738701(v=vs.100).aspx

  12. self-assigned this
    on Jul 10, 2014
  13. franciscojunior commented on Jul 10, 2014

    @franciscojunior
    Member

    Even if the close/open cycle is required, doesn't it make sense to simply move all the roundtrips to the close, rather than performing logic at the open? Connections would thus close in the background in their spare time, and some other connection would be immediately returned from the connection pool to EF?

    My idea was to use the timing the user would send her first query to send those initialization queries too and avoid roundtrips. But I also think it would be cleaner and easier to understand if the cleanup is done in the close.

    If multiple queries can be sent (and returned) in one single tcp packet (and one return packet), that would be great. It would probably be a good idea to prepend them to the first query for a connection. As mentioned in #74 (comment), a DISCARD ALL command cannot be sent in a multi-statement for some odd reason...

    Hmmmmm, maybe Postgresql wants to make sure that the client only send more commands after the server is properly clean and the client received the response message about that.

    A problem now (at least in the non-async implementation) is that while waiting for the response for the DISCARD ALL command, the thread is blocked, as it is executed by ExecuteBlind (https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlCommand.PrepareExecute.cs#L71). So the SET queries are not run until the result has been received (and discarded). The SET queries (that are sent together with the "ping" message) also blocks the thread by waiting for the response, so the user's query will also be delayed until the response is received. This means we have two extra roundtrips.

    Yes. Sending those reset and initialization queries would cause a blocking of the first client query. :(

    With async it's probably easier to implement sending multiple commands and ignore the result than it is with sync. I think the method with checking result commands doesn't need to be that complex. First, some strings must be matched, a flag in the connection object must be set if a problematic command was run, and upon disconnect/connect, simply check if the flag is set or not. If it's set, run DISCARD ALL/SET and if not, run nothing.

    I see. I'm reviewing your patch.

    Hi again. I tried to send the DISCARD ALL/SET queries after the connection has been re-opened, but I don't flush or wait for the result. I have a counter that counts how many response packages should be discarded later. That seems to work :)

    Hmmmmm, I saw your patch. I noticed you introduced a custom path to make the code return faster and don't block. I think this blocking issue could be solved in another place instead of the protocol handling code.

    I only tested for db backend 9.3.
    The only test case that failed was NpgsqlErrorRepro2 in ConnectionTests. It seems to use LargeObjectManager which uses a custom parser for the protocol (Fastpath)?

    Yes. Fastpath is another way to talk to postgresql. This code was contributed as a port of the Java version. It is kind of a shortcut in the normal postgresql protocol to provide a faster way to insert and retrieve a large quantity of data at a time.

    I admit I'm a bit afraid of parsing command texts for the purposes of determining whether the DISCARD ALL/SET queries are needed, mainly because it seems a bit brittle. Are we sure we know about all the Postgresql commands that could have side-effects (which would need to be reset)? If tomorrow Postgresql add a new command, we would have to somehow track that and add it...

    But I agree that synchronously blocking the thread every time an EF query is performed is unacceptable. I'm actively working on async support in #121, and as you said asynchronously closing would make this go away without the brittleness of the parsing approach.

    Agreed.

    HI @roji. As I noticed in Emill/Npgsql@462a5f4, it is possible to remove the roundtrips while still executing the commands, so doing it this way or the async way will solve the problem with unneeded roundtrips, so the string matching method is probably overkill and might as you say be troublesome if PostgreSQL one day adds a new command.

    Agreed.

    IMHO the bullet-proof way to handle this would be to asynchronously execute the reset commands, and only when these complete, return them to the connection pool...

    Agreed. The more I think about this, I think this is the way to go.

    In fact, I think that today it would be easy to implement. We just would need to make the "returning the connection to the pool" logic to run in another thread and we could immediately return to the client. This connection would still be in in use to the connection pool and so, when the client asks for another connection, Npgsql connection pool will give it a ready to use (already cleaned) connection and there won't be any initialization/blocking calls to be made.

    The connection is not properly resest now either completely. The SET queries are run in the IsValid method, which is run when the connection is taken out from the pool. So even now all available connectors in the pool are "in the middle of the commands".

    Today, the connections in the pool are in the state or either after the discard all if it is avialable in the server or with some initialization commands run like unlisten * on servers which don't support discard all.

    When the connection is requested by the user, those initialization queries are run before giving the connection to the user.

    I think we can and we have to optimize those unnecessary roundtrips. I think that by putting everything in the close connection handling, we can get that.

    I'll look into this after making progress on #121, let's keep this open in the meantime. For EF performance, I suggest using the method described in http://msdn.microsoft.com/en-us/library/vstudio/bb738701(v=vs.100).aspx

    I think this reference has to be in our documentation so users can be aware of this performance optimization they can apply in their projects.

  14. Emill commented on Jul 10, 2014

    @Emill
    ContributorAuthor

    IMHO the bullet-proof way to handle this would be to asynchronously execute the reset commands, and only when these complete, return them to the connection pool...

    If a connection is closed and immediately after that a connection is used again, wouldn't that mean we still have to wait for the roundtrip before the connection can be used again? Since we don't care about the response from the DISCARD ALL/SET commands, just ignore them whenever we get them (but handle possible errors of course). The backend is ready as soon as we have sent the DISCARD ALL/SET commands, as all following packets are guaranteed to come after those commands (thanks to tcp).

    I think this reference has to be in our documentation so users can be aware of this performance optimization they can apply in their projects.

    That's a great idea.

  15. franciscojunior commented on Jul 10, 2014

    @franciscojunior
    Member

    If a connection is closed and immediately after that a connection is used again, wouldn't that mean we still have to wait for the roundtrip before the connection can be used again?

    Yes. You are correct. This would be the worst case and would only happen when there are no connections available in the pool.

    But in the common scenario where there will be available connections, we would be able to eliminate the roundtrips.

  16. 9 remaining items

  17. Emill commented on Jul 16, 2014

    @Emill
    ContributorAuthor

    Ok, as I mentioned in #121 (comment), there shouldn't be any problems if it's done asynchronously, as long as it's asynchronous "all the way down".

  18. franciscojunior commented on Jul 16, 2014

    @franciscojunior
    Member

    There are already some async code every time a connector opens in https://github.com/npgsql/Npgsql/blob/master/Npgsql/Npgsql/NpgsqlClosedState.cs#L105-L140
    Do you think it has caused any troubles? Is it possible it might cause trouble?

    We have a report from Miłosz who says he is having problems with this async dns query in his production system. He can't reproduce it in his test environment though.
    We couldn't confirm the source of the problem yet. :(

    https://groups.google.com/forum/#!topic/npgsql-dev/xb8KzglpApo

  19. Emill commented on Jul 16, 2014

    @Emill
    ContributorAuthor

    I tested to have a callback both in BeginGetHostAddresses and BeginConnect, and found out that BeginGetHostAddresses runs on the worker thread pool and BeginConnect runs on the i/o completion thread pool. That means BeginGetHostAddresses will block if the worker thread pool is full. We should use another way to get host addresses. Since DNS is UDP, and System.Net.Sockets.UdpClient uses an i/o completion thread, it is possible to do this correctly asynchronously, even if the worker thread pool is full.

  20. franciscojunior commented on Jul 16, 2014

    @franciscojunior
    Member

    I tested to have a callback both in BeginGetHostAddresses and BeginConnect, and found out that BeginGetHostAddresses runs on the worker thread pool and BeginConnect runs on the i/o completion thread pool. That means BeginGetHostAddresses will block if the worker thread pool is full. We should use another way to get host addresses. Since DNS is UDP, and System.Net.Sockets.UdpClient uses an i/o completion thread, it is possible to do this correctly asynchronously, even if the worker thread pool is full.

    Excellent!
    We should definitely refactor this part of the code to use i/o completion thread.

  21. roji commented on Jul 17, 2014

    @roji
    Member

    @franciscojunior, I'm not sure a user should be expected to understand and manage things like whether a connection is closed synchronously or not - it seems like an advanced, internal implementation detail.

    One general comment: I don't think it is a problem if Npgsql stalls because of an exhausted thread pool. The thread pool is a critical .NET application resource and many things won't work well if it's exhausted, so Npgsql shouldn't necessarily be expected to either. If some problem in the user's application exhausts the thread pool, that shouldn't necessarily be our concern.

    However, I do think it's a problem if Npgsql causes thread pool exhaustion or deadlocks in any way.

    Another point - the ADO.NET API exposes both Connect() and ConnectAsync(). IMHO, the ideal way to go here is to do double flow implementation - use sync methods to implement Connect() and async ones to implement ConnectAsync(). Note that implementing ConnectAsync() properly means making our thread pool async too, so I'm definitely not touching that for now.

    If we do this, we still have the issue of timeouts. This is quite a tricky feature, but we could use a system timer which would update a timeout variable, which would be checked at various points in the flow (i.e. after each I/O event). If the variable is true, we throw a TimeoutException. The advantage of this is that it doesn't use async I/O methods, and thus is much less sensitive to thread pool exhaustion; the timer itself may not fire in time (because it requires a TP thread), but at least the synchronous connection process will continue smoothly and never block...

    What do you guys think?

  22. franciscojunior commented on Jul 17, 2014

    @franciscojunior
    Member

    One general comment: I don't think it is a problem if Npgsql stalls because of an exhausted thread pool. The thread pool is a critical .NET application resource and many things won't work well if it's exhausted, so Npgsql shouldn't necessarily be expected to either. If some problem in the user's application exhausts the thread pool, that shouldn't necessarily be our concern.

    I agree with you. I was thinking about shielding Npgsql from this type of problems. But on a second thought I think this would defeat the whole purpose of going async. :)
    I think we will have to defend ourselves from this problem using other solutions or mitigate it as much as possible. :)

    However, I do think it's a problem if Npgsql causes thread pool exhaustion or deadlocks in any way.

    Sure!

    Another point - the ADO.NET API exposes both Connect() and ConnectAsync(). IMHO, the ideal way to go here is to do double flow implementation - use sync methods to implement Connect() and async ones to implement ConnectAsync(). Note that implementing ConnectAsync() properly means making our thread pool async too, so I'm definitely not touching that for now.

    From recent discussions of today, (#121 (comment)) it seems we are going to do sync over async, right? Thus, we are won't need a double flow implementation. I think this is the way to go to avoid unnecessary code duplication, unless we find a big blocking issue with this approach.

  23. roji commented on Jul 17, 2014

    @roji
    Member

    @franciscojunior, yes, that's right. I'm now working on a sync-over-async implementation, at least until someone can show it is a bad idea.

    Especially because of the sync-over-async decision, it is now very important to never use TP worker threads inside Npgsql (in sync-over-async operations), since that would lead to the deadlock. We do all the async work in the TP IO completion threads (not the worker threads). So npgsql will be shielded from thread pool (worker) exhaustion in any case...

  24. changed the title [-]Unneeded roundtrips in the connection pool[/-] [+]Connection cleanup should happen asynchronously[/+] on Aug 9, 2014
  25. added this to the milestone on Aug 31, 2014
  26. added a commit that references this issue on Oct 12, 2014
    0cbfce2
  27. removed this from the milestone on Mar 23, 2015
  28. roji commented on Mar 23, 2015

    @roji
    Member

    Closing in favor of #552

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions