Skip to content

pg: prepare+cache query statements - #115

Open
phlip9 wants to merge 4 commits into
lightningdevkit:mainfrom
phlip9:phlip9/pg-prepared-queries
Open

pg: prepare+cache query statements#115
phlip9 wants to merge 4 commits into
lightningdevkit:mainfrom
phlip9:phlip9/pg-prepared-queries

Conversation

@phlip9

@phlip9 phlip9 commented Sep 3, 2026

Copy link
Copy Markdown

Without this change, we would re-parse and re-plan each query, potentially multiple times per request (!). For simple queries, this appears to add ~100-200 us overhead. More for more complex queries.

Instead, maintain a small prepared statement cache per connection. We'll lazily prepare a query statement the first time we execute it, then use the prepared statement thereafter.

This change reduces latency by ~20-60% on my small benchmark suite, but is particularly impactful on batch conditional updates, where we were previously re-parsing and re-planning the put query for each item in the batch. This change improved throughput there by ~2.5x (~4.8k/s -> 12.3k/s).

Using const &'static str queries is really more a stylistic preference on my part. I think it adds a nice roadblock to prevent people from accidentally adding let stmt = format!("..", untrusted_user_input) -> SQL injection.

Migrations and other admin queries are still uncached, since they're usually only executed once.

So I can `POSTGRES_ENDPOINT='postgresql://%2Frun%2Fuser%2F1000' cargo test`
against my user-local, socket-activated dev postgres.
Without this change, we would re-parse and re-plan each query,
potentially multiple times per request (!).

Instead, maintain a small prepared statement cache per connection. We'll
lazily prepare a query statement the first time we execute it, then use
the prepared statement thereafter.

This change reduces latency by ~20-60% on my small benchmark suite, but
is particularly impactful on batch conditional updates, where we were
previously re-parsing and re-planning the put query for each item in the
batch. This change improved throughput there by ~1.5x (~4.8k/s ->
12.3k/s).
@ldk-reviews-bot

ldk-reviews-bot commented Sep 3, 2026

Copy link
Copy Markdown

I've assigned @tankyleo as a reviewer!
I'll wait for their review and will help manage the review process.
Once they submit their review, I'll check if a second reviewer would be helpful.

@phlip9

phlip9 commented Sep 3, 2026

Copy link
Copy Markdown
Author

Oops, looks like the new tinyvec release accidentally broke alloc + no-std. Waiting for Lokathor/tinyvec#226

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants