Skip to content
This repository was archived by the owner on Apr 2, 2024. It is now read-only.

Commit c6ccd13

Browse files
committed
Optimize insert path in the DB by avoiding ON CONFLICT
Turns out there is a horrible CPU perf penalty on the DB for ON CONFLICT DO NOTHING. yet in our data, conflicts are rare. So we first try inserting without ON CONFLICT and fall back if there is a unique constraint violation. Unlike retriying with COPY this does not require sending the data again and thus saves latency and bandwidth.
1 parent 568ec8f commit c6ccd13

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ We use the following categories for changes:
2323
### Fixed
2424
- Fix broken `promscale_packager` telemetry field for docker envs [#1077]
2525
- Fix compression of old chunks thus reducing storage requirements [#1081]
26+
- Improved INSERT performance by avoidng ON CONFLICT [#1090]
2627

2728
## [0.8.0] - 2022-01-18
2829

pkg/migrations/migration_files_generated.go

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pkg/migrations/sql/idempotent/base.sql

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3067,13 +3067,24 @@ $$
30673067
DECLARE
30683068
num_rows BIGINT;
30693069
BEGIN
3070+
--turns out there is a horrible CPU perf penalty on the DB for ON CONFLICT DO NOTHING.
3071+
--yet in our data, conflicts are rare. So we first try inserting without ON CONFLICT
3072+
--and fall back if there is a unique constraint violation.
30703073
EXECUTE FORMAT(
30713074
'INSERT INTO prom_data.%1$I (time, value, series_id)
3072-
SELECT * FROM unnest($1, $2, $3) a(t,v,s) ORDER BY s,t ON CONFLICT DO NOTHING',
3075+
SELECT * FROM unnest($1, $2, $3) a(t,v,s) ORDER BY s,t',
30733076
metric_table
30743077
) USING time_array, value_array, series_id_array;
30753078
GET DIAGNOSTICS num_rows = ROW_COUNT;
30763079
RETURN num_rows;
3080+
EXCEPTION WHEN unique_violation THEN
3081+
EXECUTE FORMAT(
3082+
'INSERT INTO prom_data.%1$I (time, value, series_id)
3083+
SELECT * FROM unnest($1, $2, $3) a(t,v,s) ORDER BY s,t ON CONFLICT DO NOTHING',
3084+
metric_table
3085+
) USING time_array, value_array, series_id_array;
3086+
GET DIAGNOSTICS num_rows = ROW_COUNT;
3087+
RETURN num_rows;
30773088
END;
30783089
$$
30793090
LANGUAGE PLPGSQL;

0 commit comments

Comments
 (0)