Skip to content
All writing

Backend · Jul 2025

How to fix race conditions in Go

Two goroutines withdraw ₹500 each from a ₹1000 balance and ₹500 is left. Why it happens, how sync.Mutex fixes it, and what to use when your app runs on more than one server.

Let's say you have a bank account. Two users try to withdraw money at the same time using goroutines. Your balance is ₹1000. They both read the balance. Both deduct ₹500. You expect ₹0, but the final balance is ₹500.

Why it happens

Both goroutines accessed and modified the balance simultaneously. There's no guarantee who reads or writes first, it's a race. This can be solved with a mutex, which locks access so only one goroutine can change the variable at a time.

The fix: sync.Mutex

A code example using sync.Mutex:

// mutex to protect access to balance
var mu sync.Mutex
var balance = 1000

// withdraw tries to deduct 'amount' from balance safely using a mutex
func withdraw(wg *sync.WaitGroup, amount int) {
    defer wg.Done() // mark this goroutine as done once finished

    mu.Lock()         // acquire the lock before accessing shared data
    defer mu.Unlock() // ensure the lock is released after function exits

    if balance >= amount {
        balance -= amount // safely update the balance
        fmt.Println("Withdrawn:", amount)
    } else {
        fmt.Println("Insufficient funds")
    }
}

Now run it in two goroutines:

func main() {
    var wg sync.WaitGroup // WaitGroup helps us wait for multiple goroutines to finish
    wg.Add(2)             // we're about to launch 2 goroutines

    // 'go' runs the function in a new lightweight thread managed by the Go runtime
    go withdraw(&wg, 500)
    go withdraw(&wg, 500)

    wg.Wait() // wait for both goroutines to finish

    fmt.Println("Final Balance:", balance)
}

What's happening here

  • mu.Lock() blocks others from entering
  • mu.Unlock() frees the lock once done
  • sync.WaitGroup waits for both goroutines to finish

The code between Lock and Unlock is a critical section. It's protected by the lock, so two goroutines can never run it at the same time, and the final balance comes out as ₹0.

When one server isn't enough

Up until now, we've been locking access within a single Go app. But what if your app runs on multiple servers or containers? Each server has its own memory, so sync.Mutex won't help. The locks aren't shared across machines. You need a lock that works across a distributed system.

Distributed locks with Redsync

That's where Redsync comes in: distributed locking powered by Redis. It helps multiple services coordinate access to shared resources. Use cases:

  • Safely updating user balances across services
  • Preventing duplicate job executions

A basic Redsync example:

// Step 1: Initialize the Redis client
rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379", // address of your Redis server
})

// Step 2: Create a Redsync-compatible Redis connection pool
pool := redsyncredis.NewPool(rdb)

// Step 3: Create a Redsync instance using the pool
rs := redsync.New(pool)

// Step 4: Create a distributed mutex (lock) with a unique name
mutex := rs.NewMutex("bank-account-lock")

// Step 5: Try to acquire the distributed lock
if err := mutex.Lock(); err != nil {
    log.Fatal("failed to acquire lock") // exit if the lock can't be acquired
}

// Step 6: Critical section, safely perform operations that should not run
// concurrently across servers, e.g. update a user balance, process a transaction

// Step 7: Release the lock after the operation is done
if ok, err := mutex.Unlock(); !ok || err != nil {
    log.Fatal("failed to release lock") // exit if the lock can't be released properly
}

TL;DR

  • Use sync.Mutex to avoid race conditions within a single Go application
  • Use Redsync to coordinate locks across servers using Redis

Concurrency doesn't have to be scary in Go.