Sharing Database Connection among Middleware instances

I am developing a Caddy middleware plugin with custom authentication logic. The plugin is added to multiple routes. As part of the middleware logic, I need to connect to a postgresql database, but I do not think it is efficient to instantiate a DB connection for each “instance” of the plugin. Is there a recommended way to share a connection among plugin instances, for example a singleton pattern, or something similar?

Thank you all in advance.

1 Like

Great question – yes, definitely just do this once if possible.

You can use a UsagePool to share instances of a DB connection across instances of a module, and even across config reloads that use the same DB connection:

https://pkg.go.dev/github.com/caddyserver/caddy/v2#UsagePool

(Use NewUsagePool(), then LoadOrNew() or LoadOrStore() methods.)

Use this in your module’s Provision() method. Make sure to call Delete() in your module’s Cleanup() method.

3 Likes

Alternatively, if the UsagePool stuff is too complicated to manage, you could ensure there’s only a single instance of the HTTP handler by using named routes in the config. Obviously this makes the config author responsible for using that feature instead of the plugin itself taking responsibility for pooling the connections, so it’s a tradeoff.

3 Likes

This is exactly what I was looking for, thanks!

1 Like