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
wondering if you've considered either adding opentelemetry support directly, or adding hooks for pre/post query execution?
just looking for a good way to get telemetry into your awesome library - thanks!
Reacted by Mike Williamson, John Younan, GP, Ivan Drondov, Moshe Brevda, Miles, Tolsee, Archie Lamb, Guillermo Enrique Bernal Moreira, Victor and 31 more
This is really just a result of a few hours trying to grasp this library's internals and finding a hacky way to get the query statement, along with start and end span markers. I'd love some recommendations @porsager if you have better thoughts on how to hook into this library. So far it works, but I wouldn't put it anywhere close to production without some more testing.
I'm thinking the following to cover various use cases:
options.stats: true or sql.stats() gives you the following properties on the query result
result.duration// the complete duration of the queryresult.waiting// the time the query waited to be sentresult.execution// the actual execution time (query sent to pg until response)
Now that's fine for hooking up or logging if required, but for the opentelemetry case, I'm thinking an option like this:
I'm thinking the following to cover various use cases:
options.stats: true or sql.stats() gives you the following properties on the query result
result.duration// the complete duration of the queryresult.waiting// the time the query waited to be sentresult.execution// the actual execution time (query sent to pg until response)
Now that's fine for hooking up or logging if required, but for the opentelemetry case, I'm thinking an option like this:
My approach for manual instrumentation would be to wrap the sql function returned by postgres() in another function that first calls tracer.startSpan(), then awaits the original sql function, and then calls span.end() with optional error handling.
I have tried to wrap the sql function but there is something I am missing. The code works great as long as the query does not use an embedded ${sql(...)} in the tmeplate.
Essentially I would like to wrap the function to instrument to AWS Xray, but if I do anything to resolve the promise sql returns then I loosethe ability to return the correct "thing" from my wrapped funciton, requring a rewrite of all the code which tries to call the function.
If anyone has an example wrapper function to be able to instrument the query and time taken that would be amazing!
I have attempted to use it to no avail. I added this in my package.json dependencies... "postgres": "https://github.com/porsager/postgres.git#query-stats"
expecting to see those console.logs happen during and after the sql call. No errors, but nothing logged either. If you can hint as to what I am missing that would be fantastic as I think this would be perfect for me to instrument my sql calls!
First, thank you for creating such a fantastic Postgres library! I was curious if there are any plans to include query stats in an upcoming release. Access to these stats would be incredibly helpful for instrumenting and monitoring database interactions in my applications.
Thanks in advance, and looking forward to any updates!
Reacted by Arkadii Butermanov, Stephen Haberman, Matías Vallone and Maarten Baijs
Also interested in seeing this. We like postgres-js because of how fast it is, but the value of being able to analyze our queries themselves (in Sentry) and be able to fix our slow code is possibly more important.
Hello! Per real-world-usage feedback, I haven't hooked #1051 (just @abustany 's patch put into a PR) up to our APM yet (still on the todo list), but I'm using it to "count the number of SQL statements / assert against their contents" made during our test suite (for tests covering our N+1 prevention) with this basic snippet:
onquery: ()=>{// queuedreturn(q: any)=>{// sentrecordQuery(q.query??// q might be a PostgresErrorq.statement?.string,);return()=>{// finished};};},
My primary feedback is that, for me, it's hard to look at the q param and know how to get at the SQL + params (I'm reaching into q.statement?.string to get the sql-with-%1 params), and, being a newbie, I'm worried that is probably wrong under certain conditions? I'm not sure.
I think a more basic/limited API to pass as q would be like:
type QueryInfo = {
sql: string; // select * from authors where first_name = %1
args: any[]; // ["bob"]
cancel(): void; // maybe?
}
And it'd be super-easy for logging/APM tools to consume.
@porsager wdyt? What would a good QueryInfo look like, to you? Or would you rather keep passing in the raw Query?
Chiming in to press on for this tracing instrumentation. Would be of immense value to trace our live traffic at fast-growing startups and large cos alike, though would like this to hit main branch and be tested first.
Some related questions/options that might be helpful in driving this forward:
Should this change live here in postgresjs library or be in opentelemetry's plugin repro instead, where it's not a hard dependency that can impact the library's performance/functionality?
Is there's room in Node's underlying postgres drivers to do this instrumentation with minimal intrusion. Something library-agnostic would be of huge value to the entire Node community?
Further, a really powerful feature to unify tracing across the system would be to optionally pull EXPLAIN ANALYZE into traces -- Definitely an idea for later, but compelling nonetheless
Reacted by rain capsule, Max Karasinski and Nikhil Verma
Re manual instrumentation: I've had some luck using a Proxy wrapper on the SQL function/module, and only using that for top-level queries but never SQL builder. This gets around some of the weirdness with tagged template literals and overloading sql for both querying and query fragments (I don't otherwise use other functions like .cursor)
There's still a bit of lift to update all the call-sites to use the "tracedSql" variant, but gives some confidence that manual tracing wrapper won't mysteriously break queries with builders/interpolation. Yet to try in production, but seems promising
Hello. I love using postgres! I hit the same roadblock that you all have had.
I created this repository, otel-instrumentation-postgres, for building a wrapper of Postgres.js and the Open Telemetry instrumentation. In the example directory, you can find a simple hono app with Kysely + Postgres setup and a simple telemetry app. The example app runs alongside Zipkin, Prometheus, and Grafana.
We're using postgres.js with Drizzle ORM and OpenTelemetry + Langfuse for tracing. We have auto-instrumentation for HTTP, Express, and Redis — but postgres.js is the missing piece. Our traces show the full request lifecycle except DB queries, which makes it hard to debug slow requests.
Would love to see the onquery hook from the query-stats branch merged. Even a minimal hook API would let the community build OTel instrumentation on top.
Activity
porsager commentedon Aug 14, 2022
Hi @JerrySievert .. Thank you for the kind words..
I think it's a great idea to add some hooks so this can be achieved. I'll give some thoughts to how that could be achieved best.
JerrySievert commentedon Aug 14, 2022
fantastic! I look forward to seeing the addition, thanks for considering it.
tomsanbear commentedon Sep 27, 2022
Hey @JerrySievert @porsager
I ended up taking a stab at instrumenting this library over here:
https://github.com/tomsanbear/opentelemetry-instrumentation-postgres
This is really just a result of a few hours trying to grasp this library's internals and finding a hacky way to get the query statement, along with start and end span markers. I'd love some recommendations @porsager if you have better thoughts on how to hook into this library. So far it works, but I wouldn't put it anywhere close to production without some more testing.
JerrySievert commentedon Oct 6, 2022
@tomsanbear that's awesome, but is there some trick to getting it to work?
and then in my instrumentations when instantiating the sdk:
is there something else I need to do?
younanjo commentedon Mar 2, 2023
@porsager checking to see if there is any updates on supporting OpenTelemetry?
porsager commentedon Jun 25, 2023
I'm thinking the following to cover various use cases:
options.stats: true or sql.stats() gives you the following properties on the query result
Now that's fine for hooking up or logging if required, but for the opentelemetry case, I'm thinking an option like this:
I've got a branch with that setup here if you want to test it out https://github.com/porsager/postgres/tree/query-stats .. Let me know what you think:
clouedoc commentedon Jun 30, 2023
What might be interesting would be to also provide hooks for different lifecycle events of the query;
i.e., for instance, there might be a high "time to connect to postgres" compared to "time of query execution"
porsager commentedon Jul 1, 2023
That's exactly what the above is? 😉
clouedoc commentedon Jul 1, 2023
Oh, haha, yes, sorry about that; I didn't pay enough attention 🤦♂️
Thanks for your library, by the way!
gustavolzangelo commentedon Aug 11, 2023
@porsager this is perfect! I think these 3 stats are exactly what is needed. Is there any plan to implement this feature?
hastebrot commentedon Aug 14, 2023
My approach for manual instrumentation would be to wrap the
sqlfunction returned bypostgres()in another function that first callstracer.startSpan(), then awaits the originalsqlfunction, and then callsspan.end()with optional error handling.Then the trace exporter would receive
startTimeUnixNanoandendTimeUnixNano(as defined in otlp-transformer/src/trace/types.ts).mattsoftware commentedon Feb 14, 2024
I have tried to wrap the sql function but there is something I am missing. The code works great as long as the query does not use an embedded
${sql(...)}in the tmeplate.Essentially I would like to wrap the function to instrument to AWS Xray, but if I do anything to resolve the promise sql returns then I loosethe ability to return the correct "thing" from my wrapped funciton, requring a rewrite of all the code which tries to call the function.
If anyone has an example wrapper function to be able to instrument the query and time taken that would be amazing!
porsager commentedon Feb 14, 2024
Did you try the https://github.com/porsager/postgres/tree/query-stats branch mentioned right above instead of trying to create a wrapper @mattsoftware ?
mattsoftware commentedon Feb 14, 2024
I have attempted to use it to no avail. I added this in my package.json dependencies...
"postgres": "https://github.com/porsager/postgres.git#query-stats"and then updated my sql options to this...
expecting to see those console.logs happen during and after the sql call. No errors, but nothing logged either. If you can hint as to what I am missing that would be fantastic as I think this would be perfect for me to instrument my sql calls!
Thanks.
7 remaining items
abustany commentedon Mar 26, 2024
I updated the patch above to copy the
onqueryhandler on eachQueryinstance, that query can then do whatever it wants with it.spacetoha commentedon May 27, 2024
Dear @porsager,
Are there any plans to merge the https://github.com/porsager/postgres/tree/query-stats soon?
Thanks,
Anton
porsager commentedon May 27, 2024
sorry no plans right now
devthejo commentedon Jul 7, 2024
thanks @abustany
the patch, is working great (used yarn patch from yarn 4), applied on
postgres3.4.4, I had to changeq.stringtoq.strings.join("?")here is my yarn patch: https://codeberg.org/devthefuture/modjo/src/branch/master/.yarn/patches/postgres-npm-3.4.4-90e4c53e1e.patch
and here is the implementation: https://codeberg.org/devthefuture/modjo/src/branch/master/plugins/postgres/tracing.js
mbrevda commentedon Jul 11, 2024
Anything we can do to help move this forward?
DAcodedBEAT commentedon Oct 25, 2024
Hi @porsager 👋
First, thank you for creating such a fantastic Postgres library! I was curious if there are any plans to include query stats in an upcoming release. Access to these stats would be incredibly helpful for instrumenting and monitoring database interactions in my applications.
Thanks in advance, and looking forward to any updates!
willhoney7 commentedon Mar 24, 2025
Also interested in seeing this. We like postgres-js because of how fast it is, but the value of being able to analyze our queries themselves (in Sentry) and be able to fix our slow code is possibly more important.
porsager commentedon Mar 24, 2025
Using the branch above and giving your feedback on the API etc in real world usage is a fast track for getting it merged 😉
stephenh commentedon Mar 25, 2025
Hello! Per real-world-usage feedback, I haven't hooked #1051 (just @abustany 's patch put into a PR) up to our APM yet (still on the todo list), but I'm using it to "count the number of SQL statements / assert against their contents" made during our test suite (for tests covering our N+1 prevention) with this basic snippet:
My primary feedback is that, for me, it's hard to look at the
qparam and know how to get at the SQL + params (I'm reaching intoq.statement?.stringto get the sql-with-%1 params), and, being a newbie, I'm worried that is probably wrong under certain conditions? I'm not sure.I think a more basic/limited API to pass as
qwould be like:And it'd be super-easy for logging/APM tools to consume.
@porsager wdyt? What would a good
QueryInfolook like, to you? Or would you rather keep passing in the rawQuery?Thanks!
Korede-TA commentedon May 21, 2025
Chiming in to press on for this tracing instrumentation. Would be of immense value to trace our live traffic at fast-growing startups and large cos alike, though would like this to hit main branch and be tested first.
Some related questions/options that might be helpful in driving this forward:
Further, a really powerful feature to unify tracing across the system would be to optionally pull EXPLAIN ANALYZE into traces -- Definitely an idea for later, but compelling nonetheless
Korede-TA commentedon May 25, 2025
Re manual instrumentation: I've had some luck using a
Proxywrapper on the SQL function/module, and only using that for top-level queries but never SQL builder. This gets around some of the weirdness with tagged template literals and overloadingsqlfor both querying and query fragments (I don't otherwise use other functions like.cursor)There's still a bit of lift to update all the call-sites to use the "tracedSql" variant, but gives some confidence that manual tracing wrapper won't mysteriously break queries with builders/interpolation. Yet to try in production, but seems promising
wataruoguchi commentedon Jul 13, 2025
Hello. I love using
postgres! I hit the same roadblock that you all have had.I created this repository, otel-instrumentation-postgres, for building a wrapper of Postgres.js and the Open Telemetry instrumentation. In the
exampledirectory, you can find a simple hono app with Kysely + Postgres setup and a simple telemetry app. The example app runs alongside Zipkin, Prometheus, and Grafana.The npm package is available here.
Please let me know if you have any questions on https://github.com/wataruoguchi/otel-instrumentation-postgres/issues
rajuAhmed1705 commentedon Feb 16, 2026
We're using postgres.js with Drizzle ORM and OpenTelemetry + Langfuse for tracing. We have auto-instrumentation for HTTP, Express, and Redis — but postgres.js is the missing piece. Our traces show the full request lifecycle except DB queries, which makes it hard to debug slow requests.
Would love to see the
onqueryhook from thequery-statsbranch merged. Even a minimal hook API would let the community build OTel instrumentation on top.porsager commentedon Oct 29, 2026
v4 publishes on Node.js tracing channels for OpenTelemetry (#1171).