Skip to content

Persist prepared commands - #1084

Closed
MarkusSintonen wants to merge 2 commits into
npgsql:devfrom
MarkusSintonen:feature/persist-prepare-3.1
Closed

MarkusSintonen wants to merge 2 commits into
npgsql:devfrom
MarkusSintonen:feature/persist-prepare-3.1

Conversation

@MarkusSintonen

Copy link
Copy Markdown
Contributor

Implementation for #483

@roji

roji commented May 12, 2016

Copy link
Copy Markdown
Member

Thanks @MarkusSintonen, any chance you can squash all those commits?

@MarkusSintonen
MarkusSintonen force-pushed the feature/persist-prepare-3.1 branch from 2d31d57 to eafa65f Compare May 12, 2016 21:34
@MarkusSintonen

Copy link
Copy Markdown
Contributor Author

@roji commits are now squashed into a single commit

- Implemented command persisting
- Added IsPersisted property to NpgsqlCommand
- Added Persist Prepared connection string parameter
- Added unit tests for above
@MarkusSintonen
MarkusSintonen force-pushed the feature/persist-prepare-3.1 branch from eafa65f to a785850 Compare May 12, 2016 21:49
@roji
roji force-pushed the dev branch 6 times, most recently from 3b2c4af to ad61dee Compare May 23, 2016 11:27
Comment thread src/Npgsql/NpgsqlCommand.cs Outdated

internal const int DefaultTimeout = 30;

internal const bool DefaultIsPersistent = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure of the value of having a const false here... We can just say that the default is false without having a const to define it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing, will simplify this

@roji

roji commented May 31, 2016

Copy link
Copy Markdown
Member

@MarkusSintonen am waiting for your responses on this

@MarkusSintonen

Copy link
Copy Markdown
Contributor Author

Hi @roji,

Sorry I haven't been able to respond yet. I'm currently abroad and I'll answer ASAP when I get back home after sunday.

@roji

roji commented May 31, 2016

Copy link
Copy Markdown
Member

Sure thing @MarkusSintonen, no problem.

- Disabling IsPersistent no longer deallocates stament immediately
- Fixed tests
@MarkusSintonen

MarkusSintonen commented Jun 7, 2016 •

Copy link
Copy Markdown
Contributor Author

@roji I made a new commit to the pull request. Sorry it took a while to react.

@MarkusSintonen

MarkusSintonen commented Jun 27, 2016 •

Copy link
Copy Markdown
Contributor Author

Hi @roji,

I totally missed your last comment at the closed PR #1053 so I did not respond to that. I copied your last comment here from the closed PR so we can continue discussion here:

I've taken a very quick look, here are some remarks.
1.Thanks for the extensive tests!
2. Seeing the API at work, maybe we should simply have an overload of Prepare() which accepts a boolean rather than a separate IsPersistent property?
3. Is there any particular reason we need the new PersistentPreparedCommand and PersistentPreparedParameter? Can't we just have a simple dictionary cache, mapping statement SQLs to PostgreSQL persistent statement names?
4. Related to the last point - in my mind all caching would happen at the statement level, rather than at the command level - since this is what is actually prepared on the PostgreSQL side. In other words, when I prepare a persistent command, we parse the text as usual, and for each of the statements resulting from the parse, we check if there's a match in the persistent statement cache. If so, we simply use the prepared statement name and that's it. I think this would also make management simpler in general.
5. Especially if the above works, I'd simply fold PersistentPreparedRegistry into the connector, the split into another class seems to create more complexity than it saves... It's just two data structures...
6. Any specific reason for using Guids in prepared statement names? This just seems to make everything harder to follow - why not a simple counter as before?
7. Let me know what you think of the above, if you want I can do a PR of my own for comparison.

Regarding your questions:
2: I agree that Prepare(bool) overload would be a better solution here
3-4: I also first thought about just persisting single statements and not the full command. But I chose to go with persisting the full command and using the sql as the key to map to the persisted command. This had much better performance charactestics than parsing the command into individual statements everytime Prepare is called on persisted command. This solution just fetches the persisted representation of the command and requires no additional parsing of the sql.
5: The current data structures are created so that it supports the above solution. Of course some simplifications can be made but to me this seems simpler than putting the additional structures directly under connector. Connector already has a lot of member fields and I tried to avoid polluting it further. This is basically matter of taste.
6: I also tried to use a counter as in the original implementation but this became too complicated to manage since the counter was previously reset to zero. When statements are persisted we can no longer just simply reset the index counter because some of the counter indexes might be already in use as prepared statement names. Counter implementation would require some additional data structures etcetc to keep track of the consumed indexes. This would become too complicated and performance would be poorer. Also the counter can not be just incremented forever since there is always a risk of overflow or wrap around in very long living applications. Because of these points I chose to go with GUIDs because they require no special logic and they are fast to generate.
7: Of course it would be intresting to see your solution if you have it ready

@roji

roji commented Jul 9, 2016

Copy link
Copy Markdown
Member

@MarkusSintonen, I'm sorry I haven't replied sooner, other things have kept me busy. I really appreciate your work and responses, here are some comments:

  1. Is there any particular reason we need the new PersistentPreparedCommand and PersistentPreparedParameter? Can't we just have a simple dictionary cache, mapping statement SQLs to PostgreSQL persistent statement names?
  2. Related to the last point - in my mind all caching would happen at the statement level, rather than at the command level - since this is what is actually prepared on the PostgreSQL side. In other words, when I prepare a persistent command, we parse the text as usual, and for each of the statements resulting from the parse, we check if there's a match in the persistent statement cache. If so, we simply use the prepared statement name and that's it. I think this would also make management simpler in general.

3-4: I also first thought about just persisting single statements and not the full command. But I chose to go with persisting the full command and using the sql as the key to map to the persisted command. This had much better performance charactestics than parsing the command into individual statements everytime Prepare is called on persisted command. This solution just fetches the persisted representation of the command and requires no additional parsing of the sql.

Do you really think performance is important here? First, it's a one-time pass (per connection) when doing Prepare. Second, whatever time the parsing takes, it's going to be completely dwarfed by the actual networking etc. So this seems like an unnecessary optimization to me.

I do understand that the data structures are necessary to support the per-command caching, but it seems like if you switch to per-statement caching things become much simpler - basically you just need a dictionary mapping (parsed) statement SQL to the PostgreSQL prepared statement name. We would need two of these - one for persistent statements and one for non-persistent statements (which get deallocated on close). This would be very light and doesn't introduce any new classes. Since performance isn't a real concern here, in my opinion, I'd opt for the lighter/less invasive design.

6: I also tried to use a counter as in the original implementation but this became too complicated to manage since the counter was previously reset to zero. When statements are persisted we can no longer just simply reset the index counter because some of the counter indexes might be already in use as prepared statement names. Counter implementation would require some additional data structures etcetc to keep track of the consumed indexes. This would become too complicated and performance would be poorer. Also the counter can not be just incremented forever since there is always a risk of overflow or wrap around in very long living applications. Because of these points I chose to go with GUIDs because they require no special logic and they are fast to generate.

I may be missing something but I imagined a simple counter for persistent prepared statements only, that only goes gets incremented. For a given (physical) connection it never gets reset - no need to keep track of anything. Regarding overflow, a program would need to prepare over ulong.MaxValue distinct persistent statements, which is very hard to imagine. Don't forget that GUIDs can also collide if you generate enough of them, a ulong counter at least have the advantage of generating an overflow exception rather than a silent untrackable GUID collision...

Let me know what you think of the above.

@MarkusSintonen

MarkusSintonen commented Jul 12, 2016 •

Copy link
Copy Markdown
Contributor Author

Hi @roji nice to hear from you,

Regarding your comments:

Do you really think performance is important here? First, it's a one-time pass (per connection) when doing Prepare. Second, whatever time the parsing takes, it's going to be completely dwarfed by the actual networking etc. So this seems like an unnecessary optimization to me.

I think the use cases of persisting the prepared commands is in applications where performance is paramount. We have one of these: a time series database that is time critical requiring very high performance. We had the exact performance problems with Npgsql, that we are trying to solve in PR, the missing command persisting feature. This required us to create a custom connection pooling and command persisting logic on top of the Npgsql. I think this is not a very optimal solution since the library should support the command persisting out of the box for these kind of applications. We did performance measurements and the processing of raw command SQLs inside Prepare() was also one of the culprits for the low performance (we use few fairly complex queries that also require a high query performance). With the custom command persisting (and connection pooling) logic we got huge performance benefits (I can give some numbers later if needed). I agree that the networking somewhat dwarfs the command parsing but I don't agree that this can be generalized since one of the use cases for command persisting is with highly complex queries. Which would require some parsing burden every time when the IsPersistent command is used. Unnecessary parsing also increases the CPU usage and GC load where commands are used in a tight cycle. Where as in the PR solution a simple dictionary lookup is used instead of a full sql parsing, making it very efficient.

I do understand that the data structures are necessary to support the per-command caching, but it seems like if you switch to per-statement caching things become much simpler - basically you just need a dictionary mapping (parsed) statement SQL to the PostgreSQL prepared statement name. We would need two of these - one for persistent statements and one for non-persistent statements (which get deallocated on close). This would be very light and doesn't introduce any new classes. Since performance isn't a real concern here, in my opinion, I'd opt for the lighter/less invasive design.

I agree the design could be further simplified also with the command persisting based on full SQL. But I also think the full command persisting is performance wise better (noticable with complex queries) than the solution where command is everytime parsed into individual statements.

I may be missing something but I imagined a simple counter for persistent prepared statements only, that only goes gets incremented. For a given (physical) connection it never gets reset - no need to keep track of anything. Regarding overflow, a program would need to prepare over ulong.MaxValue distinct persistent statements, which is very hard to imagine. Don't forget that GUIDs can also collide if you generate enough of them, a ulong counter at least have the advantage of generating an overflow exception rather than a silent untrackable GUID collision...

I also agree that ulong is the best solution here and not the GUID.

BR

@roji

roji commented Jul 12, 2016

Copy link
Copy Markdown
Member

@MarkusSintonen I'm definitely interested in your performance experience with Npgsql. Can you share some hard figures specifically on the SQL parsing part? I'm sure that the current parser isn't necessarily very optimized - it's a pretty old piece of code within Npgsql and although it works pretty well it may not be the fastest. However, I'd rather optimize the parser itself than cover over its inefficiencies by persisting prepared commands; this way everyone benefits from the performance, with or without persisting. Also, I'd still like to see evidence that the SQL parsing is actually significant when compared to networking.

Note also #1042, which is about allowing a mode where no parsing takes place at all. I personally really dislike that Npgsql parses SQL - IMHO it should simply be forwarding user SQL strings to the database. The two reasons this is necessary is:

So if #1042 is implemented, caching by statement becomes just as fast as caching by command, since no parsing takes place.

@MarkusSintonen

MarkusSintonen commented Jul 15, 2016 •

Copy link
Copy Markdown
Contributor Author

Hi @roji

I'm definitely interested in your performance experience with Npgsql. Can you share some hard figures specifically on the SQL parsing part? I'm sure that the current parser isn't necessarily very optimized - it's a pretty old piece of code within Npgsql and although it works pretty well it may not be the fastest. However, I'd rather optimize the parser itself than cover over its inefficiencies by persisting prepared commands; this way everyone benefits from the performance, with or without persisting. Also, I'd still like to see evidence that the SQL parsing is actually significant when compared to networking.

I created a version of IsPersisted feature that includes the SQL parsing step at each Prepare() to measure the performance implication of parsing. I then created a test that uses a quite complex SQL query (as was the case with our original performance problems). The test uses 4 workers that run the query in a loop to collect the performance results. The workers used their own NpgsqlConnection without returning it to pool during the test run. The test measured the time taken to Prepare() and ExecuteScalar() separately to evaluate the networking overhead. Both were measured 100000 times with JIT warm up taken into account and by using StopWatch. The tests do not take the initial Prepare() into account that prepares the statements to PostgreSQL. Here are the results:

3 test runs WITHOUT parsing:

  • Avg. Prepare Time: 4,304us, Avg. ExecuteScalar Time: 97,123us, Total Run Time: 11627ms
  • Avg. Prepare Time: 4,341us, Avg. ExecuteScalar Time: 95,509us, Total Run Time: 11452ms
  • Avg. Prepare Time: 4,236us, Avg. ExecuteScalar Time: 97,845us, Total Run Time: 11692ms

3 test runs WITH parsing:

  • Avg. Prepare Time: 10,820us, Avg. ExecuteScalar Time: 98,846us, Total Run Time: 12549ms
  • Avg. Prepare Time: 10,513us, Avg. ExecuteScalar Time: 97,762us, Total Run Time: 12365ms
  • Avg. Prepare Time: 10,781us, Avg. ExecuteScalar Time: 98,655us, Total Run Time: 12501ms

As you can see the parsing worsens the Prepare() performance by a factor of 2,5x. Just the parsing itself seems to take about 6% of total Prepare() + ExecuteScalar() time. The whole test run takes about 1 second longer with parsing.

Below are also CPU profiler results.

CPU usage WITHOUT parsing:
perf_no_parse

CPU usage WITH parsing:
perf_with_parse

With CPU profiler we can see the true performance hit from the SQL parsing. 16% of total CPU usage is consumed just for parsing the SQL. Total CPU time (ms) spend in Prepare() with parsing is higher by a factor of 5,0x. Profiler also shows that Prepare() with parsing takes 27% of CPU (ms) time when Prepare+ExecuteScalar is executed. Wihout parsing this is only 7%. Parsing is therefore a major contributor to the performance problem and not so much the networking. This could be now avoided altogether with IsPersisted feature. Without parsing even the initial NpgsqlConnection opening is slower than the subsequent Prepare() calls.
These kind of figures due to parsing are quite unacceptable in our application and as said we have avoided these by creating our own resource handling implementations around Npgsql. It would be wonderful to have these build in to the library.

I also examined the SQL parsing step with profiler but there is no single point that seems to take lot of CPU cycles. It is just generally intensive to parse the query and it gets worse linearly as expected compared to the pull requests O(1) dictionary lookup.

About my test setup:
Intel Core i7-3630QM (4 cores, 8 threads)
8GB RAM
256GB SSD
Windows 10
PostgreSQL 9.5.3 x64 and test run on localhost.

I know that it would be much more elegant to just persist the statements but we do not have API to initialize the NpgsqlStatements separately currently. This requires us to work with NpgsqlCommand and in my mind we should avoid the parsing step in IsPersisted feuture. This feature would have very positive performance implications in Npgsql and we should bring it as soon as possible. In the future the user initialized NpgsqlStatements (#1042) would probably also have the IsPersisted flags available. This feature would be easy to implement on top of the suggested PR.

BR
Markus

@roji

roji commented Jul 15, 2016 •

Copy link
Copy Markdown
Member

@MarkusSintonen, thanks for the detailed benchmark, it's always good to see hard numbers.

This is definitely a "low-latency" usage of Npgsql, which seems quite rare (but that doesn't mean it isn't important). It's worth nothing that if you benchmark against any non-localhost database (even in a LAN) the SQL parsing time is almost sure to be competely dominated by networking. I'm also wondering how the gains in avoiding SQL parsing compare against the overall query execution, including server-side processing - shaving off a few microseconds at the client side doesn't mean much if the entire query roundtrip takes 50 milliseconds.

More concretely, here's how I see things. #1042 is already planned for 3.2, as is the persistent prepared statement feature. #1042 removes SQL parsing altogether for those who use it, so it obviates the extra optimization involved in persisting the entire command rather than the statement. In other words, in 3.2 low-latency users should definitely use raw SQL mode.

I think this way everyone wins: you get to have the performance you want, without any SQL parsing going on, and we get the simpler/more elegant design of persisting prepared statements rather than commands. The only "drawback" is that you, as a low-latency user, are forced to use raw SQL mode, which will imply certain things (i.e. using PostgreSQL's positional arguments, using a PostgreSQL-specific batching API). But that seems reasonable to me.

If you agree with the above, I can dig up the work I've already done on this and finish work on it. I also intend to look at raw SQL mode (#1042) soon.

for (int i = 0; i < stmtNames.Count; i++)
{
var query = String.Format("DEALLOCATE \"{0}\";", stmtNames[i]);
PrependInternalMessage(QueryMessage.Populate(query));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this line fails if there are many deallocations, i.e. if there are enough to fill the 8192 byte send buffer.

@MarkusSintonen

Copy link
Copy Markdown
Contributor Author

@roji thank you for your work on this! I hope to see the #1042 implemented in near future.

@roji

roji commented Jul 18, 2016

Copy link
Copy Markdown
Member

@MarkusSintonen do you have any comments on my implementation, will you have time to review? Or should I go ahead and merge?

@MarkusSintonen

Copy link
Copy Markdown
Contributor Author

I'll move the conversation to your pull request at #1204

roji added a commit to roji/Npgsql that referenced this pull request Jul 18, 2016
Prepared statements can now be made to persist across pooled connection
Close/Open. This can provide a significant performance boost in
applications with short-lived connections and complex queries that take
long to plan.

Based on significant work by @MarkusSintonen in npgsql#1084 (thanks!)

Fixes npgsql#483
roji added a commit that referenced this pull request Jul 30, 2016
Prepared statements can now be made to persist across pooled connection
Close/Open. This can provide a significant performance boost in
applications with short-lived connections and complex queries that take
long to plan.

Based on significant work by @MarkusSintonen in #1084 (thanks!)

Fixes #483
roji added a commit that referenced this pull request Jul 30, 2016
Prepared statements can now be made to persist across pooled connection
Close/Open. This can provide a significant performance boost in
applications with short-lived connections and complex queries that take
long to plan.

Based on significant work by @MarkusSintonen in #1084 (thanks!)

Fixes #483
@roji

roji commented Jul 30, 2016

Copy link
Copy Markdown
Member

Replaced by adf1c0b

@roji roji closed this Jul 30, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants