Skip to content

RegisterDBStatsMetrics provides no way to Unregister, leading to memory leaks #580

Closed

Description

@sfc-gh-jzana

Description

Our application is a server that opens and closes a sql.DB instance for each request (since each one gets credentials based on the caller)

Our opening pattern looks like this:

			db := otelsql.OpenDB(c, options...)
			otelsql.RegisterDBStatsMetrics(db, options...)
			return db

We recently observed that with increased requests per second, our memory allocations and heap size was growing. Profiling the situation pointed to many instances of (*contextAwareMeter).Float64Histogram allocated under RegisterDBStatsMetrics

Looking at the code for RegisterDBStatsMetrics , it calls RegisterCallback and discards the first return value, which is a Registration. Registration has an Unregister function that is supposed to be called when you are done according to the README. "use Meter.RegisterCallback and Registration.Unregister to add and remove callbacks without leaking memory."

otelsql never calls Unregister and gives us no hook to do so, so I believe this is a memory leak.

Environment

  • OS: linux
  • Architecture: x86
  • Go Version:1.25
  • otelsql version: 0.40.0

Steps To Reproduce

  1. In a loop, open and close a sql.DB instance, register stats on it, and close it:
  2. Take a heap dump

Something like this should work

for  {
	db := otelsql.OpenDB(c, options...)
	otelsql.RegisterDBStatsMetrics(db, options...)
	db.Close()
}

Expected behavior

RegisterDBStatsMetrics should return a Registration which can be used to Unregister whenever the applicattion chooses to.

Activity

  1. added
    bug
    on Dec 14, 2025
  2. XSAM commented on Dec 16, 2025

    @XSAM
    Owner

    Hey @sfc-gh-jzana, thanks for the issue! I have submitted a PR to fix this. Let me know if this does not resolve your problem.

  3. added 2 commits that reference this issue on Dec 16, 2025
    60175c2
    92a17e7
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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions