Skip to content
This repository was archived by the owner on Mar 24, 2026. It is now read-only.
This repository was archived by the owner on Mar 24, 2026. It is now read-only.

Database commands coalescing #7019

Closed
Closed

Description

@sebastienros

The Npgsql (PostgresQL driver for .NET) contributors have been looking into other drivers implementation to understand where improvements can be done.

Here is a current picture for the multi-queries scenario:

image

There are several frameworks around 30-34K (not all displayed here) and then a subsequent jump to ~60K.

After analyzing the network traffic between the Drogon framework and the Postgres server, which is represented in the following screenshot and validated by other specific payloads, it appears that queries issued from multiple http requests are coalesced in the same network packets and executed with a single "SYNC" command which will tell Postgres to execute them "as a batch".

image

Bundling together multiple commands in a single Sync batch has important consequences: if any command errors (e.g. unique constraint violation), all later commands are skipped until the Sync. Even more importantly, all commands are implicitly part of the same transaction.

Here we have not only implicit batching for the same request (20 queries), but more importantly batching across requests.

Our interpretation of the TechEmpower rule below leads us to believe that this method violates those rules

Except where noted, all database queries should be delivered to the database servers as-is and not coalesced or deduplicated at the database driver. In all cases where a database query is required, it is expected that the query will reach and execute on the database server. However, it is permissible to pipeline traffic between the application and database as a network-level optimization. That is, two or more separate queries may be delivered from the application to the database in a single transmission over the network, and likewise for query results from the database back to the application, as long as the queries themselves are executed separately on the database server and not combined into a single complex query.

We haven't looked if the other frameworks showing the same high performance are using the same technique.

/cc @an-tao @roji

Activity

  1. roji commented on Jan 10, 2022

    @roji
    Contributor

    Note: most of the investigation work above was done by @NinoFloris and @vonzshik from the Npgsql project.

  2. an-tao commented on Jan 11, 2022

    @an-tao
    Contributor

    https://2ndquadrant.github.io/postgres/libpq-batch-mode.html

    here I used the batch mode of postgresql driver, this work has been done two years ago, and the coalescing happens only when:

    1. all sqls are read-only;
    2. all sqls in pipeline are in the same call stack of the current event-loop;
      so if any wrriten sql is executed, the sync comand is sent immediately, you could see the network traffic in the update test to comfirm it. The rules say it's not permited to combine mutiple sqls into a single complex query, I don't think drogon broke it because every reading sql is executed separately (they are in the same batch and sent together , it's a network-level optimization)
  3. marty1885 commented on Jan 11, 2022

    @marty1885

    Hi, I'm another maintainer of Drogon.

    I've chatted with @an-tao privately. He is not as fluent in English. Poke me if you need help explaining this reply. Please allow me to explain my view and response of the rules in detail. My views may differ with his, so I don't represent his position. I think this in a reasonable framework-level optimization. Hopefully helping both parties understand the differences.

    all database queries should be delivered to the database servers as-is and not coalesced or deduplicated at the database driver.

    In drogon with PQ-batch support. We control when the sync happens. It's a framework level optimization. To be specific, a sync happens when a SQL query that modifies data occurs, enough commands are batched or when the web application wasn't busy adding more queries to the batch. Therefor a batch only consists of read queries or ends with a write query. Any write fails (transaction conflict, uniqueness failure, etc..) will not cause reads to fail. And no subsequent commands exists to be skipped.

    In all cases where a database query is required, it is expected that the query will reach and execute on the database server.

    Besides above. The SQL banchmark only reads from the DB. Thus it's impossible to have a transaction error causing queries to fail. The test itself guarantee that. I think we are safe in this regard too.

    Furthermore, I also think this is a reasonable optimization in practice. Since a batch always ends with a write. We guarantee all reads are executed (Note that SELECT .. FOR UPDATE is considered writing). The only edge case is when the web app runs an intentionally bad SELECT query. Which could get placed in the middle of a batch. But I consider it an application bug and I won't blame the framework for it.

  4. Brar commented on Jan 11, 2022

    @Brar

    @marty1885
    Just for clarification. By "intentionally bad SELECT query" you mean any SELECT query that fails and causes the whole transaction to rollback instead of only the failing query - no?

  5. marty1885 commented on Jan 11, 2022

    @marty1885

    No, I mean by some sequence of non-transaction queries.

    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ....");
    co_await db->execSqlCoro("SELECT xxx FROM non_exist_table WHERE ....");;
    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ...."); // This gets dropped.

    I think all queries in transaction are considered writing. Thus always not batched. Is it? If not, I think we need to add a special case. In any case, it doesn't invalidate this optimization. @an-tao

    Also I think the performance benefits comes from sending all the queries at the same time. Only sending sync at the end is quark of pq_batch. We could spend some time look into the updated libpq and resolve the entire issue all together.

  6. vonzshik commented on Jan 11, 2022

    @vonzshik

    We guarantee all reads are executed (Note that SELECT .. FOR UPDATE is considered writing).

    @marty1885 I assume you're talking about query parsing, which doesn't check for function and procedure calls (which can do inserts/updates). There is also a problem of PG adding a new keyword (however improbable it is), which might have side effects.

    But I consider it an application bug and I won't blame the framework for it.

    Speaking from my experience, I'm working on an app, which allows to generate queries via SQL with a bit of a meta language. As an example:

    SELECT *
    FROM "SomeTable"
    WHERE 1 = 1
    #param(ID, "ID")
    #param(Value, "Value")
    

    A user via UI can specify whether he wants to filter by ID or by Value (or both), and the corresponding SQL is generated with the required parameters. With some queries taking a hundreds of lines, it's not that rare for some combinations of parameters to generate an invalid SQL. While it's definitely not great, there is nothing requiring immediate fixing, since only the specific combination is broken. But if we were using drogon, that would start breaking unrelated queries, making that issue critical and requiring immediate fixing.

    Just wondering, is batching (and possible issues from it) mentioned in drogon's documentation?

  7. Brar commented on Jan 11, 2022

    @Brar

    Sorry, by transaction I meant everything that the driver puts before a sync packet.

    The issue I see is something like the following:

    co_await db->execSqlCoro("SET statement_timeout TO 10000");
    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ....");
    
    // Simulates a query that might happen to take slightly longer than statement_timeout under some load conditions
    co_await db->execSqlCoro("SELECT pg_sleep(15)");
    
    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ...."); // This gets dropped.
  8. roji commented on Jan 11, 2022

    @roji
    Contributor

    We guarantee all reads are executed (Note that SELECT .. FOR UPDATE is considered writing).

    @marty1885 I assume you're talking about query parsing, which doesn't check for function and procedure calls (which can do inserts/updates). There is also a problem of PG adding a new keyword (however improbable it is), which might have side effects.

    I want to make sure this crucial point by @vonzshik is clear... As I understand it, if a command is executed which happens to SELECT from a function, and around the same time another unrelated command is executed which produces an error (e.g. unique constraint violation), then any side-effects from the function may get rolled back, without any indication to the program that this happened. That is, the user code executing the function will continue as if the function completed successfully and its side effects were committed, when in fact they were silently rolled back.

    There may be other such scenarios where "implicit" side-effects aren't detected. So I think the idea that a database driver can reliably parse SQL to know whether it's read-only is quite problematic.

    @marty1885, you wrote:

    Also I think the performance benefits comes from sending all the queries at the same time.

    In our experience, sending the Sync at the end has quite a significant impact on performance (FWIW Npgsql does send all commands at the same time like Drogon, but with a Sync after each command instead of at the end). This is likely related with the PostgreSQL MVCC overhead of creating and committing many small transactions (Npgsql) vs. a single transaction which encompasses all commands (Drogon).

    Only sending sync at the end is quark of pq_batch. We could spend some time look into the updated libpq and resolve the entire issue all together.

    Importantly, Sync at the end is indeed the desirable behavior when application code wants to send a set of related commands, as a batch: either all commands complete or none do (I believe this was the intent of the PG pipelining mode). The crucial difference is that the application explicitly opts into this behavior - via some API gesture - whereas Drogon is applying this implicitly on unrelated commands, under the hood.

  9. marty1885 commented on Jan 11, 2022

    @marty1885

    @vonzshik

    I assume you're talking about query parsing, which doesn't check for function and procedure calls (which can do inserts/updates). There is also a problem of PG adding a new keyword (however improbable it is), which might have side effects.

    Yeah. We noticed that earlier too. We will patch that.

    Just wondering, is batching (and possible issues from it) mentioned in drogon's documentation?

    Drogon's batching support requires a patched version of libpq (we haven't implement support after the feature being upstreamed). So we expect the users to know what they get getting themselves into at this point.

    @Brar

    Yeah.. that's an issue. But in a different way. Thanks for finding it.

    co_await db->execSqlCoro("SELECT pg_sleep(15)"); suspends current coroutine from execution. No further code in the same coroutine gets executed. Since that statement always error out, it causes co_await <awaiter> to throw exception. And other SELECT statements in the same batch would also error out and throw. (My bad for the code I shared above. It's a quick illustration)

    // coroutine 1
    {
    co_await db->execSqlCoro("SELECT pg_sleep(15)"); // This fails. Throw
    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ...."); // CPU never runs this because of throw
    }
    
    // coroutine 2
    {
    // Throws because the statement gets bundled and gets skipped.
    co_await db->execSqlCoro("SELECT xxx FROM my_table WHERE ....");
    }

    @roji

    In our experience, sending the Sync at the end has quite a significant impact on performance

    Thanks for pointing it out. I'm discussing with @an-tao to determine that's the best action to fix this. Likely we'll add an option to opt-in to batch mode if we detect batch support.


    Back to the original issue. I still think batching should be allowed in benchmark as it produces known behavior and does not break program flow when error happens. And it does not violate the rules under the benchmark.

  10. roji commented on Jan 11, 2022

    @roji
    Contributor

    I assume you're talking about query parsing, which doesn't check for function and procedure calls (which can do inserts/updates). There is also a problem of PG adding a new keyword (however improbable it is), which might have side effects.

    Yeah. We noticed that earlier too. We will patch that.

    How do you propose to patch this? If the idea is to disable batching, that would mean the driver parsing to detect arbitrary function calls within arbitrary user SQL - that once again sounds quite problematic and brittle?

    Back to the original issue. I still think batching should be allowed in benchmark as it produces known behavior and does not break program flow when error happens. And it does not violate the rules under the benchmark.

    Stepping back here, all the various problems signaled above a result of Drogon applying implicit batching under the hood; this technique changes actual program behavior in a significant way - and does break program flow in ways that are very hard to predict and diagnose (as everything depends on timing). It's hard to see how this could be treated as a transparent network optimization.

    Compare this with sending all the commands together, but with Syncs between each command; this indeed guarantees at the protocol level that each command runs independently of each other, and errors are guaranteed to not affect unrelated commands; IMHO this is what is meant by a network-level optimization.

  11. marty1885 commented on Jan 11, 2022

    @marty1885

    How do you propose to patch this? If the idea is to disable batching, that would mean the driver parsing to detect arbitrary function calls within arbitrary user SQL - that once again sounds quite problematic and brittle?

    We'll add additional checks to prevent common cases. I think it's quite rate for this to happen since we haven't get user complaining it yet. Then figure out how to solve this.

    Drogon applying implicit batching under the hood; this technique changes actual program behavior in a significant way - and does break program flow in ways that are very hard to predict and diagnose ... and errors are guaranteed to not affect unrelated commands; IMHO this is what is meant by a network-level optimization.

    I think this is acceptable. At least for me, as a C++ developer. We are used to dealing with data races and feels fine as long as timing doesn't crash the application or causes unrecoverable state change. It's perfectly ok for lock-free C++ algorithms to return error when stuff doesn't work this try. This characteristic gives me the same vibe. The maintainers are also treating SQL this way.

    So in conclusion, is the following allowed?

    • Drogon must send sync for every command
    • Add an batch flag to batch commands (and don't sync every command) that we know does not write
  12. roji commented on Jan 11, 2022

    @roji
    Contributor

    Drogon applying implicit batching under the hood; this technique changes actual program behavior in a significant way - and does break program flow in ways that are very hard to predict and diagnose ... and errors are guaranteed to not affect unrelated commands; IMHO this is what is meant by a network-level optimization.

    I think this is acceptable. At least for me, as a C++ developer. We are used to dealing with data races and feels fine as long as timing doesn't crash the application or causes unrecoverable state change. It's perfectly ok for lock-free C++ algorithms to return error when stuff doesn't work this try. This characteristic gives me the same vibe. The maintainers are also treating SQL this way.

    I agree that if an error were returned and the program could try again, this would maybe be acceptable. But here we're talking about database changes being silently rolled back - without an error - because some other unrelated command happened to error. This is quite different from attempting a lock-free operation and retrying it; it's more like your lock-free operation saying it succeeded, when in fact it didn't. I have no idea how I'd write reliable code in this situation, and so IMHO this does qualify as causing "unrecoverable state change". Regardless of how rare such a scenario is or what kind of SQL it requires from users, I don't believe a database driver should do something like this.

    I do agree that it would be helpful for the benchmark rules to be more explicit on these nuances - IMHO it's important for the benchmarks not to encourage unsafe/dangerous driver behavior (as least according to my viewpoint).

  13. marty1885 commented on Jan 11, 2022

    @marty1885

    database changes being silently rolled back - without an error

    I to think about this. I think the current behavior is that driver notices something failed. Then framework understands some SQL commands gets dropped. Then the entire list of yet-to-be executed SQL calls throws error. Which is then recoverable.

    Please help us determine what's the acceptable behavior for the benchmark. We will update our benchmark and framework.

  14. roji commented on Jan 11, 2022

    @roji
    Contributor

    database changes being silently rolled back - without an error

    I to think about this. I think the current behavior is that driver notices something failed. Then framework understands some SQL commands gets dropped. Then the entire list of yet-to-be executed SQL calls throws error. Which is then recoverable.

    @marty1885 I'm not referring to yet-to-be-executed SQL statements - I do understand these are skipped and the user gets an error. The problem is with SQL statements which were already previously executed, already completed, and are now rolled back because of the error.

  15. marty1885 commented on Jan 11, 2022

    @marty1885

    Ahhh... I didn't realize that

  16. 46 remaining items

  17. roji commented on Feb 18, 2022

    @roji
    Contributor

    Stepping back and trying to be crystal clear: there's the question of whether implicit batching of unrelated commands is safe, and there's the question of whether it should be allowed in the benchmarks, according to the rules. The two questions are related, though they are separate.

    Yes, I agree (and always have) that there are specific scenarios where implicit batching is safe - read-only SQL chains, and also read-only chains followed by a single update, after which comes the Sync (the latter scenario isn't something we've been discussing recently, so I haven't been mentioning it). You are arguing that users should be allowed to explicitly opt into this when they know their workload happens to match the above; I'd avoid this in a production, real-world driver since the consequences of getting it wrong are disasterous (silent data loss). Even if this discussion only results in some drivers putting this behind an opt-in (which seems to be the case), then I feel something good has already come out of this.

    But in any case, every driver writer does and will do what they think is right, which is where we come to the 2nd question - should TE allow implicit batching.

    My view of the TE benchmarks, is that they're supposed to show you typical or standard performance for a given scenario; Fortunes is supposed to tell you e.g. how many RPS a framework does when executing a single database query. Allowing the above optimization would instead show RPS numbers for queries which are known to be side-effect free; that's quite a restriction: we're no longer discussing the perf of any single query, but of a very specific subset of queries. Now, it's true that Fortunes happens to be compatible with this optimization from a safety point of view, but IMHO the idea is to use Fortunes as a proxy for general query performance; otherwise the result becomes rather meaningless.

    This is what I meant with my "ad absurdum" example memoization - it's just another example of a possible driver optimization. Although it could be a valid thing to do in the real world (no potential safety issues in any case), this isn't something that we want used in the benchmarks, since it doesn't measure what we want (general database query performance): it would provide us with results that are only relevant when the same queries are repeated over and over again (and lagging results are OK). In the same way, implicit batching provides us with results that are only relevant when queries are known to be 100% side-effect-free.

    To summarize, not everything that can speed up perf is something we necessarily want allowed in these benchmarks, and just like TE already disallows memoization and coalescing of multiple SQL commands into one, I believe it should disallow this optimization, which is only safe for use in very specific scenarios as we've already agreed. I don't think this should necessarily limit innovation or experimentation - but it would make sure that we're showing apples-to-apples numbers for the same generalized scenarios.

    I hope the above accurately (and respectfully!) represents the state of the discussion and our respective positions.

  18. michaelhixson commented on Mar 7, 2022

    @michaelhixson
    Contributor

    I'd propose something along the lines of:

    If any pipelining or network optimization is performed, then the execution behavior and semantics must match what they would be if the multiple SQL statements were executed without the optimization, i.e. in separate roundtrips. For example, it is forbidden to perform any optimization could change the transactionality and/or error handling of the SQL statements. To avoid any doubt, such optimizations are forbidden even if they wouldn't produce the behavioral change with the specific SQL statements of the TechEmpower benchmarks, but would produce it with other statements a user might supply.

    I agree with this proposed requirement.

    I tried to articulate this position in a Google Group thread from 2018 -- read from "I bet a compliant pipelining
    implementation would" onwards. These clarifications never made it into the official requirements, and I think the proposed addition does a good job of that.

    It might be worth clarifying with an example for the Postgres protocol specifically, as it sounds like the only way to implement this is to put a sync message between each query.

  19. NateBrady23 commented on Mar 8, 2022

    @NateBrady23
    Member

    We're going to update the requirements with the proposed text above. Thank you everybody for your contributions to this discussion. We won't have any automated way to test for violating this requirement right away, so we'll continue to rely on the community to politely point out the frameworks that do. Thanks again!

  20. roji commented on Mar 8, 2022

    @roji
    Contributor

    @nbrady-techempower thanks for your patience with this long thread!

    If you do decide to implement verification for this, I think @billywhizz's suggestion above is a good way to do that:

    it should be possible to tighten the current checks by verifying the number of txns for each run is same as number of http responses received - so, at least one txn per http response received, no? this would disallow cross request batching for single and fortunes and would allow per request batching for the multi and update queries and make cross-request batching pretty much impossible on those too.

  21. billywhizz commented on Mar 11, 2022

    @billywhizz
    Contributor

    sorry to continue this.... =)

    this new requirement still seems a bit unclear to me, especially with @roji's response re. my proposed verification which would allow pipelining, but only within each http request. just to try to clarify, is this compliant with the new rule? i think it should be.

    for each http request to
    /db
    we put at least

    BIND
    EXEC
    SYNC
    

    on the wire

    for each http request to
    /fortune
    we put at least

    BIND
    EXEC
    SYNC
    

    on the wire

    for each http request to
    /query?q=N
    we put at least

    BIND
    EXEC
    ... repeat N - 1 times
    SYNC
    

    on the wire

    for each request
    /update?q=N
    we put at least

    BIND
    EXEC
    ... repeat N - 1 times
    BIND
    EXEC
    SYNC
    

    on the wire

    so, essentially, each http request must have an enclosing transaction and transactions/syncpoints cannot be shared across http requests.

    OR

    are we saying every single sql command must be wrapped in a transaction, so the /query and /update http requests where N = 20 will result in 20 and 21 syncpoints instead of 1?

  22. michaelhixson commented on Mar 11, 2022

    @michaelhixson
    Contributor

    OR

    are we saying every single sql command must be wrapped in a transaction, so the /query and /update http requests where N = 20 will result in 20 and 21 syncpoints instead of 1?

    This one.

    I'm wondering if there is a way we can make the requirement clearer.

    From item 7 under General Test Requirements:

    That is, two or more separate queries may be delivered from the application to the database in a single transmission over the network, and likewise for query results from the database back to the application, as long as the queries themselves are executed separately on the database server and not combined into a single complex query.

    Would you have asked the same question if we'd added "or transaction" to the end of that?

    ... as long as the queries themselves are executed separately on the database server and not combined into a single complex query or transaction.

    We could also get really specific about Postgres in there. We could add a sentence like this:

    If using PostgreSQL's extended query protocol, each query must be separated by a Sync message.

  23. Brar commented on Mar 11, 2022

    @Brar

    I'm wondering if there is a way we can make the requirement clearer.

    After seeing the different opinions around this topic I'd say that it cannot be too clear.

    Would you have asked the same question if we'd added "or transaction" to the end of that?

    I think that would help to specify the intent you stated above in a rather database-agnostic way, even if it may not completely resolve misunderstanding regarding the behavior around PostgreSQL's Sync message since it's effect on transactions is not documented very clearly and is not totally obvious.

    We could also get really specific about Postgres in there. We could add a sentence like this:

    If using PostgreSQL's extended query protocol, each query must be separated by a Sync message.

    In my opinion that would make it crystal clear, resolve any further misunderstandings about your intent and hit the major issue about comparability of driver implementations that has been discussed here.
    If you specify it this way, people may challenge your intent and ask the question whether this is a useless limitation you force upon driver implementations but most certainly wouldn't misunderstand it. Depending on the depth of their insight you could point them to this thread to better understand the issues around sync or just tell them that the results of optimizations beyond this point are hard to generalize and are not a goal you are pursuing with the current tests.
    The compliance of a driver implementation with this rule would also be measurable/provable on the network level (e. g. via wireshark).

  24. billywhizz commented on Mar 12, 2022

    @billywhizz
    Contributor

    @Brar @michaelhixson @roji @nbrady-techempower

    If you specify it this way, people may challenge your intent and ask the question whether this is a useless limitation you force upon driver implementations but most certainly wouldn't misunderstand it.

    i agree this would be much clearer but i think it will need a verification implemented in the tfb toolset to enforce this clarified rule, otherwise nobody can have any real confidence in which frameworks are compliant or not without going and testing themselves. i might try to do some work on this over next couple weeks if nobody at techempower is available right now and you agree it would be worth doing.

    PS - this response from @michaelhixson on that google group thread is i think the clearest statement of what is actually required: https://groups.google.com/g/framework-benchmarks/c/A78HrYsz4AQ/m/OfFev6s_AwAJ. i wish it had been posted here earlier. 🙄

  25. michaelhixson commented on Mar 14, 2022

    @michaelhixson
    Contributor

    i agree this would be much clearer but i think it will need a verification implemented in the tfb toolset to enforce this clarified rule, otherwise nobody can have any real confidence in which frameworks are compliant or not without going and testing themselves. i might try to do some work on this over next couple weeks if nobody at techempower is available right now and you agree it would be worth doing.

    Right now we're trying to avoid creating more code in TFB's existing Python toolset that we'd have to port over to our new work-in-progress toolset. I think this verification is worth adding, but now is not a good time.

    If we were going to add this to the existing toolset, my hope is that it would fit in to the "run siege, then query the database for stats" verifications that we have already.

    Related code:

    • AbstractDatabase.verify_queries
      def verify_queries(cls, config, table_name, url, concurrency=512, count=2, check_updates=False):
      '''
      Verify query and row numbers for table_name.
      Retrieve from the database statistics of the number of queries made, the number of rows read, eventually the number of updated rows.
      Run 2 repetitions of http requests at the concurrency level 512 with siege.
      Retrieve statistics again, calculate the number of queries made and the number of rows read.
      '''
    • postgres.Database.get_queries
      def get_queries(cls, config):
      return cls.__exec_and_fetchone(config, "SELECT SUM(calls) FROM pg_stat_statements WHERE query ~* '[[:<:]]%s[[:>:]]'" % cls.tbl_name)

    I can't tell if Postgres (or any other database) exposes the stats we need here, though. Nothing is jumping out at me from the pg_stat_statements table that we're currently using or from any of the other pg_stat tables.

    If anyone can find out where Postgres stores the information we'd need here, that would be useful to us. If the change to the Python toolset would be small enough, we'd consider making it.

  26. roji commented on Mar 14, 2022

    @roji
    Contributor

    If anyone can find out where Postgres stores the information we'd need here, that would be useful to us. If the change to the Python toolset would be small enough, we'd consider making it.

    So if we're following @billywhizz's suggestion of checking the number of transactions against the number of HTTP requests (and calculated number of DB requests done inside them), then that information should be available in pg_stat_database.xact_commit (docs) (suggested above). You'd sample this value before starting the benchmark, and then ensure that after the benchmark it's equal to the total number of statements that were supposed to be issued.

  27. michaelhixson commented on Mar 22, 2022

    @michaelhixson
    Contributor

    I made those two small edits to the requirements: "or transaction" and "If using PostgreSQL...".

    I tried implementing the verification changes using pg_stat_database.xact_commit, but I couldn't get it working correctly. The xact_commit number seems to lag behind what I'd expect. In manual testing, sending a second request makes the number "catch up" to what it should have been after the first request. In automatic verification, the number is much more than 1 request short and it's very inconsistent. I'm not sure what's going on there.

    I pushed my (failing) work in progress to a branch: master...michaelhixson:batch-query-verification

  28. billywhizz commented on Mar 22, 2022

    @billywhizz
    Contributor

    I tried implementing the verification changes using pg_stat_database.xact_commit, but I couldn't get it working correctly. The xact_commit number seems to lag behind what I'd expect. In manual testing, sending a second request makes the number "catch up" to what it should have been after the first request. In automatic verification, the number is much more than 1 request short and it's very inconsistent. I'm not sure what's going on there.

    yep. i saw this same behaviour with xact_commit when i tried it a few weeks ago. didn't have time to investigate why. maybe something that should be raised with the pg devs?

  29. Brar commented on Mar 22, 2022

    @Brar

    Maybe the following information about the statistics collector may help:

    When using the statistics to monitor collected data, it is important to realize that the information does not update instantaneously. Each individual server process transmits new statistical counts to the collector just before going idle; so a query or transaction still in progress does not affect the displayed totals. Also, the collector itself emits a new report at most once per PGSTAT_STAT_INTERVAL milliseconds (500 ms unless altered while building the server). So the displayed information lags behind actual activity.

    Source: https://www.postgresql.org/docs/current/monitoring-stats.html#MONITORING-STATS-VIEWS

  30. stephenh commented on Sep 18, 2022

    @stephenh

    I am wary of "yet another opinion", but FWIW I am not a low-level framework optimizer (like @billywhizz :-D and others on this thread), but I am an application-/orm-builder and I could see @billywhizz 's outline of:

    for each request /update?q=N -->

    BIND
    EXEC
    ... repeat N - 1 times
    BIND
    EXEC
    SYNC
    

    Being done safely & automatically for users of ORMs that use a Unit of Work pattern:

    // called for each request to /update
    async function handleUpdate(n: number) {
      await uow.transaction(async (uow) => {
        await Promise.all(zeroTo(n).map(async () => {
          const w = await uow.load(World, random());
          w.randomNumber = random();
        }));
        // The ORM diffs/sends UPDATE(s) automatically when lambda finishes
      });
    

    There are:

    • No hand-written queries here (i.e. to the concern that "skipping SYNC relies on the programmer knowing what they're doing / writing side-effect-free queries"; here the ORM is driving that and it knows/controls the queries),
    • The code is very high-level/realistic production code, i.e. not a micro-optimization just to please the TechEmpower benchmark

    And so, AFAIU in this model, the per-request pipelining that @billywhizz proposed would actually be safe & kosher?

    Even if it's not allowed by TechEmpower, I want to get my ORM to do that someday. :-D

    (I get the push back that cross-request pipelining is even more esoteric, although I wonder if an ORM like ^ could still safely take advantage of it (when outside of transactions), again by knowing/controlling the queries, which given the ORM-focus of the TechEmpower benchmark, again seems kosher.)

    (...also I wonder if just saying updates?q=N endpoint must use a transaction would more succinctly highlight that each request must use its own connection and not multiplex a single connection; surely that was discussed, but I didn't see it go by.)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions