Skip to content

How do you do multiple inserts with npgsql (batch not serial) #2779

Closed

Description

@PaulGWebster

Hey there, I had a look around google for howto do something relatively simple like:

INSERT INTO order_side (id) VALUES ('OTHER'),('MARKETSALE'),('MARKETBUY'),('LIMITBUY'),('LIMITSALE');

with npgsql and got into a world of weirdness and random bug tickets, I assume this has probably already been answered somewhere but I honestly cannot figure out where and cannot find anything but a hack in the docks: http://www.npgsql.org/doc/performance.html#batchingpipelining

Which to me looks like its just doing a bunch of singular inserts collecting the results and returning (maybe I am wrong - if so my fault).

But yes I need to basically insert blocks of data which would be roughly equal to 500 rows per second (which is not a vast amount - but it creates significant overhead doing it in a singular loop), the postgresql peeps have told me to use batch inserts, I just cannot seem to see how to get them to work. Any help availible?

As an oddity I do not actually even care about the result as long as the query succeeds

Activity

  1. PaulGWebster commented on Jan 6, 2020

    @PaulGWebster
    Author

    oh I am using .NET Framework (as needs to be compatible with mono) not sure if it makes any difference

  2. YohDeadfall commented on Jan 6, 2020

    @YohDeadfall
    Contributor

    Answered in #2511 (comment). You should pass values using an array and change the query to:

    INSERT INTO order_side (id)
    SELECT * FROM unnest(@ids);
  3. roji commented on Jan 6, 2020

    @roji
    Member

    For inserting large amounts of rows it's generally best to use the bulk COPY API.

  4. PaulGWebster commented on Jan 6, 2020

    @PaulGWebster
    Author

    @roji I spotted that but thought if you used the COPY api things like BIGSERIAL and such fields would not be triggered and auto incremented so I went down the path of doing:

                NpgsqlConnection dbh = new NpgsqlConnection(databaseDSN);
    
                // Connect to the correct databases
                dbh.Open();
    
                // How many inserts should be bundled?
                int sqlBundleAmount = 500;
    
                // Create buffers for bundling inserts togetherhttps://dpaste.org/peZG
                List<string> sqlBuffer = new List<string>();
    
                string sqlCommand =
                    "INSERT INTO public.market_data(type, product, market, side, price, size) VALUES ";
    
                for(int iterator=0;iterator<sqlBundleAmount;iterator++)
                {
                    string iteratorStr = iterator.ToString();
                    sqlCommand += string.Format(
                        "({0},{1},{2},{3},{4},{5})",
                        "@a" + iteratorStr,
                        "@b" + iteratorStr,
                        "@c" + iteratorStr,
                        "@d" + iteratorStr,
                        "@f" + iteratorStr,
                        "@g" + iteratorStr
                ) ;
    
                if (iterator+1 != sqlBundleAmount)
                    {
                        sqlCommand += ",";
                    }
                }
    
    #pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
                NpgsqlCommand insertBatch = new NpgsqlCommand(sqlCommand, dbh);
    #pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
    
                for (int iterator = 0; iterator < sqlBundleAmount; iterator++)
                {
                    string iteratorStr = iterator.ToString();
    
                    insertBatch.Parameters.Add("a" + iteratorStr, NpgsqlDbType.Text);
                    insertBatch.Parameters.Add("b" + iteratorStr, NpgsqlDbType.Text);
                    insertBatch.Parameters.Add("c" + iteratorStr, NpgsqlDbType.Text);
                    insertBatch.Parameters.Add("d" + iteratorStr, NpgsqlDbType.Text);
                    insertBatch.Parameters.Add("f" + iteratorStr, NpgsqlDbType.Bigint);
                    insertBatch.Parameters.Add("g" + iteratorStr, NpgsqlDbType.Bigint);
                }
    
                insertBatch.Prepare();
    
                for (int iterator = 0; iterator < sqlBundleAmount; iterator++)
                {
                    string iteratorStr = iterator.ToString();
    
                    insertBatch.Parameters["a" + iteratorStr].Value = "OPEN";
                    insertBatch.Parameters["b" + iteratorStr].Value = "BTC-USD";
                    insertBatch.Parameters["c" + iteratorStr].Value = "GDAX";
                    insertBatch.Parameters["d" + iteratorStr].Value = "MARKETSALE";
                    insertBatch.Parameters["f" + iteratorStr].Value = 27300000;
                    insertBatch.Parameters["g" + iteratorStr].Value = 10000000;
                }
    
                insertBatch.ExecuteNonQuery();
  5. PaulGWebster commented on Jan 6, 2020

    @PaulGWebster
    Author

    oh as an aside it might be nice adding: insertBatch.Parameters["c" + iteratorStr].Value = "GDAX"; in my case to the 'simple preperatio' example on:

    http://www.npgsql.org/doc/prepare.html

  6. roji commented on Jan 6, 2020

    @roji
    Member

    @roji I spotted that but thought if you used the COPY api things like BIGSERIAL and such fields would not be triggered and auto incremented so I went down the path of doing:

    I'm almost 100% sure that COPY will properly handle SERIAL/IDENTITY columns - this is really a better way to do things than to batch insert statements. Did you try this out and run into an issue?

  7. YohDeadfall commented on Jan 12, 2020

    @YohDeadfall
    Contributor

    Did comparison of different insertion methods supported by PostgreSQL. As expected COPY wins. The second place holds INSERT INTO ... FROM unnest(...) which is fast enough to insert one or a few thousand rows. The third fastest way is batched INSERT used by Entity Framework, but it's limited by 32767 parameters or by a row count equals to 32767 divided by number of inserting columns.

    A nice feature of unnest inserts is that you can do populate two tables, or update another, or get back values of some columns (for example identity) at the same time using a CTE, or do upsert:

    Simple UPSERT

    INSERT INTO data_table (id, name)
    SELECT * FROM unnest(@i, @n)
        ON CONFLICT ON data_table_pkey
        DO UPDATE SET name = EXCLUDED.name

    UPSERT with INSERTion into a log table

    WITH upd AS (
        INSERT INTO data_table (id, name)
        SELECT * FROM unnest(@i, @n)
            ON CONFLICT ON data_table_pkey
            DO UPDATE SET name = EXCLUDED.name
        RETURNING *
    )
    INSERT INTO data_table_log
    SELECT *, current_timestamp FROM upd

    Benchmarks

    [Config(typeof(Config))]
    public class Insert
    {
        protected class Config : ManualConfig
        {
            public Config()
            {
                Add(StatisticColumn.OperationsPerSecond);
                Add(MemoryDiagnoser.Default);
            }
        }
    
        NpgsqlConnection _connection = default!;
        (int Id, string Name)[] _records = default!;
    
        [Params(1, 10, 100, 1_000, 10_000, 100_000)]
        public int Records { get; set; } = default!;
    
        [GlobalSetup]
        public void GlobalSetup()
        {
            _connection = new NpgsqlConnection(
                new NpgsqlConnectionStringBuilder(BenchmarkEnvironment.ConnectionString) { Pooling = false }.ToString());
            _connection.Open();
    
            using (var command = new NpgsqlCommand(
                connection: _connection,
                cmdText: "CREATE TEMP TABLE data_table (id INTEGER NOT NULL, name TEXT NOT NULL) ON COMMIT DELETE ROWS"))
                command.ExecuteNonQuery();
    
            _records = Enumerable
                .Range(0, Records)
                .Select(i => (i, $"My identifier is {i}"))
                .ToArray();
        }
    
        [GlobalCleanup]
        public void GlobalCleanup() => _connection.Close();
    
        [Benchmark(Baseline = true)]
        public async Task InsertPlain()
        {
            var transaction = _connection.BeginTransaction();
            using var command = new NpgsqlCommand(connection: _connection, cmdText:
                "INSERT INTO data_table (id, name) VALUES (@i, @n)");
    
            var id = new NpgsqlParameter<int>("i", default(int));
            var name = new NpgsqlParameter<string>("n", string.Empty);
    
            command.Parameters.Add(id);
            command.Parameters.Add(name);
    
            foreach (var element in _records)
            {
                id.TypedValue = element.Id;
                name.TypedValue = element.Name;
    
                await command.ExecuteNonQueryAsync();
            }
    
            await transaction.CommitAsync();
        }
    
        [Benchmark]
        public async Task InsertPrepared()
        {
            var transaction = _connection.BeginTransaction();
            using var command = new NpgsqlCommand(connection: _connection, cmdText:
                "INSERT INTO data_table (id, name) VALUES (@i, @n)");
    
            var id = new NpgsqlParameter<int>("i", default(int));
            var name = new NpgsqlParameter<string>("n", string.Empty);
    
            command.Parameters.Add(id);
            command.Parameters.Add(name);
            await command.PrepareAsync();
    
            foreach (var element in _records)
            {
                id.TypedValue = element.Id;
                name.TypedValue = element.Name;
    
                await command.ExecuteNonQueryAsync();
            }
    
            await transaction.CommitAsync();
        }
    
        [Benchmark]
        public async Task InsertBatched()
        {
            using var command = new NpgsqlCommand(connection: _connection, cmdText: null);
    
            var sb = new StringBuilder("INSERT INTO data_table (id, name) VALUES ");
            for (var i = 0; i < _records.Length; i++)
            {
                if (i != 0) sb.Append(',');
                var iName = (i * 2 + 1).ToString();
                var nName = (i * 2 + 2).ToString();
    
                sb.Append("(@").Append(iName).Append(", @").Append(nName).Append(')');
                command.Parameters.Add(new NpgsqlParameter<int>(iName, _records[i].Id));
                command.Parameters.Add(new NpgsqlParameter<string>(nName, _records[i].Name));
            }
    
            command.CommandText = sb.ToString();
            await command.ExecuteNonQueryAsync();
        }
    
        [Benchmark]
        public async Task InsertUnnest()
        {
            using var command = new NpgsqlCommand(connection: _connection, cmdText:
                "INSERT INTO data_table (id, name) SELECT * FROM unnest(@i, @n) AS d");
    
            command.Parameters.Add(new NpgsqlParameter<int[]>("i", _records.Select(e => e.Id).ToArray()));
            command.Parameters.Add(new NpgsqlParameter<string[]>("n", _records.Select(e => e.Name).ToArray()));
    
            await command.ExecuteNonQueryAsync();
        }
    
        [Benchmark]
        public async Task Copy()
        {
            using var importer = _connection.BeginBinaryImport(
                "COPY data_table (id, name) FROM STDIN (FORMAT binary)");
        
            foreach (var element in _records)
            {
                await importer.StartRowAsync();
                await importer.WriteAsync(element.Id);
                await importer.WriteAsync(element.Name);
            }
    
            await importer.CompleteAsync();
        }
    }

    Summary

    BenchmarkDotNet=v0.11.5, OS=Windows 10.0.19041
    Intel Xeon CPU E5-2687W 0 3.10GHz, 2 CPU, 32 logical and 16 physical cores
    .NET Core SDK=3.1.100
      [Host]     : .NET Core 3.1.0 (CoreCLR 4.700.19.56402, CoreFX 4.700.19.56404), 64bit RyuJIT
      Job-VXRSXR : .NET Core 3.0.1 (CoreCLR 4.700.19.51502, CoreFX 4.700.19.51609), 64bit RyuJIT
    
    Runtime=Core  Toolchain=netcoreapp3.0
    
    Method Records Mean Error StdDev Op/s Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
    InsertPlain 1 12.75 ms 0.2517 ms 0.6405 ms 78.4609 1.00 0.00 - - - 2771 B
    InsertPrepared 1 12.54 ms 0.2466 ms 0.5360 ms 79.7187 0.99 0.07 - - - 2907 B
    InsertBatched 1 10.24 ms 0.2031 ms 0.4944 ms 97.6151 0.81 0.06 - - - 2816 B
    InsertUnnest 1 10.93 ms 0.2167 ms 0.5820 ms 91.4856 0.86 0.06 - - - 2960 B
    Copy 1 11.31 ms 0.2261 ms 0.5148 ms 88.4250 0.89 0.06 - - - 1744 B
    InsertPlain 10 15.19 ms 0.3016 ms 0.6092 ms 65.8429 1.00 0.00 - - - 2771 B
    InsertPrepared 10 13.90 ms 0.2848 ms 0.7250 ms 71.9504 0.91 0.06 - - - 2907 B
    InsertBatched 10 11.09 ms 0.2208 ms 0.5458 ms 90.1816 0.74 0.05 - - - 12216 B
    InsertUnnest 10 11.15 ms 0.2218 ms 0.5141 ms 89.7084 0.74 0.05 - - - 4832 B
    Copy 10 11.64 ms 0.2302 ms 0.5732 ms 85.9327 0.77 0.05 - - - 3328 B
    InsertPlain 100 49.66 ms 0.9781 ms 1.1643 ms 20.1371 1.00 0.00 - - - 2822 B
    InsertPrepared 100 38.07 ms 0.7610 ms 1.0669 ms 26.2649 0.77 0.02 - - - 2945 B
    InsertBatched 100 13.01 ms 0.2603 ms 0.3896 ms 76.8371 0.26 0.01 - - - 109800 B
    InsertUnnest 100 11.63 ms 0.2302 ms 0.5603 ms 86.0148 0.24 0.01 - - - 22720 B
    Copy 100 12.62 ms 0.2406 ms 0.2954 ms 79.2130 0.25 0.01 - - - 19168 B
    InsertPlain 1000 405.33 ms 7.6858 ms 7.1893 ms 2.4671 1.00 0.00 - - - -
    InsertPrepared 1000 312.83 ms 5.9970 ms 5.3162 ms 3.1967 0.77 0.02 - - - -
    InsertBatched 1000 61.82 ms 1.2353 ms 1.3731 ms 16.1768 0.15 0.00 - - - 975240 B
    InsertUnnest 1000 51.51 ms 1.0061 ms 1.0765 ms 19.4119 0.13 0.00 - - - 199160 B
    Copy 1000 49.70 ms 0.4378 ms 0.3656 ms 20.1204 0.12 0.00 - - - 177568 B
    InsertPlain 10000 3,437.15 ms 68.7058 ms 122.1245 ms 0.2909 1.00 0.00 1000.0000 - - -
    InsertPrepared 10000 2,590.87 ms 50.8784 ms 52.2484 ms 0.3860 0.75 0.03 1000.0000 - - -
    InsertBatched 10000 206.24 ms 4.0828 ms 4.3685 ms 4.8488 0.06 0.00 666.6667 333.3333 - 8361640 B
    InsertUnnest 10000 87.67 ms 0.5470 ms 0.4849 ms 11.4065 0.03 0.00 166.6667 - - 2014136 B
    Copy 10000 66.14 ms 1.2644 ms 1.4054 ms 15.1188 0.02 0.00 125.0000 - - 1761568 B
    InsertPlain 100000 34,010.51 ms 669.8259 ms 1,470.2840 ms 0.0294 1.000 0.00 14000.0000 1000.0000 - -
    InsertPrepared 100000 25,138.78 ms 315.8775 ms 295.4720 ms 0.0398 0.758 0.06 11000.0000 - - -
    InsertBatched 100000 NA NA NA NA ? ? - - - -
    InsertUnnest 100000 505.31 ms 9.5184 ms 9.3483 ms 1.9790 0.015 0.00 1000.0000 - - 17735064 B
    Copy 100000 209.40 ms 4.1555 ms 8.5819 ms 4.7756 0.006 0.00 1000.0000 - - 17601568 B
  8. kojo12228 commented on Sep 30, 2023

    @kojo12228

    I wanted to use @YohDeadfall's benchmarks to justify moving from COPY to INSERT INTO ... FROM unnest ... but it was correctly pointed out to me that the performance characteristics of Postgres might have changed in more recent version.

    Using Testcontainers to run the database locally with Docker, I got these results with the a few recent version:

    BenchmarkDotNet v0.13.8, Ubuntu 22.04.3 LTS (Jammy Jellyfish)
    AMD Ryzen 5 4500U with Radeon Graphics, 1 CPU, 6 logical and 6 physical cores
    .NET SDK 7.0.401
      [Host]     : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2 DEBUG
      DefaultJob : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2
    
    Method Insertions PostgresVersion Mean Error StdDev Median
    InsertUnnest 1 14.9 285.9 us 20.15 us 59.40 us 266.8 us
    Copy 1 14.9 283.1 us 7.66 us 22.11 us 279.1 us
    InsertUnnest 1 15.4 293.9 us 21.23 us 62.61 us 283.9 us
    Copy 1 15.4 288.7 us 12.93 us 37.93 us 279.8 us
    InsertUnnest 1 16.0 263.8 us 13.92 us 40.17 us 255.5 us
    Copy 1 16.0 260.9 us 6.67 us 19.57 us 257.6 us
    InsertUnnest 10 14.9 310.8 us 17.00 us 49.04 us 296.7 us
    Copy 10 14.9 295.6 us 10.88 us 31.92 us 293.0 us
    InsertUnnest 10 15.4 302.0 us 15.23 us 44.20 us 294.0 us
    Copy 10 15.4 273.9 us 10.08 us 28.42 us 268.6 us
    InsertUnnest 10 16.0 284.2 us 10.02 us 27.77 us 280.0 us
    Copy 10 16.0 270.5 us 6.34 us 17.68 us 269.1 us
    InsertUnnest 100 14.9 531.4 us 17.92 us 52.27 us 528.9 us
    Copy 100 14.9 722.9 us 39.65 us 116.90 us 720.8 us
    InsertUnnest 100 15.4 560.1 us 23.25 us 67.81 us 543.6 us
    Copy 100 15.4 772.8 us 28.84 us 85.04 us 773.8 us
    InsertUnnest 100 16.0 530.1 us 19.79 us 56.78 us 516.9 us
    Copy 100 16.0 769.0 us 25.97 us 76.57 us 783.4 us
    InsertUnnest 1000 14.9 2,888.0 us 138.42 us 408.14 us 2,865.5 us
    Copy 1000 14.9 3,790.0 us 89.60 us 264.17 us 3,776.1 us
    InsertUnnest 1000 15.4 2,729.2 us 93.61 us 273.05 us 2,734.4 us
    Copy 1000 15.4 3,767.6 us 120.24 us 350.74 us 3,791.0 us
    InsertUnnest 1000 16.0 2,861.0 us 104.59 us 306.75 us 2,869.8 us
    Copy 1000 16.0 3,950.5 us 110.79 us 326.66 us 3,993.8 us
    InsertUnnest 10000 14.9 19,168.7 us 768.59 us 2,266.21 us 18,856.0 us
    Copy 10000 14.9 16,855.2 us 866.56 us 2,555.06 us 17,145.9 us
    InsertUnnest 10000 15.4 19,633.9 us 787.47 us 2,321.87 us 19,098.0 us
    Copy 10000 15.4 16,300.4 us 656.47 us 1,935.60 us 16,314.2 us
    InsertUnnest 10000 16.0 20,062.4 us 711.13 us 2,028.89 us 20,141.2 us
    Copy 10000 16.0 18,392.5 us 796.31 us 2,347.94 us 19,013.6 us
    InsertUnnest 100000 14.9 200,035.0 us 5,413.34 us 15,961.36 us 200,850.7 us
    Copy 100000 14.9 104,037.2 us 3,350.32 us 9,878.50 us 104,052.1 us
    InsertUnnest 100000 15.4 199,700.9 us 4,582.95 us 13,512.92 us 201,165.3 us
    Copy 100000 15.4 100,257.6 us 4,044.39 us 11,924.98 us 98,818.0 us
    InsertUnnest 100000 16.0 192,565.3 us 5,346.35 us 15,763.84 us 192,880.9 us
    Copy 100000 16.0 103,594.3 us 4,225.02 us 12,457.56 us 101,967.5 us

    Code in https://github.com/kojo12228/PostgresPerf.Net (mostly copy of @YohDeadfall but in F# and not using a temp table due to an issue I encountered).

    The Postgres 16 Beta 1 notes mention the following about COPY: PostgreSQL 16 can also improve the performance of concurrent bulk loading of data using COPY up to 300%. It's a bit more complicated though, helpfully described on pganalyse (emphasis copied):

    If you want to know whether there is a chance that you will benefit from this once Postgres 16 comes out: when you're doing these types of bulk loads with COPY watch out for the wait event of wait event type "lock" and then the lock wait event "extend".

    I might do a bit more testing and I'll update accordingly.

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