Skip to content

Trigger backend cancellation when a (frontend) timeout occurs #1567

Closed

Description

@roji

Npgsql currently has frontend (or socket) timeouts - if a read is stuck on a socket for too long, an exception is raised and the connection is broken. One disadvantage of this is that the backend is left with the running query, at least until it attempts to write some results back (at which point it would bomb due to the closed connection). For cases of which don't produce any results for a long time, this is problematic.

When a socket timeout occurs, we can trigger a cancellation on the connection to resolve this.

Split off from #1344, and also discussed in #1551.

Activity

  1. added this to the milestone on May 20, 2017
  2. self-assigned this
    on May 20, 2017
  3. FlorianRainer commented on Nov 17, 2017

    @FlorianRainer
  4. roji commented on Nov 18, 2017

    @roji
    Author
  5. FlorianRainer commented on Nov 20, 2017

    @FlorianRainer
  6. roji commented on Nov 20, 2017

    @roji
    Author
  7. modified the milestones: 4.0, on Mar 14, 2018
  8. modified the milestones: 4.1, 5.0 on Aug 26, 2019
  9. vonzshik commented on Aug 19, 2020

    @vonzshik
    Contributor

    Hello, @roji, is anyone working on this one?

  10. roji commented on Aug 20, 2020

    @roji
    MemberAuthor

    @vonzshik nope - although I think @Brar is doing some timeout-related work in his logical replication branch, so this may not be the perfect time (@Brar can you confirm?).

    Otherwise feel free to work on this, but it may be a good idea to discuss exactly what we want to do before starting implementation, and to consider the discussion in #2437 (this issue actually seems to be a dup of that one).

    Here are some thoughts on what we should do:

    • I think the ideal behavior in Npgsql is to first attempt a so-called backend/PostgreSQL timeout - contact PG and trigger cancellation of the currently-running query. This has the advantage of terminating long operations in PG, and of keeping the physical connection alive.
    • If the PG timeout isn't completed within a certain time window, we then perform a client/socket timeout. This always succeeds, and breaks the physical connection.
    • Note that this backend-then-frontend behavior would need to be implemented across the board, for both sync and async. This would mean NpgsqlCommand.Cancel and the cancellation token of the DbCommand.Execute* methods, as a minimum.
    • Note that backend cancellation isn't currently supported with multiplexing. I think it's OK to scope that out for now (Design behavior around timeouts and multiplexing #3110)

    /cc @Brar and @YohDeadfall it would be good to get your opinion on the above (though I know we briefly discussed this before).

  11. vonzshik commented on Aug 20, 2020

    @vonzshik
    Contributor

    So, as an example:

    1. We have 30 seconds as a CommandTimeout
    2. 5 seconds before client timeout, we contact PG to cancel query
    3. If we are successful, we should throw a timeout exception (without breaking connection)
    4. On closing connection, it returns to the pool to be reused
    5. If we are not successful with cancellation within 5 seconds, we should get a timeout exception from socket (cancellation token in case of async). Also, we (maybe?) cancel cancel request.
    6. On closing connection, it returns to the pool to be disposed
  12. roji commented on Aug 20, 2020

    @roji
    MemberAuthor

    @vonzshik yes, that more or less corresponds to what I had in mind. Some open questions:

    Should we contact PG to cancel query after 25 seconds (as you suggest), or after 30? I think after 30 is better, with the Command Timeout setting being a lower bound rather than an upper bound. It would be surprising (and probably more ncorrect) if the user specifies 30 seconds, but their query gets cancelled after only 25.

    If the PG cancellation succeeds, we should probably continue to throw the PostgresException with SqlState=57014, rather than TimeoutException. Besides allowing the user to distinguish the two cancellation types (and just passing along the PG response), throwing a TimeoutException would be a breaking change - existing code already expects PostgresException as a consequence of cancellation. (it's true that we would start to throw TimeoutException for the client timeout in case the PG one fails, but that seems more acceptable).

    Also, we (maybe?) cancel cancel request.

    Very good point.

    Anyway, I'd like to hear @YohDeadfall's and @Brar's opinions about this plan (and also to know whether @Brar thinks there's going to be a conflict with his own work), but aside from that it sounds like we're aligned.

  13. Brar commented on Aug 20, 2020

    @Brar
    Member

    I consider timeouts and cancellation as related but not identical concepts.
    While timeouts are probably the most common reason to trigger cancellation, it might also happen as a reaction to a GUI event (e. g. a user clicking a button to abort a long running query).
    So to me #2437 is a more general thing about cancellation whereas this is more about timeouts that cause a cancellation.
    While the actual implementation will overlap to a huge amount, I don't think we should mix the two terms or treat them as interchangeable.

    I think @Brar is doing some timeout-related work in his logical replication branch, so this may not be the perfect time (@Brar can you confirm?).

    Yes I can.
    What I'm currently working on (cancellation and timeouts in replication connections) will rely on async cancellation but will not use anything around CommandTimeout so the actual overlap of our work would probably be the cancellation part. Also, since the replication API will be async only, I don't care about sync cancellation.

    For this reason I think that we should, at first, talk about what we actually want regarding (async) cancellation (#2437 - e. g. wire the cancellation tokens we already have on some of our public API down to the actual socket + trigger backend cancellation first as an attempt to save the physical connection) and then both of us could probably do their thing without too much overlap.

  14. vonzshik commented on Aug 21, 2020

    @vonzshik
    Contributor

    Should we contact PG to cancel query after 25 seconds (as you suggest), or after 30? I think after 30 is better, with the Command Timeout setting being a lower bound rather than an upper bound. It would be surprising (and probably more ncorrect) if the user specifies 30 seconds, but their query gets cancelled after only 25.

    Agree, it should be 30 seconds.

    If the PG cancellation succeeds, we should probably continue to throw the PostgresException with SqlState=57014, rather than TimeoutException. Besides allowing the user to distinguish the two cancellation types (and just passing along the PG response), throwing a TimeoutException would be a breaking change - existing code already expects PostgresException as a consequence of cancellation. (it's true that we would start to throw TimeoutException for the client timeout in case the PG one fails, but that seems more acceptable).

    Yep, we shouldn't change this behavior (at the very least in this issue).

    I've had some time to think it over, and this is how I see it working:

    1. There are no changes in NpgsqlReadBuffer, it should work as it is.
    2. We only change NpgsqlConnector (I'm talking about while (true) reading loop here).
    3. When NpgsqlReadBuffer fails because of CommandTimeout (doesn't matter, sync or async), we should catch it in the loop.
    4. Then, if and only if we determine that exception is defitinelly because of CommandTimeout, we send request to PG to cancel query. Also, this request should have timeout different from CommandTimeout (maybe another param in ConnectionString?).
    5. If request also fails with timeout, then nothing changes - connection is broken etc.
    6. But if it is successful, we return to the read loop and proceed to read everything, until we get PG exception.
    7. After that, also nothing changes - connection is not broken, it returns to the pool to be reused.

    Most likely I've missed some cases, where it wouldn't work (multiplexing?).

  15. vonzshik commented on Sep 6, 2020

    @vonzshik
    Contributor

    @roji ping, in case you have some time to continue discussion. Or maybe I should take a look at some other issues (for example, #2282, #1810) for now?

  16. roji commented on Sep 6, 2020

    @roji
    MemberAuthor

    Am just writing a response here :)

  17. roji commented on Sep 6, 2020

    @roji
    MemberAuthor

    Sorry for disappearing for a while, had to deal with some personal issues. Although this issue is about timeouts, I'll try to summarize things as I see them for both timeouts and cancellation, as they're somewhat related.

    User-triggered cancellation seems to be the simpler case (this is tracked by #2437).

    • Both DbCommand.Cancel (sync) and the cancellation token (async) trigger PostgreSQL server cancellation.
      • Good: it actually cancels the query in PG
      • Bad: if there's a network partition it has no effect, and user code is stuck on read forever.
      • Bad (minor): PostgreSQL server cancellation is unapplicable for multiplexing (queries are interleaved on the connection, and it's impossible to know which one will be cancelled).
    • Since Socket now honors cancellation tokens, we can add a socket cancellation at some interval after the backend cancellation times out. This would solve the two bad points above.

    User-managed timeout is more complicated:

    • Our current user timeout story (i.e. CommandTimeout) is pretty much the opposite: CommandTimeout is only implemented via socket timeouts.
      • Bad: the PG query doesn't get cancelled
      • Good: it there's a network partition, user code gets the exception and stops hanging.
      • (multiplexing is a bit more complicated here, let's leave it out of the discussion for now (Design behavior around timeouts and multiplexing #3110).
    • Adding a PostgreSQL cancellation when the timeout expires would fix the bad part above.
    • However, there's an alternative - we can also consider going back to PostgreSQL statement_timeout.
      • Npgsql used to do this, but we removed it back in 2015 (Remove backend timeouts #689 - see that issue for context, and especially this conversation in pg-hackers.
      • In a nutshell, statement_timeout fires after X seconds have passed, regardless of the type of time. For example, if the user code takes time in processing some row result, that time is counted in the timeout. This is very different from the socket timeouts we're using, which are only about time spent waiting for responses (on the network).
      • However, an advantage of statement_timeout compared to PG cancellation, is that if a network partition occurs at some point after the query has started, the former will cancel the query while the latter won't.
      • As @Brar noted below, it's always possible for users to manually set statement_timeout just like any other PG parameter if that's what they want.

    In light of the above, I think we should continue not using statement_timeout, and implement PG cancellation as already discussed in this issue. Basically, the scenario of a network partition after the query starts doesn't seem important enough compared to the quirkiness of how statement_timeout works (and the subtle breakage that starting to use it would introduce).

    Also, as we're already considering doing the timeout part, we should consider doing the cancellation part as well for 5.0, to (finally) present a complete and working cancellation & timeout story in Npgsql.

    Thoughts?

  18. Brar commented on Sep 6, 2020

    @Brar
    Member

    In light of the above, I think we should continue not using statement_timeout, and implement PG cancellation as already discussed in this issue.

    Agreed.

    Basically, the scenario of a network partition after the query starts doesn't seem important enough compared to the quirkiness of how statement_timeout works (and the subtle breakage that starting to use it would introduce).

    Agreed.
    Also if somebody really uses very heavy queries that should definitely stop after some time, even in case of a network partition, there's nothing stopping them from issuing a SET statement_timeout TO 123; before the actual query.

    Also, as we're already considering doing the timeout part, we should consider doing the cancellation part as well for 5.0, to (finally) present a complete and working cancellation & timeout story in Npgsql.

    Yes absolutely. My replication work will build on top of (async) cancellation so it would be good for my work to even do the cancellation part first.

  19. roji commented on Sep 6, 2020

    @roji
    MemberAuthor

    Also if somebody really uses very heavy queries that should definitely stop after some time, even in case of a network partition, there's nothing stopping them from issuing a SET statement_timeout TO 123; before the actual query.

    That's a very good point, and another argument why we don't need to do this in the driver. I've added it to the analysis above.

  20. roji commented on Sep 6, 2020

    @roji
    MemberAuthor

    @vonzshik let's see what @YohDeadfall thinks, but I think we have a good consensus - unless something new comes from @YohDeadfall I think you can start implementation. You don't have to do both the timeout and cancellation in the same PR (in fact it's always better to split things to smaller chunks for easier reviewing).

  21. YohDeadfall commented on Sep 6, 2020

    @YohDeadfall
    Contributor

    Am okay with everything said by @roji and @Brar. There is no third opinion.

  22. linked a pull request that will close this issueCancelling queries on timeouts #3130on Sep 18, 2020
  23. roji commented on Oct 2, 2020

    @roji
    MemberAuthor

    FYI @vonzshik and others, here is the plan for timeouts in MySqlConnector by @bgrainger, which is similar to what we've done: mysql-net/MySqlConnector#455 (comment). It's good to have validation from another database driver expert that most of the decisions/arguments here are valid.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions