What could cause waiting for table metadata lock?
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:


Lock several tables in the DB
Do its queries
Send a message to chat with the results
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!