How do I implement idempotency keys with Redis in Go?

Implementing idempotency keys is crucial for ensuring that repeated requests do not result in unintended side effects, particularly in a distributed system. Using Redis can help manage these keys efficiently. Here is how you can implement idempotency keys with Redis in Go.

Example Implementation


package main

import (
    "context"
    "fmt"
    "github.com/go-redis/redis/v8"
    "net/http"
)

var ctx = context.Background()

// Redis client initialization
var rdb = redis.NewClient(&redis.Options{
    Addr: "localhost:6379", // Address of the Redis server
})

// Function to check idempotency key
func handleRequest(w http.ResponseWriter, r *http.Request) {
    idempotencyKey := r.Header.Get("Idempotency-Key")
    
    if idempotencyKey == "" {
        http.Error(w, "Missing Idempotency-Key", http.StatusBadRequest)
        return
    }

    // Check if the key already exists in Redis
    exists, err := rdb.Exists(ctx, idempotencyKey).Result()
    if err != nil {
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
        return
    }

    if exists > 0 {
        http.Error(w, "Duplicate request", http.StatusConflict)
        return
    }

    // Mark the idempotency key as used
    rdb.Set(ctx, idempotencyKey, "processed", 0) // Set a TTL if desired

    // Your business logic goes here
    fmt.Fprintln(w, "Request processed successfully")
}

func main() {
    http.HandleFunc("/", handleRequest)
    http.ListenAndServe(":8080", nil)
}
    

idempotency keys Redis Go distributed systems request processing idempotent requests Go programming Redis implementation