Skip to content

perf(postgres): optimize task and push write paths under high concurrency - #219

Merged
MisterVVP merged 8 commits into
mainfrom
dev-optimize-postgresql-write-saturation
Aug 25, 2026
Merged

MisterVVP merged 8 commits into
mainfrom
dev-optimize-postgresql-write-saturation

Conversation

@MisterVVP

@MisterVVP MisterVVP commented Aug 18, 2026 •

Copy link
Copy Markdown
Owner

Motivation

Issue #206 identified PostgreSQL write saturation between concurrency 16 and 64 while connection-pool acquisition remained negligible. The goal of this PR is to remove measured SDK/SQL/schema overhead from the affected task and push write paths without weakening correctness, transaction safety, least-privilege behavior, or TCK compatibility.

What changed

PostgreSQL write-path diagnostics

  • Extends the focused postgres-write profile with PostgreSQL-side diagnostics for:
    • wait events;
    • WAL/database counters;
    • MultiXactMember / MultiXactOffset SLRU activity;
    • per-operation PostgreSQL phase latency and call counts.
  • Distinguishes optimistic task_history_snapshot reads from legacy task_history_lock_read attribution.
  • Keeps the focused profile at pool size 64 with c1/c4/c16/c64 and five repetitions.
  • Fixes the push-create warmup fixture so warmup and measured IDs cannot collide.
  • Keeps query-plan fixtures at the configured fan-out after EXPLAIN ANALYZE insert probes.

Push-config create/delete coordination

  • Replaces task-row FOR KEY SHARE coordination with schema-scoped transaction advisory locks.
  • Push create/update takes the shared advisory lock; task deletion takes the matching exclusive advisory lock in a BEFORE DELETE trigger.
  • Advisory keys include the schema-qualified task-table identity plus the complete task ID, avoiding cross-schema interference.
  • Rejects local task-aware push creation under REPEATABLE READ / SERIALIZABLE, where a stale transaction snapshot could otherwise survive an advisory-lock wait.
  • Preserves least-privilege operation without requiring task-table UPDATE.
  • Hardens externally managed schema validation, including case-sensitive validation of the delete-lock key seed.

Push write amplification

  • Removes the redundant push-config task secondary index.
  • Removes the remaining push ordering index after validating that list ordering still comes from explicit ORDER BY created_sequence.
  • Keeps the (task_id, config_id) primary key as the write/conflict index.
  • Updates managed-schema and manual-migration documentation accordingly.

Task send path

  • Separates explicit task-ID resolution from authoritative task validation.
  • Reuses the already fetched task snapshot instead of performing redundant task-store reads.
  • Preserves context, terminal-state, and requested-task identity validation.
  • Updates lifecycle benchmarks to measure the extracted validation step rather than only the ID resolver.

Optimistic task-history writes

  • Replaces transaction / SELECT ... FOR UPDATE history appends with bounded optimistic revision-checked updates.
  • Retries revision conflicts with a fixed upper bound instead of allowing an unbounded loop.
  • Includes created_sequence in the history CAS predicate to prevent delete/recreate ABA overwrites.
  • Adds deterministic concurrent-append and task-recreation coverage.
  • Preserves both concurrent messages and task metadata without holding a row lock across the append flow.

Benchmark/API and local-build cleanup

  • Keeps PushConfig_CreateMany on the same public executor/service path used by production.
  • Removes the benchmark-only PostgreSQL batch API and its unused SQL builder rather than hardening an API with no production caller.
  • Removes benchmark/test-only shortcuts that would make before/after results incomparable.
  • Fixes the Windows local FetchContent example path/toolchain handling.
  • Updates storage and performance documentation to describe the final advisory-lock and optimistic-history designs.

Performance comparison

Sources

Main-equivalent baseline:

Final combined PR (#219 + #221):

  • CI: 32860693863
  • head: bc8e51fb59e8a56e9b1eceabda061dbdbeb4615a
  • TCK: 32860693755
  • CI and TCK both passed.

The focused table below uses five-run medians from postgres-write, pool size 64.

Focused c64 results

Scenario Main c64 Final PR c64 Throughput vs main c64 p95: main → PR c64 p99: main → PR c16→c64: main → PR
PushConfig_Create 4,817 ops/s 5,356 ops/s +11.2% 31.01 → 30.09 ms (-3.0%) 81.21 → 81.26 ms (+0.1%) -24.9% → -21.9%
PushConfig_CreateMany 734 ops/s 831 ops/s +13.3% 129.03 → 115.33 ms (-10.6%) 167.74 → 141.35 ms (-15.7%) -13.5% → -11.3%
SendMessage_CreateTask 2,883 ops/s 3,892 ops/s +35.0% 53.07 → 39.19 ms (-26.1%) 74.76 → 54.59 ms (-27.0%) -3.4% → -6.4%
SendMessage_FollowUpExistingTask 2,202 ops/s 2,878 ops/s +30.7% 58.34 → 47.26 ms (-19.0%) 77.05 → 63.59 ms (-17.5%) -4.5% → -2.4%

The important change after folding #221 into #219 is that the previous follow-up-task regression is gone. All four focused c64 paths now have higher throughput than the main-equivalent baseline, and three of four also improve both p95 and p99.

SendMessage_CreateTask now has substantially higher absolute throughput and materially lower tails at c64 even though its c16→c64 percentage is slightly worse because c16 improved even more strongly.

Normal in-process PostgreSQL matrix

Across c1/c4/c16/c64 in the normal CI matrix, geometric-mean movement versus the main-equivalent baseline is:

Scenario Throughput geometric mean p95 geometric mean
PushConfig_Create +13.9% -6.7%
PushConfig_CreateMany +22.6% -46.2%
SendMessage_CreateTask +30.3% -22.2%
SendMessage_FollowUpExistingTask +13.7% -5.1%
SendMessage_FollowUpAtHistoryDepth/8 +12.8% -6.3%

The normal matrix therefore supports the focused result: the final combined branch no longer has a follow-up-task throughput regression, while create-task remains the largest measured gain.

Structural database evidence

The final profile also shows that the intended work was removed from the hot paths:

Signal Main Final PR
SendMessage_CreateTask task reads/op 1 0
SendMessage_FollowUpExistingTask task reads/op 2 1
Push-create MultiXact SLRU activity row-lock path could generate MultiXact work 0 across final focused push rows
c64 connection-acquire p95 negligible still negligible (sub-µs on the focused write paths)

The remaining high-concurrency drop is most visible in push-create, but the final profile still does not point to connection-pool starvation. Residual pressure is primarily PostgreSQL-side write/WAL/buffer contention rather than avoidable SDK connection waiting.

Benchmark comparability note

This PR fixes a correctness bug in the push benchmark fixture: warmup and measured push-create IDs previously overlapped, so the main-equivalent baseline could update warmup rows instead of measuring disjoint creates.

Because of that:

  • task-path main-vs-PR absolute comparisons remain directly comparable;
  • push-path c16→c64 scaling within each run remains the strongest cross-version signal;
  • absolute push throughput/latency deltas against the old main artifact should still be treated as directional rather than a perfectly identical workload comparison.

GitHub-hosted runner variability also means small single-digit movements should not be overinterpreted. The focused five-repetition medians are the stronger signal for this PR.

@MisterVVP MisterVVP added the codex Automatic label added by codex agent. Should not be used label Aug 18, 2026 — with ChatGPT Codex Connector
@MisterVVP
MisterVVP marked this pull request as draft August 18, 2026 06:00
@MisterVVP MisterVVP self-assigned this Aug 18, 2026
@MisterVVP MisterVVP added AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes. and removed codex Automatic label added by codex agent. Should not be used labels Aug 18, 2026
@MisterVVP MisterVVP changed the title Collect MultiXact SLRU counters, avoid redundant push index, and improve task send/validation flow perf(pSQL store): collect MultiXact SLRU counters, avoid redundant push index, and improve task send/validation flow Aug 20, 2026
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex, do full review of this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 345553ec2d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/server/stores/postgres_common.cpp Resolved
Comment thread src/server/stores/postgres_common.cpp Resolved
@MisterVVP
MisterVVP force-pushed the dev-optimize-postgresql-write-saturation branch from 345553e to e672e4b Compare August 22, 2026 09:34
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c7f02792e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: beb77bf2c0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/unit/examples_support_test.cpp Resolved
@MisterVVP
MisterVVP marked this pull request as ready for review August 22, 2026 19:36
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this pr again

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c8c3d98553

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/performance_runner.py Resolved
Comment thread book/src/server/storage.md Resolved
Comment thread docs/performance-testing.md Resolved
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR again

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 265b2ed25a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@MisterVVP

Copy link
Copy Markdown
Owner Author

This does not provide enough improvements to be merged... Let's continue experimenting.

@MisterVVP
MisterVVP marked this pull request as draft August 23, 2026 09:12
@MisterVVP

Copy link
Copy Markdown
Owner Author

There are some experiments at #221 and #222

Eventually we should proceed here with some perf. gains after another review round, then focus on other performance issues and later on async I/O (which requires development of a brand new async API)

@MisterVVP
MisterVVP marked this pull request as ready for review August 25, 2026 10:58
Replace transaction/SELECT FOR UPDATE history appends with bounded
revision-checked optimistic updates.

- preserve concurrent history appends without long row locks
- protect against delete/recreate ABA with created_sequence
- add deterministic contention and recreation coverage
- distinguish optimistic history snapshots in PostgreSQL diagnostics
- keep retry behavior bounded under contention
@MisterVVP

Copy link
Copy Markdown
Owner Author

OK, no more time for experiments. This can be merged now. Next goal is to finish #209 and fix a few tech. debt issues. After that the next minor release (0.5.0) can be published

The following minor release (0.6.0) should focus on async I/O

@MisterVVP MisterVVP linked an issue Aug 25, 2026 that may be closed by this pull request
10 tasks
@MisterVVP MisterVVP changed the title perf(pSQL store): collect MultiXact SLRU counters, avoid redundant push index, and improve task send/validation flow perf(postgres): optimize task and push write paths under high concurrency Aug 25, 2026
@MisterVVP
MisterVVP merged commit fc34a18 into main Aug 25, 2026
19 checks passed
@MisterVVP
MisterVVP deleted the dev-optimize-postgresql-write-saturation branch August 25, 2026 16:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance]: Profile and optimize PostgreSQL task/push write saturation

1 participant