Skip to content

opentelemetry support or hooks? #461

Closed

Description

@JerrySievert

hi,

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!

Activity

  1. porsager commented on Aug 14, 2022

    @porsager
    Owner

    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.

  2. JerrySievert commented on Aug 14, 2022

    @JerrySievert
    Author

    fantastic! I look forward to seeing the addition, thanks for considering it.

  3. tomsanbear commented on Sep 27, 2022

    @tomsanbear

    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.

  4. JerrySievert commented on Oct 6, 2022

    @JerrySievert
    Author

    @tomsanbear that's awesome, but is there some trick to getting it to work?

    const {
      PostgresInstrumentation
    } = require('opentelemetry-instrumentation-postgres');
    
    

    and then in my instrumentations when instantiating the sdk:

      instrumentations: [
        getNodeAutoInstrumentations(),
        new HapiInstrumentation(),
        new PostgresInstrumentation(),
        new NetInstrumentation()
      ]
    

    is there something else I need to do?

  5. younanjo commented on Mar 2, 2023

    @younanjo

    @porsager checking to see if there is any updates on supporting OpenTelemetry?

  6. added
    enhancement
    on Jun 25, 2023
  7. porsager commented on Jun 25, 2023

    @porsager
    Owner

    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 query
    result.waiting // the time the query waited to be sent
    result.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:

    const sql = postgres({
      ...,
      onrequest() {
        // query queued
        return () => {
          // query sent
          return () => // query finished
        }
      }
    })

    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:

  8. clouedoc commented on Jun 30, 2023

    @clouedoc

    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"

  9. porsager commented on Jul 1, 2023

    @porsager
    Owner

    That's exactly what the above is? 😉

  10. clouedoc commented on Jul 1, 2023

    @clouedoc

    Oh, haha, yes, sorry about that; I didn't pay enough attention 🤦‍♂️
    Thanks for your library, by the way!

  11. gustavolzangelo commented on Aug 11, 2023

    @gustavolzangelo

    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 query
    result.waiting // the time the query waited to be sent
    result.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:

    const sql = postgres({
      ...,
      onrequest() {
        // query queued
        return () => {
          // query sent
          return () => // query finished
        }
      }
    })

    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:

    @porsager this is perfect! I think these 3 stats are exactly what is needed. Is there any plan to implement this feature?

  12. hastebrot commented on Aug 14, 2023

    @hastebrot

    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.

    Then the trace exporter would receive startTimeUnixNano and endTimeUnixNano (as defined in otlp-transformer/src/trace/types.ts).

  13. mattsoftware commented on Feb 14, 2024

    @mattsoftware

    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!

  14. porsager commented on Feb 14, 2024

    @porsager
    Owner
  15. mattsoftware commented on Feb 14, 2024

    @mattsoftware

    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...

            const sql = postgres({
                host,
                port: databaseSecrets.port,
                database: databaseSecrets.dbname,
                username: databaseSecrets.username,
                password: databaseSecrets.password,
                ssl,
                idle_timeout: 3,
                max_lifetime: 60 * 15,
                onrequest: () => {
                    console.log(
                        "======================= SQL REQUEST queued ======================="
                    );
                    return () => {
                        console.log(
                            "======================= SQL REQUEST sent ======================="
                        );
                        return () => {
                            console.log(
                                "======================= SQL REQUEST finished ======================="
                            );
                        };
                    };
                }
            });
    

    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.

  16. 7 remaining items

  17. abustany commented on Mar 26, 2024

    @abustany

    I updated the patch above to copy the onquery handler on each Query instance, that query can then do whatever it wants with it.

  18. spacetoha commented on May 27, 2024

    @spacetoha
  19. porsager commented on May 27, 2024

    @porsager
    Owner

    sorry no plans right now

  20. devthejo commented on Jul 7, 2024

    @devthejo
  21. mbrevda commented on Jul 11, 2024

    @mbrevda

    Anything we can do to help move this forward?

  22. DAcodedBEAT commented on Oct 25, 2024

    @DAcodedBEAT

    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!

  23. willhoney7 commented on Mar 24, 2025

    @willhoney7

    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.

  24. porsager commented on Mar 24, 2025

    @porsager
    Owner

    Using the branch above and giving your feedback on the API etc in real world usage is a fast track for getting it merged 😉

  25. stephenh commented on Mar 25, 2025

    @stephenh
    Contributor

    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: () => {
            // queued
            return (q: any) => {
              // sent
              recordQuery(
                q.query ?? // q might be a PostgresError
                  q.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?

    Thanks!

  26. Korede-TA commented on May 21, 2025

    @Korede-TA

    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

  27. Korede-TA commented on May 25, 2025

    @Korede-TA

    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

  28. wataruoguchi commented on Jul 13, 2025

    @wataruoguchi

    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.

    The npm package is available here.

    Please let me know if you have any questions on https://github.com/wataruoguchi/otel-instrumentation-postgres/issues

  29. rajuAhmed1705 commented on Feb 16, 2026

    @rajuAhmed1705

    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.

  30. porsager commented on Oct 29, 2026

    @porsager
    Owner

    v4 publishes on Node.js tracing channels for OpenTelemetry (#1171).

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions