Fixing MySQL Server Has Gone Away in Symfony Messenger Workers

#mysql server has gone away symfony messenger

Founder & Lead Developer

Expert in software development and legacy code optimization

LinkedIn

If you search for "mysql server has gone away symfony messenger", you probably have a worker that runs fine all afternoon and then fails the first message of the morning with SQLSTATE[HY000]: General error: 2006 MySQL server has gone away. The message lands in the failure transport, a retry succeeds, and nobody can reproduce it locally. The cause is almost always the same: a PHP process that lives for hours is holding a database connection that MySQL closed a long time ago.

A normal web request opens a connection, uses it for a few hundred milliseconds and throws it away. A messenger:consume process keeps one Doctrine connection for its whole life. When the queue is quiet, that connection sits idle, and MySQL does not wait forever.

Why MySQL server has gone away hits Symfony Messenger workers

MySQL closes connections that have been idle longer than wait_timeout. The default is eight hours, but many managed databases and hosting setups use a much lower value, and a proxy or load balancer between your application and the database may drop idle TCP connections even sooner. Doctrine does not notice any of this. The connection object in your worker still looks open until the next query hits a dead socket.

So the timeline usually looks like this. The worker starts at 6 p.m. and processes the evening traffic. The queue goes quiet at night. At 9 a.m. the first order comes in, the handler calls $entityManager->find(), and the query fails with error 2006, or sometimes 2013 ("Lost connection to MySQL server during query").

One detail surprises people: the transport matters. If you use the Doctrine transport on the same connection, the worker polls the messages table every second or so, which keeps the connection busy, and you may never see the error. Switch to AMQP or Redis and the default DBAL connection suddenly has nothing to do between messages. If you are weighing transports for other reasons, our comparison of AMQP, Doctrine and Redis transports covers the trade-offs.

The two Doctrine middlewares and what they do

Symfony ships two middlewares in the Doctrine bridge that exist for exactly this problem. You enable them per bus:

# config/packages/messenger.yaml
framework:
    messenger:
        buses:
            messenger.bus.default:
                middleware:
                    - doctrine_ping_connection
                    - doctrine_close_connection
                    - doctrine_transaction

doctrine_ping_connection runs before your handler, and only for messages that a worker consumes (it skips messages that are dispatched and sent to a transport). It runs a cheap dummy query on the connection. If that query fails, the middleware closes the connection so DBAL reconnects on the next query. It also checks whether the EntityManager has been closed and, if so, resets it through the manager registry. That second part matters more than most people expect, and we will come back to it.

doctrine_close_connection runs after the handler and closes the connection. The next message then opens a fresh one. This costs one reconnect per message, which is fine for most queues and wasteful for a queue that processes hundreds of tiny messages per second. On PostgreSQL it also keeps idle workers from holding connection slots, which is a separate reason to use it.

You can use either one or both. Ping on its own fixes the gone-away error for most setups. Close on its own also fixes it, because no connection lives long enough to time out. Using both is a common default and the cost is small.

Order matters with doctrine_transaction. Put the ping before the transaction middleware, so the connection is verified before a transaction starts on it.

What changed when DBAL removed ping()

Older blog posts and Stack Overflow answers tell you to call $connection->ping() in your handler or in an event listener. That method was deprecated in DBAL 2 and removed in DBAL 3. If you upgraded and copied an old snippet, it will not work.

The middleware itself was rewritten for this. It no longer calls a ping() method. It runs the platform's dummy select (SELECT 1 on MySQL) and catches the exception. If you wrote a custom listener in the DBAL 2 days, delete it and use the middleware instead. If you have a specific reason to keep your own check, copy the same approach: run a trivial query, catch the DBAL exception, call close(), and let the next query reconnect.

If you are in the middle of a larger Doctrine upgrade, this is one of the small breaking changes that tends to show up weeks later in production rather than in tests. Our notes on the Doctrine ORM 3 upgrade list others.

The closed EntityManager after an exception

The gone-away error has a nasty sibling: The EntityManager is closed. Doctrine closes the EntityManager when a flush fails, for example after a unique constraint violation or a deadlock. In a web request that is harmless, because the next request gets a new EntityManager. In a worker, the same EntityManager instance would serve every following message, and every one of them would fail.

This is the second reason to use doctrine_ping_connection. Because it resets a closed EntityManager before each consumed message, one bad message does not poison the next thousand. Without it, you get a cascade: one deadlock at 10:14, then every message after it fails until someone restarts the worker.

Two rules help here. First, do not inject the EntityManager into a service and keep a reference to a repository in a property for the lifetime of the worker. Ask the registry for the manager when you need it, or make sure the service is reset between messages. Second, do not catch Doctrine exceptions in a handler and carry on with the same EntityManager. Let the exception bubble up so Messenger can retry the message with a clean state.

Long handlers are a different problem

The ping middleware checks the connection once, before the handler starts. It cannot help if the handler itself waits a long time between two queries. A typical example: the handler loads an order, calls a slow external API for several minutes, generates a PDF, and then tries to flush. If the gap between the first and the last query is longer than the timeout on your network path, the flush fails with the same error.

There are a few ways out. Split the work into smaller messages, so the slow API call happens in one message and the database write in the next. Do the slow part first and touch the database only at the end. Or, if neither fits, close the connection yourself right before the database work with $connection->close(), so DBAL opens a fresh one. The last option is a workaround, so leave a comment explaining why it is there.

Worker limits: restart before things go stale

Even with the middlewares in place, a worker should not run forever. Memory grows, caches fill up, and a deploy should not have to wait for a process that started three weeks ago. messenger:consume has options for this:

php bin/console messenger:consume async \
    --time-limit=3600 \
    --memory-limit=256M \
    --limit=1000

--time-limit stops the worker after the given number of seconds, --memory-limit stops it when memory use passes the threshold, and --limit stops it after a number of messages. The worker finishes the current message before it exits. A time limit of an hour or less also caps how long any single connection can live, which on its own makes the gone-away error much rarer.

These limits only work if something restarts the worker, which is what supervisor or systemd are for.

Supervisor configuration

A minimal supervisor program for one consumer looks like this:

[program:messenger-consume]
command=php /var/www/app/bin/console messenger:consume async --time-limit=3600 --memory-limit=256M
user=www-data
numprocs=2
process_name=%(program_name)s_%(process_num)02d
autostart=true
autorestart=true
startsecs=0
stopwaitsecs=60

autorestart=true brings the worker back after it exits because of a limit. startsecs=0 stops supervisor from treating a quick exit as a failed start, which matters when a worker exits soon after starting because of a limit. stopwaitsecs gives a running handler time to finish before supervisor kills it during a deploy.

On deploy, run php bin/console messenger:stop-workers. It signals every worker to exit after its current message, supervisor starts new ones, and the new processes run the new code with fresh connections.

A checklist for your workers

If you are fighting this error right now, check these in order:

  1. Is doctrine_ping_connection enabled on every bus that is consumed by a worker?
  2. What is wait_timeout on your database, and is there a proxy or load balancer with its own idle timeout?
  3. Do the workers run with --time-limit and --memory-limit, and does supervisor restart them?
  4. Does any handler wait minutes between its first and last query?
  5. Does any service keep a reference to the EntityManager or a repository across messages, or swallow Doctrine exceptions?

In our experience the problem is usually in the first two items. The other three explain the cases where the error keeps coming back after the obvious fix. Once workers are stable, the next step is knowing when they stop being stable, and our guide to monitoring Messenger queues and dead letter queues covers that. For high-volume queues, the post on backpressure, poison pills and rate limiting goes further.

When the queue keeps surprising you

Gone-away errors are usually a configuration problem, and they are fixed in an afternoon. When they show up together with deadlocks, a growing failure transport and workers that need a manual restart every few days, the cause is often deeper in how the application handles background work. That is the kind of problem we look at in our legacy code optimization and code quality consulting work.

If your Symfony workers keep losing their connection or their state and you want a second pair of eyes on the setup, write to hello@wolf-tech.io or have a look at what we do on wolf-tech.io.