Skip to content

Can't create more than max_prepared_stmt_count statements #10832

Description

@Horyougen

When my server runs for a period of time, this prompt appears.

"can't create more than max_prepared_stmt_count statements".

I checked the status of MySQL and got the following results:

mysql> SHOW GLOBAL STATUS LIKE 'com_stmt%';
+-------------------------+---------+
| Variable_name           | Value   |
+-------------------------+---------+
| Com_stmt_execute        | 6512872 |
| Com_stmt_close          | 0       |
| Com_stmt_fetch          | 0       |
| Com_stmt_prepare        | 18313   |
| Com_stmt_reset          | 0       |
| Com_stmt_send_long_data | 0       |
| Com_stmt_reprepare      | 0       |
+-------------------------+---------+
mysql> show variables like "%prepared%";
+------------------------------------------------------+-------+
| Variable_name                                        | Value |
+------------------------------------------------------+-------+
| max_prepared_stmt_count                              | 16382 |
| performance_schema_max_prepared_statements_instances | -1    |
+------------------------------------------------------+-------+

My friend suggested that I can modify mysql's 'max_prepared_stmt_count' to a higher value.I checked the sequelize code and found that the connection pool was just 'closed' connection, does not close PreparedStatement.Is there any API can solve this or only can be modifying 'max_prepared_stmt_count'.very thanks.

Environment

Dialect:

  • mysql
    Sequelize version: 5.3.5
    Database version: 8.0.15
    Node Version: v10.3.0
    OS: Centos 7.5
    TypeScript version: 3.4.3

Activity

  1. Josephu commented on Jul 15, 2019

    @Josephu

    I have also found this issue, and the root cause seem to be that sequelize does not parameterize variables when you use Op.x. As an example, below is a query that had this issue:

      return Table.update({ date: Date.now() }, {
        where: {
          [Op.and]: {
            hotelUuid: { [Op.eq]: hotelUuid },
            nights: { [Op.eq]: nights },
            source: { [Op.eq]: source },
            checkIn: { [Op.eq]: moment(checkIn).valueOf() },
            maxAdults: { [Op.in]: maxAdults }
      },
        },
      })
    

    And by using Sequelize debug mode, I see:

    Executing (default): UPDATE `table` SET `date`=?,`updated_at`=? WHERE (`nights` = 2 AND `source` = 'XYZ' AND `max_adults` IN (1) AND `hotel_uuid` = 'hotel-uuid-1' AND `check_in` = '2017-12-31 13:00:00.000')
    

    So after I change to:

      return Table.update({ date: Date.now() }, {
        where: {
          hotelUuid,
          nights,
          source,
          checkIn: moment(checkIn).valueOf(),
          maxAdults
          },
      })
    

    What I see from debug log is:

    Executing (default): UPDATE `table` SET `date`=?,`updated_at`=? WHERE `nights` = ? AND `source` = ? AND `max_adults` IN (1) AND `hotel_uuid` = ? AND `check_in` = ?
    

    Interesting you'll notice that even after the change, max_adults still has a static value inside, so it seems that arrays are also not parameterized properly.

    Environment
    mysql 5.7
    Sequelize 5.9.4
    node v8.12.0

  2. bsapot commented on Aug 20, 2019

    @bsapot
    Contributor

    We ran into the original issue mentioned by @play2010dk as well and solved it. The number of prepared statements is controlled by the mysql2 library. The mysql2 lib uses a lru cache to cache the prepared statements. The default number of cached statements is 16,000 per connection.

    See the documentation on prepared statements.

    If you have a connection pool with more than 1 connection you may create:
    number of connections * 16,000 = prepared statements.

    To solve this you can set maxPreparedStatements to a a much lower value in the sequelize connection config.

    Here is an example, it is set in the dialect options.

    const sequelizeOptions = { 
        dialect: "mysql",
        port: mysqlPort,
        logging: sqlLogging,
        benchmark: true,
        pool: {
            min: 10,
            max: 50
        },
        replication: {
            read: [
                { host: mysqlHost, username: mysqlUser, password: mysqlPassword },
                { host: mysqlHost2, username: mysqlUser, password: mysqlPassword }
            ],
            write: { host: mysqlHost, username: mysqlUser, password: mysqlPassword }
        },
        dialectOptions: {
            // @see https://github.com/sequelize/sequelize/issues/8019
            decimalNumbers: true,
            maxPreparedStatements: 100
        },
        timezone: "+00:00"
    };

    Side note:

    There may be a bug in the lru cache mysql is using or a bug in how lru cache is used by the mysql2 lib. We only have about 100 parameterized querys (update,inserts) so we should never have more than 100 per connection. But we are seeing 1000s in production and we can replicate it in our development environment.

    Environment

    mysql 5.7
    Sequelize 5.15.0
    node v10.16.0

  3. papb commented on Aug 21, 2019

    @papb
    Member

    @bsapot Thanks a lot for sharing this solution.

    As I understand, you managed to workaround the issue successfully with the above, right?


    Side note: although completely unrelated, thanks for accidentaly bringing issue #8019 to my attention from your code snippet above!

  4. added
    dependency
    existing workaround
    status: awaiting response
    type: bug
    on Aug 21, 2019
  5. bsapot commented on Aug 21, 2019

    @bsapot
    Contributor

    Yes, this seems to have fixed the issue the first person was having which is the problem we had. We deployed it to production earlier today and it is working well.

  6. added and removed
    status: awaiting response
    on Aug 21, 2019
  7. Horyougen commented on Aug 21, 2019

    @Horyougen
    Author

    Thank you very much.Before that, I had to set 'max_prepared_stmt_count' to a very big value and restart my MySQL service periodically.

  8. papb commented on Aug 21, 2019

    @papb
    Member

    Since the above is technically a workaround, I will leave this open for now

  9. reopened this on Aug 21, 2019
  10. 16 remaining items

  11. ephys commented on Mar 23, 2023

    @ephys
    Member

    It was released in Sequelize 7 alpha 20

  12. senthilbalajir commented on Mar 23, 2023

    @senthilbalajir

    Thanks @ephys, as the issue version 6, any chances of merging the fix to version 6 package?

  13. ephys commented on Mar 23, 2023

    @ephys
    Member

    I wish it were possible but this change required a complete redesign of how we generate WHERE which took a year of work and many breaking changes which we cannot backport :(

  14. senthilbalajir commented on Mar 23, 2023

    @senthilbalajir
  15. th1nkful commented on Mar 31, 2023

    @th1nkful

    @senthilbalajir hope this can help you(and others, like me) fix the issue and how you can avoid it on v6 (I just spent a few days migrated my project to v7, but needed to get a v6 deployment stable):

    • max_prepared_stmt_count is for the server, it is for ALL connections
    • MySQL sets this variable as a default to 16382
    • mysql2 internally cached prepared statements PER CONNECTION and will keep up to the limit set using maxPreparedStatements
    • mysql2 sets this variable as a default to 16000
    • if you have lots of connections in your pool you will blow past 16382 easily when under load becuase of the Sequelize bug (if 16000 x num connections is greater than 16382 you will have issue, 2 connections? Problem. Sequelize default pool size is 5 - definitely can get past the 16000)
    • setting maxPreparedStatements lower tells mysql2 to reset the prepared statements it has cached when it hits that value

    Hopefully this helps you, this was crashing our project in production a fair bit when load got high, requiring a MySQL server restart

    This issue over on the mysql2 project helped me wrap my head around all the variables to fully understand why it was happening:
    sidorares/node-mysql2#702 (comment)

  16. ephys commented on Apr 1, 2023

    @ephys
    Member

    Then I think we could fix the problem by setting maxPreparedStatements's default value to to (max_prepared_stmt_count ?? 16382) / poolMaxSize

    We'd still be generating too many different queries in v6, but at least it would not crash

  17. reopened this on Apr 1, 2023
  18. senthilbalajir commented on Apr 3, 2023

    @senthilbalajir

    @th1nkful, worked for me the setting up max prepared statements, but slow in a bit.
    @ephys, thanks for re-opening the issue. The calculation will work for single instance but will it work in multi instance scenarios?

  19. ephys commented on Apr 3, 2023

    @ephys
    Member

    You'd need to divide max_prepared_stmt_count by how many instances you expect to have running at the same time, but otherwise yes

  20. fang-hd commented on Nov 13, 2024

    @fang-hd

    I'm using 5.7, has the latest version fixed this issue?

  21. igor-gregori commented on Dec 16, 2024

    @igor-gregori

    Hello everyone.

    Has this issue been fixed in any version of Sequelize 6 @ephys ?

    Or is it still recommended to set maxPreparedStatements?


    I'm doing some tests, and apparently updating with sequelize.query solves my problem easily.

  22. added theissue type on Mar 9, 2025
  23. removed
    type: other
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P4: nice to havedependencyexisting workaroundstatus: understood

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions