Repository navigation
Description
To significantly increase perf under load, we may want to change the architecture of Npgsql to support multiplexing/pipelining. This issue is for having a high-level architectural discussion, here are some definitions to make sure everyone is on the same page:
- Batching. This refers to the ability of a program to use a specific driver API to send more than one SQL statement for execution. This is currently supported by packing multiple statements into
NpgsqlCommand.CommandText, separated by semicolons (although https://github.com/dotnet/corefx/issues/3688 exists for proposing a better API). - Pipelining: This refers to the ability of a single client to send a new statement before a previous statement has completed executing (and its resultset fully consumed). In practical terms this means executing
ExecuteReader()while a reader is still open on the connection. In the SQL Server world this is called MARS (Multiple Active Result Sets). - Multiplexing: This refers to the driver routing statements from different clients to different physical connections (can be seen as a sort of mutliple-producer-multiple-consumer model). The application no longer holds its own dedicated physical connection for any length of time.
Batching and pipelining provide the same benefits in many scenarios - pack multiple statements into the same roundtrip. However, there are some crucial differences:
- If SQL statements need to go out gradually, i.e. we don't have the full list of statements up-front, then pipelining provides a significant boost as it allows sending statements at any time. With batching we can send several statements, but then we're stuck waiting until the batch completes before being able to send another statement.
- Batching does have the advantage of packing everything up-front, doing a single I/O system call, and guaranteeing the requests will go out consolidated in a minimal number of TCP packets (potentially one). With pipelining the driver doesn't see all statements at once, so we perform several I/O system calls and sent several packets (unless we implement some sort Nagling, which doesn't seem to make much sense).
With multiplexing, an application no longer allocates (or rents) a physical connection for exclusive use, but sends statements via potentially different physical connections each time. The main perf advantage is that under load, when all physical connections are busy, a new statement can still be sent without waiting: as long as the TCP window isn't exhausted, we can always send our statement. Contrast this with the current model, where when all physical connections are in use, DbConnection.Open() blocks until one is made available. This could be have a significant impact.
Multiplexing is a pretty radical architectural change, but it's probably possible to implement this while still adhering to the ADO.NET API. Some notes:
- Pipelining is a subset of multiplexing - implementing the latter includes the former.
DbConnection.Open()becomes a no-opDbCommand.Execute*()select some physical connection and sends the statement over it. This is done according to a scheduling strategy (idle connections are obviously selected over busy ones, and we load-balance across busy connections etc.)- If
DbConnection.BeginTransaction()is called, we must fall back to the previous model, where a physical connection is exclusively allocated, for the duration of the transaction. - Note that there is some other connection state - temporary tables, parameter settings - an application relying on these will break down with multiplexing. This is probably a bit rare, and application can either work around the issue by using transactions (if the stateful resource is temporary), or by disabling multiplexing via a connection string parameter.
When multiplexing, the application attempts to read query resultsets in an order different from the order in which they were sent. This means that we must buffer entire resultsets (Npgsql currently buffers only rows). This isn't trivial and could trigger a perf degradation if we don't implement properly; buffers must be properly sized, recycled etc.- There's no longer any real resetting of the connection state, ever (unless we want to provide it as a user-facing API). We can also probably get rid of the prepended message mechanism internally.
Some relevant conversations: aspnet/DataAccessPerformance#42 (comment), https://groups.google.com/forum/#!topic/framework-benchmarks/A78HrYsz4AQ
/cc @YohDeadfall @benaadams @divega @ajcvickers @sebastienros
Activity
roji commentedon Jun 7, 2018
/cc @bgrainger
benaadams commentedon Jun 7, 2018
Pipelining works with the *Async model; however I think it would also break peoples assumptions (and maybe the contract) of ado.net; sort of treating the database client more like httpclient.
I doubt users would expect that would work; or even try it.
Multiplexing would bring the benefits of pipelining; plus more, but wouldn't require any changes to user code (apart from maybe opting in); and also work with sync/blocking calls as well as async.
So the advantage is definitely with multiplexing; from an end-user perspective.
From an implementation perspective; I can't comment 😄
roji commentedon Jun 7, 2018
I'm not 100% sure this wouldn't work with totally synchronous APIs as well: at the end of the day you'd (synchronously) write the protocol messages to the server, and then wait (instead of await) on something to get notified when your resultset has been buffered etc.
At least up to now I've been a bit zealous about providing 100% sync APIs alongside 100% async APIs in Npgsql, although we may consider dropping that in the future if it's too much trouble.
Really? I agree it looks weird because we're used to the current ADO.NET restrictions, but at the end of the day, why not... Again, for some applications this could be a serious perf boost (i.e. immediately forward incoming requests to the database as they come in, without waiting for ongoing database operations to complete). But in any case this would come for free with multiplexing as you wrote.
I completely agree, I definitely am not considering implementing just pipelining (without also doing multiplexing). But I do think it's useful to distinguish - people seem to use pipelining to mean different things etc.
YohDeadfall commentedon Jun 7, 2018
I like the idea, but I think that it shouldn't change user code too. The reason of that restriction is that there are provider agnostic applications and ORM libraries. Inviting @NickCraver as representative of the last one.
Mix batching with multiplexing. This approach decreases the count of TCP packets sent to a server by a single command, but it doesn't block other statements in the batch from processing while executing the first portion.
It would be better to have opt-in scenario rather than opt-out for compatibility reasons.
roji commentedon Jun 7, 2018
At the moment I can't see any reason for this to necessitate any changes in user code - it should be possible to do this with the traditional ADO.NET API. You continue to call
NpgsqlConnection.Open()(although it's basically a no-op), create commands and execute them as usual. The only exception is if your application relies on connection state (e.g. temporary tables, session parameters) but that's out of the scope of ADO.NET in any case.Yes, there's no reason for applications not to continue using the batching API, which will continue to provide better perf via less system calls and TCP packet consolidation. This should still be the best practice when you know up-front you have more than one statement to send. It should be possible to pipeline and multiplex batches just like single statements.
We can always have the opt-in vs. opt-out discussion later. Again, if things go as planned there shouldn't be any reason to expect breakage (except for connection state issues). If you're talking about general instability because this is a new and complex architectural change, then unfortunately that will affect users of the new driver regardless of whether they turn on multiplexing or not... But I think it's a bit early for this question.
pablocar80 commentedon Jun 8, 2018
I see 2 huge benefits from pipelining: (1) easily migrate SQL Server applications that use MARS without redesign efforts, and (2) allow to write client code such that the output of a 2nd reader determines whether we should keep retrieving records on the 1st reader.
roji commentedon Jun 8, 2018
@pablocar80,
That's true, although to be honest an issue tracking MARS (#462) has been around since forever and we haven't seen that many requests or votes. AFAIK SQL Server is one of the rare database drivers that provides MARS, so the portability problem exists with other drivers as well.
Also true, but that would mean that resultsets need to be buffered, so to a certain extent you're reading all the records on the 1st reader anyway (but it's true you don't necessarily have to process/parse them).
Note also that this is possible today, simply by having 2 connections - a bit more cumbersome but otherwise very similar.
pablocar80 commentedon Jun 8, 2018
For (1) other databases have the same problem, definitely. For the low number of requests, this is a feature interesting only for people who aren't currently using Postgres, and those may be less likely to know about this forum and comment. I tried to look up how many people actually use MARS and haven't found any information, it may be a low number after all.
I forgot to point out for (2) that the scenario for it is when you need to have both readers under the same transaction, without having to use distributed transactions. The other alternative of course is to move everything to PL/pgSQL whenever that's possible.
roji commentedon Feb 22, 2019
See great post on pipelining/multiplexing on the Redis client: https://stackexchange.github.io/StackExchange.Redis/PipelinesMultiplexers
faibistes commentedon Mar 19, 2019
I guess that lots of people would like this to be implemented, but they don't even know it. 90% of the people that start coding with .Net use SQL Server as their DB of choice, because that's what MS feeds them and it's the easy path. They use EF, so there's no SQL, so they think that changing the database is as easy as UseNpsql(). They try it and see those weird "a second operation started" errors. Then they google "a second operation started"+npgsql, and the first dozen of hits is about not using DI correctly. So they think Npgsql is just broken, quit and go back to MSSQL. And those of them who find out that it's about MARS, see what's involved in changing their codebase (and the care they need to take in future developments), and most of them quit too.
Right now I get a couple of them from time to time, and I can't look for every lazy access and fix it with ToList()
2 remaining items
roji commentedon Jun 16, 2020
Done in 4bd4115. See PR #2993, as well as the earlier version #2852.
mvonballmo commentedon Jan 8, 2021
I'd like to try this feature, but I'm having a bit of trouble. I see in the release notes that,
I've passed the
Multiplexingoption in the connection string, but get "Synchronous command execution is not supported when multiplexing is on" when I post the first command withExecuteNonQuery(). I see that the internal command has a parameter calledasync, which must be true, but am not sure how to set that. Do I have to callNpgSqlCommand.ExecuteNonQueryAsync()instead?If I have to wait on
NpgSqlCommand.ExecuteNonQueryAsync(), that would be a significant reworking of my code (which generally usesIDbCommandand isn't async), so I'd like to be sure first.I thought that might be it, but then saw a few comments about "not having to change user code", so I figured I would ask first. Thanks for any tips or help you can provide.
roji commentedon Jan 8, 2021
Yes, only async APIs are supported when using multiplexing. It's generally recommended to do async I/O in .NET nowadays, regardless of multiplexing.
mvonballmo commentedon Jan 8, 2021
Thanks for the super-fast response! And thanks for adding multi-plexing/pipelining to make MARS possible!
I was afraid you'd say that. I was hoping to be able to handle the two issues separately (enabling multi-plexing and moving to the async API). The comments here suggested that multiplexing basically provides support for MARS, which eases migration from those using SQL Server, but only if you're using the async API, which is an important caveat because very few projects are using that from what I've seen from examples, tutorials (even those from MS itself, mysteriously).
Just for a little context, I've got a larger framework that integrates MS-SQL, SQLAnywhere, and PostgreSql as drivers. It's already quite established (13 years). It's actually quite a healthy and modern project, for all that ... but it doesn't use async data access.
We've recently wanted to re-enable MARS support for performance reasons for some queries. MS-SQL requires only a parameter in the connection string; SQL Anywhere supports it out of the box; PostgreSql now supports it with a parameter in the connection string, but you have to use the async API, so I've a bit of work to do to support MARS under PostgreSql. Not only that, but because the async API is mysteriously not on the
IDbCommandinterface (it's only present on theDbCommandclass), it seems I get to change the abstraction we're using as well.As you correctly pointed out, it is "generally recommended to do async I/O", but I'm not...and there is quite a bit of framework code to restructure to get everything async. I'm going to go out on a limb and guess that most projects that will want to move from SQL Server, hoping that their MARS code works, will discover that this caveat changes the estimated amount of work significantly. There's nothing to be done, of course, but it's more a suggestion to document that clearly.
Thanks again for the quick reply. I'll let you know how it goes.
MaceWindu commentedon Jan 8, 2021
@roji, Maybe it will be interesting for you. I'm working on enabling MARS-like scenarios for linq2db here linq2db/linq2db#2728 and found out that actually most of ADO.NET providers we support could execute multiple data reader queries:
roji commentedon Jan 8, 2021
@MaceWindu thanks for this info - I've posted it on the issue tracking MARS support (#462 (comment)). I've also posted some further notes - I wonder if on DB2 and Oracle, MARS is actually efficient (as it's supposed to be on SQL Server). For embedded databases (Sqlite, SqlCE) it makes sense that MARS can be supported - there's no networking involved.
KrzysztofBranicki commentedon May 12, 2022
@roji First thanks for working on this, it's great feature for scalability. I have question regarding status of this feature, release notes for Npgsql 5.0 say that connection multiplexing is experimental feature which is turned of by default. In release notes for Npgsql 6.0 there is not mention of connection-multiplexing. Is it still considered to be experimental? Would you recommend enabling it on production environment? Is any more work planned in this area?
roji commentedon May 15, 2022
@KrzysztofBranicki thanks for your interest... I don't think we've done significant work in 6.0 on multiplexing, but we do have #3991 for 7.0, which is about making the feature more suitable for users. Specifically, the API for using multiplexing may change with the introduction of DbDataSource (also tracked in #3991.
Having said that, if you're willing to be a bit cutting-edge, multiplexing should work fine as-is today, and it would be great to get some more feedback that would help stabilize it. We'll support you with any questions/guidance.
KrzysztofBranicki commentedon Jun 8, 2022
@roji we encountered
NotSupportedExceptionwhen using batch apiExplicit preparation not supported with multiplexing, we will try more if we decide that we want to temporarily disable prepared statements. Will preparation be supported with multiplexing in 7.0?roji commentedon Jun 11, 2022
@KrzysztofBranicki explicit preparation isn't (currently) supposed to work at all in multiplexing - when using the batching API or otherwise. However, automatic preparation should work just fine - and is in many cases better anyway. Have you tried that?
KrzysztofBranicki commentedon Jun 13, 2022
@roji no we haven't tried automatic preparation yet, so far we wanted to do preparation explicitly in places where we know we have a hot path and same statement is used very frequently. We will consider performing some tests with automatic preparation.
roji commentedon Jun 13, 2022
@KrzysztofBranicki the problem with explicit preparation is that you do it on an NpgsqlCommand instance, and then execute that command. But with multiplexing, there's no guarantee the same connection will get used for both operations.
See #4509 for an alternative, up-front explicit preparation API which I'll probably do for 7.0, which is both more efficient and compatible with multiplexing. In the meantime, I'd recommend looking at automatic preparation.
KrzysztofBranicki commentedon Jun 14, 2022
@roji thanks for the explanation, we will definitely test automatic preparation if we be able to find some time.