Mysql – What could cause waiting for table metadata lock

lockingmyisamMySQL

I am using a MySQL 5.6 DB with MyISAM tables under FreeBSD 8.3. The main part of code is in PHP, but the problem arises, when I launch the self-written on C++ chat-server. I use the mysql.h for DB connections and libwebsockets for both HTTP and websockets interaction. The previous version was written in C, no locks happened.
The chat server has a websocket regime and the refresh regime. It also uses the database for user authentication and loading/saving of settings.

Now when I run this server, after a certain period, the database gets flooded with connections with different queries, all with the status "Waiting for table metadata lock". When I kill the chat, the queries start being processed.

I am 100% sure, there are no ALTER TABLE, CREATE TABLE or similar queries being executed at any time, so they are not the reason.

So I don't understand what in this situation may be the reason for database to hang, and how can I trace and solve it. I would appreciate any help or ideas! Thanks ahead!

Best Answer

Thanks to jynus for advising on working with general log, the problem has been solved!

As in most of the cases, the error was quite simple, here is the description:

On certain occasions, a function was invoked, that performed the following:

  1. Lock several tables in the DB

  2. Do its queries

  3. Send a message to chat with the results

  4. Unlock tables

The message to the chat was sent via a socket with connection timeout of 10 seconds. Sometimes, after step 1, at step 3, the chat was busy logging on the new user, and was trying to access the tables, that are locked. So the loop was closed - the chat was waiting for the unlock and the function was waiting for processing its connection request.

10 seconds was enough for the other requests to reach the max_connections limit and lock the database.

The only thing that puzzles is me, is why the state of all queries was "Waiting for table metadata lock".

After switching the places of steps 3 and 4, the problem was no more.

Thanks for help!