Skip to content

Persist prepared statements across connections #483

Closed

Description

@roji

Continuation of #434.

Currently all (server-side) prepared statements are deallocated when the connection is closed. For a heavy website usage pattern, it makes sense for them to persist when the connection is closed and the connector is returned to the pool.

This would mean that the prepared statement is somehow marked as "persistent" by the user, and then cached by its query. The next time the same query is prepared, we return the cached prepared statement instead of resending a prepare to the server.

Activity

  1. added this to the milestone on Mar 5, 2015
  2. roji commented on Mar 5, 2015

    @roji
    MemberAuthor

    I don't agree on this (see discussion in #434).

    In many usage patterns, connection are long-lived: I create a connection to the database and use it for a long time. In these scenarios prepared statements, as implemented today, make a lot of sense. For short-lived scenarios (e.g. typical web) I agree that prepared statements don't currently make sense, but this issue is about solving that.

    IMHO solving prepared statements across short-lived connections (this issue) doesn't necessarily depend on any PostgreSQL feature, but only on internal Npgsql support related to pooling and connection management. In other words, it's a matter of adding a user API for flagging prepared commands as persistent, finding a way to maintain them across connection closing (our current DISCARD ALL kills everything), and caching them internally in the connector so that subsequent Prepare() doesn't actually go to the backend.

    Added this to 3.1 because of the considerable performance improvement and the planned work on the connection pool.

  3. roji commented on Mar 13, 2015

    @roji
    MemberAuthor

    Here's an implementation proposal, it seems quite trivial:

    • Add IsPersistent flag on NpgsqlCommand to allow the user to indicate the prepared statement should persist across connections.
    • Add a PersistentPreparedStatements dictionary on NpgsqlConnection, mapping query SQL to the backend identifier of the backend prepared statement, as well as its RowDescriptions
    • When Prepare() is called on a persistent command, check PersistentPreparedStatements is checked for the SQL.
      • If it doesn't exist (first time), the command is prepared and the mapping is added to the dictionary.
      • If it does exist, the backend identifier and RowDescriptions are used. No actual prepare takes place.
    • During connection close, we no longer use DISCARD ALL, but rather the equivalent set of statements. If the command has any persistent prepared statements, we only DEALLOCATE statements which aren't persistent.
  4. franciscojunior commented on Mar 13, 2015

    @franciscojunior
    Member

    I think this is a great plan!
    +1

    I would only add an option to specify that persistable flag in the connection string. This way the developer wouldn't need to code against an specific feature of Npgsql which could make her code more portable?
    I know this may have the side effect of adding queries the user would want to use only once to the list, but I think that 90% of the queries would be ones the developer would want to reuse, so I think the tradeoff is worthwhile.

    Just a question, for clarification: Aren't the prepared statement handles per connection? If so, how are we going to handle when the user prepares the statement in connection A and later the pool returns a connection B? Do we handle it like a new prepared statement?

  5. roji commented on Mar 13, 2015

    @roji
    MemberAuthor

    @franciscojunior, the connection string idea is not bad!

    Regarding your question... The point is that the programmer always calls Prepare, but sometimes Prepare does nothing because the connection already has a prepared version of that SQL query. So when the pool returns connection B, it is completely blank (no prepared statements). And when the user calls Prepare() on it, actual preparation takes place. But gradually, as the same connections are reused from the connection pool, all connections end up having the persistent prepared statement and no more actual preparation takes place any more.

  6. franciscojunior commented on Mar 13, 2015

    @franciscojunior
    Member

    @franciscojunior, the connection string idea is not bad!
    :)

    Regarding your question... The point is that the programmer always calls Prepare, but sometimes Prepare does nothing because the connection already has a prepared version of that SQL query. So when the pool returns connection B, it is completely blank (no prepared statements). And when the user calls Prepare() on it, actual preparation takes place. But gradually, as the same connections are reused from the connection pool, all connections end up having the persistent prepared statement and no more actual preparation takes place any more.

    Ok! I think I didn't explain myself very well. By "do we handle it like a new prepared statement" I meant exactly what you said. :)
    Thanks for clarifying it :)

  7. modified the milestones: 3.2, on Apr 21, 2016
  8. MarkusSintonen commented on Apr 25, 2016

    @MarkusSintonen
    Contributor

    Hi,

    I made an initial implementation for the #483 based on the first proposal by @roji. I did not implement the connection string option yet as proposed by @franciscojunior. I was thinking about, should we make the persistent behaviour as a default one since this has such positive performance implications when using Prepare()? Also the persisting behaviour of Prepare() is the one that programmer would expect as seen in discussions here as well as in Stack Overflow. Of course in this case there should be some timer mechanism to monitor the life time of persisted statements so that there would be no risk of resource leaks with highly dynamic queries. I don't think the IsPersistent property is the best way to handle this since it requires the programmer to always enable it when using Prepare(). Another option would be to use the connection string parameter that makes all the prepared statements persistent as a default.

    Few further API decisions must be made:

    • Does NpgsqlCommand.CommandText changing cause disposing of the already persisted command? This implementation does not dispose the already persisted command in this case
    • How we would name the already mentioned new connection string parameter?
    • Or should we instead make the IsPersistent behaviour the default one

    Also about the implementation:

    PreparedStatementCollection - contains persisted prepared commands and also handles the statement name allocation for both persistent and non persistent statements. Statement names are now based on globally unique ids. This makes it easier to allocate unique ids compared to the incrementing index number when we can not anymore reset the index counter back to zero.

    PersistentPreparedCommand - persistent memoized representation of the prepared command. Contains commands sql and list of persistent statements.

    PersistentPreparedStatement - persistent memoized representation of the persistent statement. Contains prepared statement name, statement SQL (produced by SqlQueryParser), row description received from server and list of memoized representation of statement parameters.

    PersistentStatementParameter - persistent memoized representation of the statement parameter. Contains just statement name and boolean flag indicating whether name was user defined or auto generated. These are used to map the command parameters to individual statement parameters

    Prepare() takes the PersistentPreparedCommand from PreparedStatementCollection based on CommandText (the SQL) when Prepare() is called on a persisted command that is already prepared. The NpgsqlStatements are then constructed from PersistentPreparedCommand contents. Therefore we dont need to reparse the query and fetch the row descriptors from the server each time Prepare() is called.
    If CommandText is not found from the PreparedStatementCollection dictionary then the command is prepared as normal and after this the PersistentPreparedCommand is constructed from the prepared statements.

    Connection disposing does not DEALLOCATE the persistent statements (when connection is pooled). Only the non persisting ones are DEALLOCATED. DISCARD ALL is no longer used. Instead the correct sequence and set of DISCARD ALL sub commands are executed (as described in PostgreSQL manual).

    What you think? And please review.

    Also, would it be possible to integrate this already into 3.1 if this looks good?

    BR

  9. roji commented on Apr 27, 2016

    @roji
    MemberAuthor

    @MarkusSintonen thanks for looking into this. If you've made a stab at an implementation, can you submit a PR for a proper review? It's better than discussing things in the abstract.

    Some comments on what you said...

    should we make the persistent behaviour as a default one since this has such positive performance implications when using Prepare()? Also the persisting behaviour of Prepare() is the one that programmer would expect as seen in discussions here as well as in Stack Overflow. Of course in this case there should be some timer mechanism to monitor the life time of persisted statements so that there would be no risk of resource leaks with highly dynamic queries. I don't think the IsPersistent property is the best way to handle this since it requires the programmer to always enable it when using Prepare(). Another option would be to use the connection string parameter that makes all the prepared statements persistent as a default.

    I'm not sure about making prepared statement persistent the default behavior. Persisting prepared statements in the long term could be a resource drain on the server - I'm not sure how significant this could be but I'm not sure we should experiment with it. I'm skeptical of any timer-based mechanism, it would probably be too complicated and introduce subtle bugs. And at least in my opinion, the common programmer expectation is for prepared statements to disappear when the connection is closed - do you think people assume otherwise?

    Because of all this I'd be more comfortable with making this an opt-in feature. It definitely makes sense to me to have a connection string parameter to make persistence the default, but a per-command IsPersistent should also be available (this would allow persisting only some prepared statements but not others).

    Does NpgsqlCommand.CommandText changing cause disposing of the already persisted command? This implementation does not dispose the already persisted command in this case

    I think it does make sense to deallocate the persisted statement when NpgsqlCommand.CommandText is changed. Just like the persisted statement is created by calling Prepare(), operations that normally unprepare a prepared statement should also deallocate a persisted one. We may want to publicly expose an Unprepare method as well.

    How we would name the already mentioned new connection string parameter?

    How about "Persist Prepared"?

    Or should we instead make the IsPersistent behaviour the default one

    As I said above I'm against it. But there's no reason not to have both the connection string parameter and IsPersistent (both default to false).

    Regarding your implementation, I'm not sure if your list refers to actual C# types, if so I'm not sure all that is necessary (e.g. PreparedStatementCollection could be a simple Dictionary on NpgsqlCommand). But it's best to send a PR with an actual implementation proposal.

    I'm hoping to release the beta of 3.1 in around two weeks (although that may be a bit optimistic). I can see this feature making it in for that...

  10. MarkusSintonen commented on Apr 28, 2016

    @MarkusSintonen
    Contributor

    Pull request is now available for review #1053
    The connection string parameter is now also implemented as well as deallocation of the persisted statement when command string changes.

    Also PreparedStatementCollection is now called PreparedStatementRegistry which depicts it more clearly. Class contains the logic for name allocation of prepared statements as well as the caching of persisted statements. It is owned by the connector which then commands rely on. Please review

    Of course when setting the "Persist Prepared" parameter to true the user must be careful not to create big resource leaks. It might be also wise to include parameter/parameters to limit the number of persistent prepared statements. There could be few options here to avoid the leaks:

    1. MaxPersistentPrepared - maximum number of persistent statements across all connections
    2. MaxPersistentPreparedPerConnection - maximum number of persistent statements per connection
    3. PersistentPreparedLifeTime - time after which the persistent statement is deallocated if not used
    4. and 2. would deallocate rarely used statements first when constraints are violated

    What you think about these? Would these be wise to include in the case when "Persist Prepared" is enabled?

    (Just for reference JDBC has parameters to limit the cached prepared statement count per connection https://docs.oracle.com/cd/B19306_01/java.102/b14355/stmtcach.htm#i1069942)

  11. 1 remaining item

  12. roji commented on May 24, 2016

    @roji
    MemberAuthor

    @MarkusSintonen I've pretty much cleared everything around the 3.1 release, so I now have time to review this.

    Regarding maximum counts of persisted statements and lifetimes, it seems too much for me. First, this whole discussion is around prepared statements. If a user turns on the "Persist Prepared" connection string flag, they should be aware themselves of what they're preparing and what kind of a resource drain that creates. They also have the IsPersistent flag to control, on a command-by-command basis, exactly which commands gets persisted and which don't.

    In other words, the programmer already has all the means they need to control exactly what happens, IMHO any sort of automatic timers/limits would be going overboard and overcomplicating the feature...

  13. roji commented on Jul 17, 2016

    @roji
    MemberAuthor

    See PR and design discussion in #1084

  14. roji commented on Jul 17, 2016

    @roji
    MemberAuthor

    @MarkusSintonen, I've pushed my own work as PR #1204. It's not complete - I still need to go over it, probably take care of some edge cases, but it does work and demonstrates the statement persistency approach.

    Please let me know what you think (feedback from anyone else is also welcome of course).

  15. added a commit that references this issue on Oct 13, 2016
  16. changed the title [-]Keep prepared statements across connections[/-] [+]Persist prepared statements across connections[/+] on Jan 11, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions