简体   繁体   中英

Prevent knex database connection pool from closing when idle

I am using Knex.js to handle my connections to database. I am trying to prevent connection pool from destroying the connections that were idle.

My config looks like this

    {
      "client": "pg",
      "connection": {
        "host" : "localhost",
        "port" : "15432",
        "user" : "postgres",
        "password" : "",
        "database" : "postgres",
        "charset" : "utf8"
      },
      "pool": {
        "min" : 1,
        "max": 7,
        "idleTimeoutMillis": Number.MAX_SAFE_INTEGER
      },
      "migrations": {
        "directory": "app/database/migrations"
      }
    }

However I still keep getting

{"errno":"ETIMEDOUT","code":"ETIMEDOUT","syscall":"read"}

After a period of inactivity.

To my knowledge, when enough time passes a connection should be thrown away from the pool. So if the connections are not used for a while (that is my case) there will be no connections in the pool and the first call I try should fail with given error. Subsequent calls go trough smoothly (until new timeout)

My question is - how to prevent this?

EDIT

after my app is idle for some time, first activity that has to go to the database level fails with given error. Any repeated call will be successful. That is why I came to believe that knex does not detect that a connection is being discarded as idle and it does not reconnect in time for the first query to be finished. I also believe that the problem is on the knex side and not on the database side.

So I managed to fix

{"errno":"ETIMEDOUT","code":"ETIMEDOUT","syscall":"read"}

errors, by making the configuration like this

{
  "client": "pg",
  "connection": {
    .
    .
    .      
  },
  "pool": { <- this is important
    "min" : 0 
  },
}

I found the suggested solution on https://gist.github.com/acgourley/9a11ffedd44c414fb4b8

Thing is, I did not manage to understand why is this a solution and why my previous configuration was not working.

Important thing to notice is that these solutions will not work

{
  "client": "pg",
  "connection": {
    .
    .
    .      
  },
  "pool": { 
    "min" : 0,
    "max" : 7 <- this fails in the same manner
  },
}

or

{
  "client": "pg",
  "connection": {
    .
    .
    .      
  },
  "pool": { 
    "min" : 0,
    "max" : 7 <- this fails in the same manner
    "ping": () => {... ping function ...}
  },
}

So to me this looks like circumventing some existing bug... The bug is either in knex or tarn.js or in node-postgres. Or, the issue might be that I fundamentally do not understand how JS database drivers work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM