Hook for a db connection being open?

We had one (or a few machines) go rogue the other day and suddenly 6K connections were opened to the DB. Now we are in the investigation mode and what I was thinking is that it will be good to have a hook for when a new connection is open.

Is there already such a hook? Is there a way to find where and which part of the code will open a new connection. I am thinking that if there is such a hook we can log the pid of the process, probably the stack trace, figure our which controller or job was misbehaving.

Thanks

Hi Kiril. Which database adapter? With PostgreSQL, there are various timeout parameters you might want to set on the server side to prevent excessively long lived “idle” transactions, and to kill off (cancellation) any idle connections that are stuck in a transaction. For other DB adapters, there may be similar server side settings.

Setting those values would treat the symptom more than the root cause, but if you aren’t monitoring for excessive idle connections now, it’s worth considering adding. New connection establishment can be costly. I believe by default Active Record will cancel idle connections after 5 minutes of no activity (no transactions/statements).