Skip to content

Preferred way to handle reconnect #2113

Closed

Description

@chris-rock

In case the db connection is lost, we need to reconnect to the database. I couldn't find a preferred way to handle this issue. Do you have a best practice? The issue can be solved on various ways:

  • handle in sequelize
  • handle in db module like pg
  • handle this issue outside of nodejs with connection handler

Thanks in advance

Activity

  1. janmeier commented on Aug 10, 2014

    @janmeier
    Member

    I believe this would be best handled in sequelize - at least we could retry a number of times and otherwise give up. I believe we could handle this rather nicely actually. Each dialect returns an instance of Sequelize.ConnectionLost when the connector lib gives and error, and the abstract connector manager handles trying to reconect. It should be as simple as just trying the query again, since that should try to fetch a new connection (provided that the previous query flagged its connection as broken properly).

    Flagging this as a feature request

  2. chris-rock commented on Aug 11, 2014

    @chris-rock
    Author

    @janmeier Thanks that would be amazing.

  3. bushev commented on Jan 17, 2015

    @bushev
  4. kungfoolabs commented on Jan 27, 2015

    @kungfoolabs

    +1 This is definitely something desired. Thanks!

  5. gustavohenke commented on Feb 25, 2015

    @gustavohenke

    👍 for this feature.

  6. mxfp0 commented on Feb 25, 2015

    @mxfp0

    👍 Waiting too

  7. gtomitsuka commented on Mar 11, 2015

    @gtomitsuka

    +1 I'm gonna add a bounty for this one

  8. trshafer commented on May 13, 2015

    @trshafer

    +1

  9. Pomax commented on Jun 9, 2015

    @Pomax

    This feature is so important in actual production setting, where databases run on completely different hosts, and having those hosts hiccup completely wreck everything because sequelize won't reconnect even though it should be able to.

    I can't even emphasize how much this should be the most important feature to add as soon as possible, even just an autoreconnect: true to make Sequelize try to reconnect without any kind of checking what actually went wrong would make DB interfacing with it vastly more useful =)

  10. mickhansen commented on Jun 9, 2015

    @mickhansen
    Contributor

    @Pomax so effectively retry queries anytime we get a connection type error? (Retrying a query should try to initiate a new connection assuming the old one was marked invalid which it should have).

    That would necessarily be so hard to implement, could happen at query level and look for a global or local option.

  11. mickhansen commented on Jun 9, 2015

    @mickhansen
    Contributor

    (if you are willing to be a guinea pig i'd be happy to write something like that, we've just been hesitant since it would be hard to have unit or regression tests for, so we need someone to battle test it, and for some reason i've never really encountered it).

  12. mickhansen commented on Jun 9, 2015

    @mickhansen
    Contributor

    Small issue of transactions of course, they would likely need to be retried at the transaction level rather than the query level.

  13. Pomax commented on Jun 10, 2015

    @Pomax

    Yeah, as just a simplest option "retry ad infinitum, or the user explicitly set a retry count" would be amazingly useful already. My api.nihongoresources.com has a database hosted not just on a different machine, but by a different organization, and it drops every so often because the machine it's on power cycles fairly often (few weeks, if not days sometimes), which absolutely destroys API functionality.

    If you want a guinea pig: it can't get worse than what it's doing right now, hook me up ;) This would be amazing to have:

    var reconnectOptions = {
      max_retries: 999,
      onRetry: function(count) {
        console.log("connection lost, trying to reconnect ("+count+")");
      }
    };
    
    var sequelize = new Sequelize(database,username,password, {
                      dialect: "mysql",
                      port: 3306,
                      logging: false,
                      reconnect: reconnectOptions || true
                    });
    

    ("or true" because I'll even just take a plain old "just try to reconnect forever" over "all things now broken" =D)

    Transaction failure could be left up to the user really:

    var reconnectOptions = {
      retry_on_reconnect: {
        transactions: true,
        ...
      },
      max_retries: 999,
      onRetry: function(count) {
        console.log("connection lost, trying to reconnect ("+count+")");
      }
    };
    
  14. self-assigned this
    on Jun 10, 2015
  15. 55 remaining items

  16. added a commit that references this issue on Feb 3, 2018
    8bc1dfd
  17. stringbeans commented on Jun 16, 2018

    @stringbeans

    im still unable to get this working...

    according to the documentation (http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html) it states that there are defaults set for all the pool options..

    my repro steps using mariadb 10.2:

    1. start my api server that is using sequelize v4.37.10
    2. issue a query (works fine)
    3. stop the database
    4. issue a query (fails due to db being down)
    5. start the database
    6. issue a query (continues to fail)

    even after a few minutes it seems as though the connections arent reconnecting and im unable to query the db.

    my config looks like so...

    {
        dialect: 'mysql',
        dialectOptions: {
          multipleStatements: true,
          //this is to force mysql2 lib to coerce decimal numbers into actual numbers instead of strings https://github.com/sequelize/sequelize/issues/8019
          decimalNumbers: true
        },
        replication: {
          write: {
            host: process.env.MYSQL_MASTER_HOST,
            port: process.env.MYSQL_MASTER_PORT,
            username: process.env.MYSQL_MASTER_USERNAME,
            password: process.env.MYSQL_MASTER_PASSWORD
          },
          read: [{
            host: process.env.MYSQL_SLAVE_HOST,
            port: process.env.MYSQL_SLAVE_PORT,
            username: process.env.MYSQL_SLAVE_USERNAME,
            password: process.env.MYSQL_SLAVE_PASSWORD
          }]
        },
        pool: {
          max: process.env.MYSQL_MASTER_CONNECTION_LIMIT,
          min: 1,
          idle: 10000
        },
        define: {
          timestamps: false
        }
    }
    

    this recently affected us because there was an unexpected DB crash with our AWS RDS instance.

  18. kingjerod commented on Sep 27, 2018

    @kingjerod

    @stringbeans
    Did you ever figure this out? Seeing this on production right now, Aurora Postgres failover and Sequelize doesn't reconnect (for over 40 minutes). Before when we didn't have replication I think it worked OK. But after adding replication config it won't reconnect on failover.

  19. kingjerod commented on Sep 27, 2018

    @kingjerod

    I ended up listening for a SequelizeConnectionRefusedError or SequelizeConnectionError in my middleware and if it detects that it restarts the process. A bit hacky but it works.

  20. zhming0 commented on Nov 14, 2018

    @zhming0

    After a lot testing, I can confirm that this issue still exists under replication mode.
    A quick & dirty mitigation is increasing pool.acquire to a huge value, and configure retry like @contra mentioned above.

    I am trying to locate the bug and maybe make a patch for it. (not anymore as we moved to TypeORM 😢 )

  21. bertolo1988 commented on Feb 1, 2019

    @bertolo1988

    My connection to MySQL is lost and never recovers.

    Sequelize: 4.41.1
    Node: 8.12.0

  22. davelandry commented on Feb 11, 2019

    @davelandry

    @kingjerod would you mind posting a code snippet for your middleware hack?

  23. kingjerod commented on Feb 11, 2019

    @kingjerod

    @davelandry

    My processes are managed with PM2 so exiting will cause PM2 to restart the process. There is another middleware before this that catches errors and sets the ctx.body.error message. There is some typescript in here that can be easily stripped out.

    let exiting: boolean = false;
    async function failoverCheck(ctx: Koa.Context, next) {
      await next();
      if (exiting) {
        return;
      }
    
      if (ctx.body && ctx.body.error && typeof ctx.body.error === "string") {
        const error: string = ctx.body.error.toLowerCase();
        const sequelizeErrors = [
          "SequelizeConnectionRefusedError",
          "SequelizeConnectionError"
        ];
        for (const sequelizeError of sequelizeErrors) {
          if (error.includes(sequelizeError.toLowerCase())) {
            exiting = true;
            // We wait 10 seconds so that when it reconnects hopefully the failover is finished
            setTimeout(() => {
              process.emit("SIGTERM");
            }, 10000);
          }
        }
      }
    }
    
  24. gwilakers commented on Feb 25, 2019

    @gwilakers

    Here's my thinking:

    * sequelize already has retry logic for queries
    
    * sequelize already manages the connection pool, and removes closed/errored connections
    

    From what I understand the only missing piece (and the root of this issue) is that the retry around the queries will reuse the same connection, even if it died. I'll try to dig more into this and send a PR, but I think this might end up being a really simple fix - when retrying a query, yield the old connection and ask for a new one.

    This configuration will already retry the queries on connection errors, but it will fail forever because it reuses the old connection:

    // this goes to retry-as-promised for queries
    retry: {
      match: [
        /SequelizeConnectionError/,
        /SequelizeConnectionRefusedError/,
        /SequelizeHostNotFoundError/,
        /SequelizeHostNotReachableError/,
        /SequelizeInvalidConnectionError/,
        /SequelizeConnectionTimedOutError/
      ],
      name: 'query',
      backoffBase: 100,
      backoffExponent: 1.1,
      timeout: 60000,
      max: Infinity
    }

    When a query fails due to a connection error, retry with exponential backoff with a max time of 60 seconds. This seems like a really robust way to manage reconnects/retries, just needs that fix for the connections and this should close a bunch of tickets around this.

    Edit: PR submitted - #8961

    @contra Quick question: I see that the documentation mentions the retry.match and retry.max properties, but none of the other ones. Are those properties undocumented? Thanks.

  25. yocontra commented on Feb 25, 2019

    @yocontra
    Contributor

    @gwilakers Yeah, they are undocumented.

    BTW for retrying queries - this bug is currently breaking some cases: #10453

  26. gwilakers commented on Feb 25, 2019

    @gwilakers

    @contra Okay, thanks for confirming.

    Ironically, I just subscribed to that issue this morning haha. Thanks for the update.

  27. adams-family commented on Mar 11, 2020

    @adams-family

    This doesn't seem to work in one specific case:

    1. first start sequelize with sequelize.sync()
    2. second start mysql db

    The connection to the database is established fine and sequelize is operational, however model sync has been skipped and is never retried.

    Any ideas if I'm doing something wrong?

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

    type: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions