Laravel - Lock wait timeout exceeded
When a transaction hangs long enough for the database to abort it, you'll see SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded. In your case, the root cause isn't that migrate:refresh is broken; it's that a prior transaction never committed or rolled back, leaving locks in place on tables that subsequent queries (including migrations) need to touch.
In the code you posted, you wrap business logic in a single manual transaction block and commit only if no exception occurs:
DB::beginTransaction();
try {
// Code that uses exec() to process some images.
// Code that accesses the database
} catch (\Exception $e) {
DB::rollback();
throw $e;
}
// This line runs only if no exception was thrown
DB::commit();
The pattern itself is sound, but there are two common pitfalls here that lead to lingering locks:
- Exceptions outside the try block: If code after the
try(or in a nested function called from within the try) throws, you might not hit the rollback before reachingDB::commit(), or worse, you might commit an incomplete state. - Non-transactional side effects: Using
exec()to process images can trigger background jobs or long-running external processes. If those don't complete quickly, your transaction waits for locks held by other connections until the server-side timeout kicks in.
MySQL/MariaDB will eventually kill a waiting transaction if it exceeds innodb_lock_wait_timeout (default 50 seconds). That's exactly what you're hitting. The error message suggests restarting the transaction, but "restarting" doesn't mean ignoring the underlying lock; it means starting a new query that might still wait on a held lock if the previous one never released its resources.
Why migrations stop working after a hang
When a transaction is killed due to timeout, the connection may be in an inconsistent state until the server cleans up locks. If another process (or migration) tries to access those same rows or tables, it can block waiting for a lock that will never be released if the offending transaction isn't fully cleaned up. That's why even migrate:refresh appears to stop workingâit's trying to acquire locks on tables that are still contested by lingering sessions.
Immediate steps to recover from a hung transaction
Identify and kill the stuck session
Connect directly to your database (via MySQL client or via Forge/SSH) and run:SHOW PROCESSLIST;Look for threads with
Statelike "Locked" or queries blocked on tables you know are locked. Then kill them:KILL <thread_id>;After killing the session, wait a moment and retry your migrations.
Verify lock status
Check which locks remain:SELECT * FROM information_schema.INNODB_LOCKS; SELECT * FROM information_schema.INNODB_TRX;If
INNODB_LOCKSis empty but you still see issues, the problem may be in your application code or connection pool rather than raw InnoDB locks.
Preventing future lock timeouts
Use shorter transactions and release locks sooner
Keep transaction scope narrow. Avoid performing heavy I/O (like image processing) inside the transaction unless absolutely necessary. Instead, offload work to a queue:
// Inside your controller or service
DB::beginTransaction();
try {
// Only DB changes here
ImageRecord::create(['status' => 'processing']);
} catch (\Exception $e) {
DB::rollback();
throw $e;
} else {
DB::commit();
$this->queueImageProcessing($recordId);
}
This ensures the transaction completes quickly, releasing locks before external processes run.
Handle exceptions consistently
Make sure every exception path leads to a rollback before any commit attempt. Consider wrapping your entire controller action or service method in a dedicated transaction manager that guarantees cleanup:
public function handle($request)
{
DB::beginTransaction();
try {
// Business logic with database access
$this->processImages($request);
DB::commit();
return response()->json(['status' => 'ok']);
} catch (\Exception $e) {
DB::rollBack();
// Optionally log the error or push to a dead-letter queue
\Log::error('Transaction failed', ['exception' => $e->getMessage()]);
throw $e; // Let global exception handler deal with it
}
}
Note the explicit DB::rollBack() in the catch block and avoiding any DB::commit() after an exception.
Tune timeout settings if needed
If your workload genuinely requires longer waits, you can increase innodb_lock_wait_timeout in my.cnf or my.ini:
[mysqld]
innodb_lock_wait_timeout = 300
Restart MySQL after changing this. Be cautious: increasing the timeout doesn't fix bad locking patterns; it just delays failure. Use it only after you've optimized queries and reduced lock contention.
Avoid blocking operations inside transactions
Operations like exec() that invoke external scripts or long-running processes should not be synchronous inside a transaction. If you must do them, consider:
- Running them outside the transaction entirely.
- Using Laravel's queue system to decouple processing from request handling.
- Ensuring no external process holds locks on rows your transaction needs.
When to escalate
If SHOW PROCESSLIST shows no stuck threads but migrations still fail, check for:
- Deadlocks being silently retried by the framework.
- Connection pool exhaustion causing apparent hangs.
- Long-running queries not wrapped in transactions that are holding shared locks.
In those cases, review query plans, add indexes where appropriate, and ensure foreign keys are used consistently to avoid non-indexed joins that escalate lock contention.
For production environments where transactional integrity is critical, consider integrating with a managed hosting provider like LaravelCompany for advanced database monitoring and automated failover strategies if persistent locking issues arise.