All posts

How to Fix Deadlock in Go

Learn how to fix the Deadlock in Go. Step-by-step guide with code examples.

If you've encountered a Deadlock while working with Go, you're not alone. This is one of the most common issues developers face.

What Causes This Error

A deadlock occurs when two or more operations each hold a resource the other needs, creating a circular wait. Neither operation can proceed, and your application hangs or eventually times out.

The Fix

The key is to always acquire locks in a consistent order based on resource ID to prevent circular waits:

func safeTransfer(from, to *Account, amount int) {
    // Always lock in consistent order by ID to prevent deadlock
    first, second := from, to
    if from.ID > to.ID {
        first, second = to, from
    }
    first.mu.Lock()
    defer first.mu.Unlock()
    second.mu.Lock()
    defer second.mu.Unlock()

    from.Balance -= amount
    to.Balance += amount
}

Common Pitfall

A common mistake is to ignore this error during development because it only surfaces under specific conditions. Always test with production-like settings to catch these issues early. If you're working in a team, document this fix in your project's troubleshooting guide so others don't hit the same wall.

Verify the Fix

After applying the fix, restart your Go application and verify the error no longer appears in the console or logs. Test both the happy path and edge cases to be thorough. If the error persists, double-check that your changes were saved and the application fully restarted.

Prevention

To prevent this from recurring unnoticed, set up [Bugsly](https://bugsly.dev) for your Go project — it monitors errors and gives you actionable alerts.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free