Solve a MySQL/MariaDB "Too many connections" error

Leave your reply

Introduction

Learn how to solve the MySQL/MariaDB "Too many connections" error, which occurs when all available MySQL/MariaDB connections are in use. This error may occur in a script which connects to MySQL/MariaDB, or on a webpage which is generated (in whole or in part) from elements provided by a MySQL/MariaDB database.

Choose a New Maximum Number of Connections

The system variable max_connections determines the number of connections which MySQL/MariaDB will accept. The default value is 151 connections, which allows 150 normal connections plus one connection from the SUPER account.

The first thing to decide is what new maximum value you want to set for max_connections. There are several considerations to take into account when increasing the number of MySQL/MariaDB connections. The maximum number which can be supported by the system will depend on:

  • The amount of available RAM.
  • How much RAM each connection takes (simple queries will require less RAM than more labor-intensive connections).
  • The acceptable response time.

According to the MySQL documentation, most Linux systems should be able to support 500-1000 connections without difficulty.

Change max_connections

The max_connections variable will need to be changed in two places:

  1. Update the my.cnf file, so that the new value is used if the MySQL/MariaDB server is restarted.
  2. Use the SET GLOBAL command to update the value on the running MySQL/MariaDB server.

Fortunately, by using this method, you will not need to restart MySQL/MariaDB, and therefore will not need to experience any downtime.

Show the Current max_connections Value

To see the current number of max_connections log in to the MySQL/MariaDB command line client with the command:

mysql -u root -p

Use the command:

SHOW variables;

This will output a list of all of the variables which are set for MySQL/MariaDB. Scroll up through the list to find the value for max_connections.

Update my.cnf

Open the file /etc/my.cnf for editing with the command:

sudo nano /etc/my.cnf

Directly beneath the first line:

[mysqld]

Add a line:

max_connections=[desired new maximum number]

For example, to set max_connections to 200, the first two lines of the file will read:

[mysqld]
max_connections=200

Save and exit the file.

SET GLOBAL

Log in to the MySQL/MariaDB command line client with the command:

mysql -u root -p

Set the new max_connections value with the command:

SET GLOBAL max_connections=[desired new maximum number];

For example, to set max_connections to 200, the command is:

SET GLOBAL max_connections=200;

Exit MySQL/MariaDB with the command:

quit;