Skip to content

Go Redis Transaction

DodaTech 1 min read

In this tutorial, you'll learn about Go Redis: Transaction (MULTI/EXEC). We cover key concepts, practical examples, and best practices.

Redis transactions -- Use WATCH with TxPipeline for optimistic locking and conditional transactions.

The Problem

Redis transactions use MULTI/EXEC but do not support rollback. Use WATCH to implement optimistic locking. Use TxPipeline for simpler atomic operations.

Wrong

// Race condition:
val := rdb.Get(ctx, "key").Val()
rdb.Set(ctx, "key", val+1) // Another client may have changed it!

Output:

// Lost update! Race condition.
err := rdb.Watch(ctx, func(tx *redis.Tx) error {
    val, err := tx.Get(ctx, "key").Int()
    if err != nil { return err }
    _, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
        pipe.Set(ctx, "key", val+1, 0)
        return nil
    })
    return err
}, "key")

Output:

// Atomic increment. WATCH retries on conflict.

Prevention

  • Use Watch for optimistic locking
  • Use TxPipelined inside Watch
  • Watch retries the function on conflict
  • Unwatch keys when done
  • Watch works on individual keys or key patterns

Common Mistakes with redis transaction

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**What happens if WATCH detects change?**

The transaction fails and Watch retries the function.

Can I WATCH multiple keys?

Yes. Pass multiple keys to Watch.

Is there retry limit?

No built-in limit. Track retries in your code.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro