You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The SQL Server provider has some sort of bulk insert optimization, look into it. At the most extreme we can do a COPY operation, although that would probably be going a bit overboard.
Reacted by Per Lundberg, tiwarijyoti, Steve Hansen, bugproof, Tomasz Grażyński, Ryouko Konpaku, Victor Lee, Brecht Carlier, Douglas Gaskell, Ben Longo and 4 more
Agree, this would be great. Here is a link which describes how it can be done with the ADO.NET provider for SQL Server. Some sample code taken from that page:
If we could get an API that is basically swapping SqlBulkCopy there to NpgsqlBulkCopy instead, that would be awesome. (Of course, anyone who has worked with DataTables much knows that they are awkward and painful, but perhaps for this kind of use case it makes at least some sense...)
This issue is about using that bulk copy API from Npgsql's Entity Framework Core provider. EF Core already supports batched updates, where if you do several updates and then call SaveChanges(), these will all be done in a single roundtrip (rather than a roundtrip-per-update). It's technically possible to further optimize this, checking if a large group of these updates happen to be inserts and to use bulk copy in that case.
This is far from a trivial change, and we need to benchmark first to see if the performance benefits (i.e. bulk copy vs. batched inserts) justify it.
Reacted by bugproof, Ryan Elian, Mark Francis and Ryouko Konpaku
You will probably want someone who knows this much better than me to actually look it over and do it, however i hope it can be a help to optimize inserts :)
From personal experience: It doesn't speed up postgres a whole lot (The difference i saw in local testing could be attributed to chance). However in the case of Cockroach db, I saw up to 15x throughput, simply because it can bulk transactions much better, and it will probably matter even more for distributed clusters (I was just testing with a 3 node docker cluster on the same machine).
@zlepper can you provide some context on exactly what your POC is doing? The provider already batches multiple updates/inserts into a single DbCommand, which means that everything happens in a single round-trip.
The issue would be to implement insert specifically via Npgsql's binary copy API, which is a super-optimized, PostgreSQL-specific way to get data into the database.
@roji Yes, I'm basically trying to insert a couple of billion rows into the database. So the optimization i did converts (With just a lot more rows per save):
insert into foo(a, b)
values ('a', 'b');
insert into foo(a, b)
values ('c', 'd');
insert into foo(a, b)
values ('e', 'f');
into
insert into foo(a,b)
values ('a', 'b'),
('c', 'd'),
('e', 'f');
(Of cause it's still parametized, i just didn't want to type that out, since that doesn't matter for the specific changes i did)
So it's still just one roundtrip, but each statement becomes a transaction (If i have understood things correctly, i'm not that sharp on database things).
My purpose of inserting data doesn't actually have anything to do with inserting it, i just need the data there, to test how some different databases handles it when there is a lot of data already.
Do also watch out for the binary copy. In my experience that doesn't work in cockroach (At least the thing Z.EntityFrameworkExtensions does doesn't work.
For my specific case i ended using the actual import apis, since they are by far the fastest, but that's a whole other thing.
@zlepper When using the former (without your change), have you tried turning on automatic statement preparation? This has the potential of making the inserts run much faster than your modified version.
Regardless, if you really are inserting billions of rows, consider bypassing EF and coding directly against the Npgsql COPY API - you'll definitely get the best perf possible. You can still use EF Core for all other access to the database.
@zlepper When using the former (without your change), have you tried turning on automatic statement preparation? This has the potential of making the inserts run much faster than your modified version.
Would this then help even more with the bulk version also? But no, I was not aware that was a thing.
Regardless, if you really are inserting billions of rows, consider bypassing EF and coding directly against the Npgsql COPY API - you'll definitely get the best perf possible. You can still use EF Core for all other access to the database.
I mean, that is basically what I ended up doing, just using IMPORT against an aspnet endpoint that dynamically generates csv data. Currently i'm getting about 250.000 rows per second with this, so I'm pretty satisfied, it does however mean that there are no validation being run what-so-ever. Which I imagine COPY will actually do.
I have no doubt your suggestion will help with Postgres, however my main problem was actually the performance in Cockroachdb, where the bottleneck comes from the consistency (Which requires communication between nodes), and there the problem is insert statements with just one pair of values.
Also very interestingly, i cannot find the COPY statement in the Cockroach documentation, however it is apparently supported according to this PR: cockroachdb/cockroach#8756.
Would this then help even more with the bulk version also? But no, I was not aware that was a thing.
It might, if you execute the same command (with the same number of parameters) multiple times.
Considering that we EF is currently chunking our insert sizes at 1000 rows per query, then yes, we would definitely fit under that :D
But either way, if you can use what I send, feel free. If not, feel free not to :) Just thought it might help some of the general investigation work here :)
Note: dotnet/efcore#9118 is planned for EF Core 7.0, which would unlock this.
There are various methods we could use:
Multi-row insert (not good for prepared statements when the number of rows varies)
Insert with arrays (and unnest)
COPY (binary import).
Multiple single-row inserts (the current default)
@YohDeadfall did some great benchmarking in npgsql/npgsql#2779 (comment). tl;dr insert with arrays work really well up until beyond 100 rows, at which point COPY overtakes it.
One reason why COPY may be slow for less rows, is that it currently requires multiple roundtrips, i.e. BeginBinaryImport and the terminating Complete (this alsomeans that whether is worth doing COPY depends on latency to PostgreSQL). We could think about changing the ADO.NET COPY import API to be single-roundtrip, i.e. make BeginBinaryImport do nothing (a bit like BeginTransaction), and only flush and wait on Complete. We may want this to be an opt-in, not sure. I'm also not sure whether COPY always works and has no limitations, so an opt-out is a good idea (probably a minimum row threshold for switching to COPY, which can be set to 0 to disable).
Note also dotnet/efcore#27333, which is about a special EF Core API for bulk importing. So it may make sure to implement that API with COPY, and to implement SaveChanges with insert with arrays. Though if we do implement single-roundtrip-COPY, COPY may be a better option all the time - experiment.
tl;dr we should do Insert_with_arrays starting from 2-5 rows (benchmark to get the exact threshold).
Notes:
When using database-generated keys (e.g. identity), the RETURNING clause doesn't guarantee row ordering, so we need to wrap it in a WITH statement and apply ordering explicitly; this is what the _sorted methods do above. If there are no database-generated keys (e.g. client-generated GUIDs), the unsorted version is fine.
Insert_with_multiple_rows has the disadvantage of having different SQL for different numbers of rows, which means that the same prepared statement cannot be used. This isn't manifested above since the same number of rows is used. The other methods do not have this drawback.
Batched_inserts has the slight disadvantage of requiring a transaction (which isn't done in the above benchmark), whereas the other options are a single statement.
Copy (binary import) is included mainly for comparison purposes - it would require lots of effort to use it for SaveChanges (and would only work when there are no database-generated values). Also, Copy starts to be better than Insert_with_arrays only after over 1000 rows, which is an extreme scenario; at that point, you also want to avoid the change tracking overhead and use the EF future dedicated import API (Bulk import for efficient importing of data from the client into the database dotnet/efcore#27333).
BenchmarkRunner.Run<Benchmark>();publicclassBenchmark{[Params(1,2,5,10,100,500,1000,10000)]publicintNumRows{get;set;}privateNpgsqlConnection_connection;privateNpgsqlCommand_command;privateasyncTaskSetup(){_connection=newNpgsqlConnection("Host=localhost;Username=test;Password=test;Max Auto Prepare = 10");await_connection.OpenAsync();awaitusingvarcommand=_connection.CreateCommand();command.CommandText="DROP TABLE IF EXISTS foo; CREATE TABLE foo (id INT, data INT)";awaitcommand.ExecuteNonQueryAsync();}[GlobalSetup(Target=nameof(Batched_inserts))]publicasyncTaskSetup_Batched_inserts(){awaitSetup();_command=_connection.CreateCommand();_command.CommandText=newStringBuilder().AppendJoin(" ",Enumerable.Range(0,NumRows).Select(i =>$"INSERT INTO foo (data) VALUES (@p{i});")).ToString();for(vari=0;i<NumRows;i++){varparam=_command.CreateParameter();param.ParameterName="p"+i;param.Value=i;_command.Parameters.Add(param);}}[GlobalSetup(Target=nameof(Insert_with_multiple_rows))]publicasyncTaskSetup_Insert_with_multiple_rows(){awaitSetup();_command=_connection.CreateCommand();varstringBuilder=newStringBuilder("INSERT INTO foo (data) VALUES");for(vari=0;i<NumRows;i++){stringBuilder.Append(i==0?" ":", ").Append($"(@p{i})");varparam=_command.CreateParameter();param.ParameterName="p"+i;param.Value=i;_command.Parameters.Add(param);}_command.CommandText=stringBuilder.ToString();}[GlobalSetup(Target=nameof(Insert_with_multiple_rows_sorted))]publicasyncTaskSetup_Insert_with_multiple_rows_sorted(){awaitSetup_Insert_with_multiple_rows();_command.CommandText=@$"WITH bar AS({_command.CommandText} RETURNING id)SELECT * FROM bar ORDER BY id";}[GlobalSetup(Target=nameof(Insert_with_arrays))]publicasyncTaskSetup_Insert_with_arrays(){awaitSetup();_command=_connection.CreateCommand();_command.CommandText="INSERT INTO foo (data) SELECT * FROM unnest(@i)";varparam=_command.CreateParameter();param.ParameterName="i";param.Value=Enumerable.Range(0,NumRows).ToArray();_command.Parameters.Add(param);}[GlobalSetup(Target=nameof(Insert_with_arrays_sorted))]publicasyncTaskSetup_Insert_with_arrays_sorted(){awaitSetup_Insert_with_arrays();_command.CommandText=@$"WITH bar AS({_command.CommandText} RETURNING id)SELECT * FROM bar ORDER BY id";}[GlobalSetup(Target=nameof(Copy))]publicTaskSetup_Copy()=>Setup();[Benchmark(Baseline=true)]publicasyncTaskBatched_inserts()=>await_command.ExecuteNonQueryAsync();[Benchmark]publicasyncTaskInsert_with_multiple_rows()=>await_command.ExecuteNonQueryAsync();[Benchmark]publicasyncTaskInsert_with_multiple_rows_sorted()=>await_command.ExecuteNonQueryAsync();[Benchmark]publicasyncTaskInsert_with_arrays()=>await_command.ExecuteNonQueryAsync();[Benchmark]publicasyncTaskInsert_with_arrays_sorted()=>await_command.ExecuteNonQueryAsync();[Benchmark]publicasyncTaskCopy(){usingvarimporter=_connection.BeginBinaryImport("COPY foo (data) FROM STDIN (FORMAT binary)");for(vari=0;i<NumRows;i++){awaitimporter.StartRowAsync();awaitimporter.WriteAsync(i);}awaitimporter.CompleteAsync();}}
An important problem with the above optimizations, is that they don't guarantee the ordering of database-generated values returned via the RETURNING clause; this means we can't match up the returned IDs to their corresponding entity instances client-side.
The solution here would probably be to use MERGE in the same way as SQL Server - MERGE is coming to PostgreSQL 15.
This is great stuff! It's always been a pain point with DB-seeding scripts that utilize business logic for seeding and you end up seeding your graph in 20-30 seconds then waiting 5 minutes for the EF Core inserts 😅
@douglasg14b in general, EF's seeding feature isn't suitable for use with many rows for various reasons (e.g. seeding is present in the migration snapshots on disk, which would become huge). So I don't think this is very relevant for seeding.
Note that for inserting a large number of rows (bulk insert/import), dotnet/efcore#27333 is in general a better approach (expose Npgsql's binary COPY via a standard EF API).
Activity
perlun commentedon Mar 4, 2017
Agree, this would be great. Here is a link which describes how it can be done with the ADO.NET provider for SQL Server. Some sample code taken from that page:
If we could get an API that is basically swapping
SqlBulkCopythere toNpgsqlBulkCopyinstead, that would be awesome. (Of course, anyone who has worked withDataTables much knows that they are awkward and painful, but perhaps for this kind of use case it makes at least some sense...)roji commentedon Mar 5, 2017
@perlun, I think there's a bit of confusion here. Npgsql already has an efficient bulk copy API which provides the same benefits as SqlBulkCopy.
This issue is about using that bulk copy API from Npgsql's Entity Framework Core provider. EF Core already supports batched updates, where if you do several updates and then call
SaveChanges(), these will all be done in a single roundtrip (rather than a roundtrip-per-update). It's technically possible to further optimize this, checking if a large group of these updates happen to be inserts and to use bulk copy in that case.This is far from a trivial change, and we need to benchmark first to see if the performance benefits (i.e. bulk copy vs. batched inserts) justify it.
zlepper commentedon Oct 14, 2020
As part of some POC i did some performance optimizations around this library (Mainly ported the code from the sql server provider): https://gist.github.com/zlepper/7f55ab76547d81eb6eb403ad4feab06b
You will probably want someone who knows this much better than me to actually look it over and do it, however i hope it can be a help to optimize inserts :)
From personal experience: It doesn't speed up postgres a whole lot (The difference i saw in local testing could be attributed to chance). However in the case of Cockroach db, I saw up to 15x throughput, simply because it can bulk transactions much better, and it will probably matter even more for distributed clusters (I was just testing with a 3 node docker cluster on the same machine).
roji commentedon Oct 14, 2020
@zlepper can you provide some context on exactly what your POC is doing? The provider already batches multiple updates/inserts into a single DbCommand, which means that everything happens in a single round-trip.
The issue would be to implement insert specifically via Npgsql's binary copy API, which is a super-optimized, PostgreSQL-specific way to get data into the database.
zlepper commentedon Oct 14, 2020
@roji Yes, I'm basically trying to insert a couple of billion rows into the database. So the optimization i did converts (With just a lot more rows per save):
into
(Of cause it's still parametized, i just didn't want to type that out, since that doesn't matter for the specific changes i did)
So it's still just one roundtrip, but each statement becomes a transaction (If i have understood things correctly, i'm not that sharp on database things).
My purpose of inserting data doesn't actually have anything to do with inserting it, i just need the data there, to test how some different databases handles it when there is a lot of data already.
Do also watch out for the binary copy. In my experience that doesn't work in cockroach (At least the thing
Z.EntityFrameworkExtensionsdoes doesn't work.For my specific case i ended using the actual import apis, since they are by far the fastest, but that's a whole other thing.
roji commentedon Oct 14, 2020
@zlepper When using the former (without your change), have you tried turning on automatic statement preparation? This has the potential of making the inserts run much faster than your modified version.
Regardless, if you really are inserting billions of rows, consider bypassing EF and coding directly against the Npgsql COPY API - you'll definitely get the best perf possible. You can still use EF Core for all other access to the database.
zlepper commentedon Oct 14, 2020
Would this then help even more with the bulk version also? But no, I was not aware that was a thing.
I mean, that is basically what I ended up doing, just using
IMPORTagainst an aspnet endpoint that dynamically generates csv data. Currently i'm getting about 250.000 rows per second with this, so I'm pretty satisfied, it does however mean that there are no validation being run what-so-ever. Which I imagineCOPYwill actually do.I have no doubt your suggestion will help with Postgres, however my main problem was actually the performance in Cockroachdb, where the bottleneck comes from the consistency (Which requires communication between nodes), and there the problem is insert statements with just one pair of values.
Also very interestingly, i cannot find the
COPYstatement in the Cockroach documentation, however it is apparently supported according to this PR: cockroachdb/cockroach#8756.roji commentedon Oct 14, 2020
It might, if you execute the same command (with the same number of parameters) multiple times.
Yeah, if you're using Cockroach then everything definitely needs to be checked there specifically... I have no idea exactly what they support.
zlepper commentedon Oct 14, 2020
Considering that we EF is currently chunking our insert sizes at 1000 rows per query, then yes, we would definitely fit under that :D
But either way, if you can use what I send, feel free. If not, feel free not to :) Just thought it might help some of the general investigation work here :)
[-]Optimize command batching with bulk insert[/-][+]Optimize command batching with COPY (bulk import)[/+][-]Optimize command batching with COPY (bulk import)[/-][+]Optimize multiple insertions[/+]roji commentedon Mar 6, 2022
Note: dotnet/efcore#9118 is planned for EF Core 7.0, which would unlock this.
There are various methods we could use:
@YohDeadfall did some great benchmarking in npgsql/npgsql#2779 (comment). tl;dr insert with arrays work really well up until beyond 100 rows, at which point COPY overtakes it.
One reason why COPY may be slow for less rows, is that it currently requires multiple roundtrips, i.e. BeginBinaryImport and the terminating Complete (this alsomeans that whether is worth doing COPY depends on latency to PostgreSQL). We could think about changing the ADO.NET COPY import API to be single-roundtrip, i.e. make BeginBinaryImport do nothing (a bit like BeginTransaction), and only flush and wait on Complete. We may want this to be an opt-in, not sure. I'm also not sure whether COPY always works and has no limitations, so an opt-out is a good idea (probably a minimum row threshold for switching to COPY, which can be set to 0 to disable).
Note also dotnet/efcore#27333, which is about a special EF Core API for bulk importing. So it may make sure to implement that API with COPY, and to implement SaveChanges with insert with arrays. Though if we do implement single-roundtrip-COPY, COPY may be a better option all the time - experiment.
2 remaining items
roji commentedon Mar 7, 2022
Updated benchmark with the various candidate methods, based on @YohDeadfall's benchmarks in npgsql/npgsql#2779 (comment):
tl;dr we should do Insert_with_arrays starting from 2-5 rows (benchmark to get the exact threshold).
Notes:
/cc @AndriySvyryd
Benchmark code
roji commentedon Apr 21, 2022
An important problem with the above optimizations, is that they don't guarantee the ordering of database-generated values returned via the RETURNING clause; this means we can't match up the returned IDs to their corresponding entity instances client-side.
The solution here would probably be to use MERGE in the same way as SQL Server - MERGE is coming to PostgreSQL 15.
douglasg14b commentedon Sep 23, 2022
This is great stuff! It's always been a pain point with DB-seeding scripts that utilize business logic for seeding and you end up seeding your graph in 20-30 seconds then waiting 5 minutes for the EF Core inserts 😅
roji commentedon Sep 24, 2022
@douglasg14b in general, EF's seeding feature isn't suitable for use with many rows for various reasons (e.g. seeding is present in the migration snapshots on disk, which would become huge). So I don't think this is very relevant for seeding.
douglasg14b commentedon Sep 24, 2022
@roji I'm not talking about using EFs seeding features. Just logic that generates data & state, and many entities, in C#, and with DbContext.
roji commentedon Nov 13, 2023
Note that for inserting a large number of rows (bulk insert/import), dotnet/efcore#27333 is in general a better approach (expose Npgsql's binary COPY via a standard EF API).