dedup

package
v0.18.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package dedup runs an operation once per key and hands the result of its first success to the repeats, the way a cache hands out a value:

id, err := k.Do(ctx, "refund/"+orderID, func(ctx context.Context) (string, error) {
    return payments.Refund(ctx, orderID)
})

The package is universal: it knows no other package of skit. The service wraps its own HTTP handlers, consumers, jobs and functions in Do; the recipes below show how. The records live in memory or in Redis, and the service names the store explicitly.

Outcomes

Do looks the key up first:

  • free or expired: fn runs under the lease as its deadline. A success is encoded with encoding/json/v2 and stored for the TTL. An error of fn is returned as it is, with the value of fn, and frees the key, as a panic of fn does, so a repeat runs fn again.
  • done: Do decodes the stored success and returns it; fn does not run.
  • running: Do returns ErrInProgress at once, without waiting. The caller decides: an HTTP handler answers 409, a consumer requeues, a job fails and retries, a scheduled run skips.
  • store down: Do returns an error wrapping ErrUnavailable; fn does not run.

When the success cannot be stored — the store fails, or fn outlived the lease and lost the key — Do still returns it and logs a warning; a repeat may run fn again. Do never runs inside a transaction: the record in memory or Redis does not roll back with it (see the recipe "An effect in your own database").

Keys

A key names one operation and is the same on every repeat of it: the Idempotency-Key of a request, the id of a message, a slot of a schedule. Put the owner in front of it ("user-7/" + header) so that callers never share keys, and join the parts with a separator none of them contains. The stored success must decode into the T of every repeat: an incompatible change of T goes under a new prefix ("refund.v2/" + id).

Lease and TTL

WithLease (default 1m) is the deadline of fn and the life of the record of a running call: a crashed holder blocks its key no longer than that. Long work takes a longer lease. Each call holds its key with a token of its own, so a call whose lease ended neither overwrites nor frees the record of the next. WithTTL (default 24h) is how long a stored success is handed to repeats, counted from its completion.

Stores

New takes the store from the scheme of a uri, so the config of the service names it: mem:// or redis://host:port/db (rediss:// for TLS, unix:// for a socket, the query parameters of redis.ParseURL). An empty or unknown uri is an error: there is no store by default. Close closes the Redis client New opened. NewMemory and NewRedis build the same stores in code; NewRedis takes a client the caller owns and closes.

The memory store keeps the records in the process: tests and a service of one replica. Redis shares them between replicas: a record is the string key "dedup:"+key, one script per operation. A new key costs two round trips, a repeat one. Run Redis with maxmemory-policy noeviction or give dedup an instance of its own: an evicted record runs fn again. The memory it takes is about calls per second × TTL × the size of a result.

Recipes

An HTTP handler: the key is the Idempotency-Key of the request behind the subject of the caller, and T is the response — status, content type and body — so a retry gets the same answer (see the example of Keeper.Do). An error response is an error of fn: it is not stored, and a retry runs the handler again. A final error that the retry must see again, such as 422, is a value of fn. ErrInProgress answers 409 with Retry-After, ErrUnavailable 503. To reject another request under the same key, put a hash of its body in T and compare it after Do.

A message of a broker: the key is the group of the subscription, the source and the id of the message, so the replicas of a group share the records and different groups do not. A verdict other than Ack is an error of fn: the key is freed and the redelivery runs the handler again. ErrInProgress and ErrUnavailable requeue the message. A stable message id comes from the queue of events; a producer that publishes directly sets a deterministic one.

A schedule on every replica: the key is the name of the job and its slot, name + "/" + time.Now().UTC().Truncate(time.Minute). A schedule of five fields fires at second zero, so the replicas count the same slot; one runs the job, the others get ErrInProgress or the stored success and skip. An error frees the slot for a replica that fires later. @every does not fit: the replicas fire at different moments.

At most once, for an effect where a loss is better than a duplicate (SMS, email, push): mark the key with an empty fn first, and run the effect only if this call set the mark. A crash or an error after the mark loses the effect:

first := false
_, err := k.Do(ctx, "sms/"+id, func(context.Context) (struct{}, error) {
    first = true
    return struct{}{}, nil
})
if err != nil || !first {
    return err
}
return sms.Send(ctx, phone, text)

An effect in your own database needs no dedup: exactly once comes from a mark that commits with the data, in the same transaction — a unique index of the domain or an inbox table of your own with INSERT ... ON CONFLICT DO NOTHING. Zero rows means done; the repeat reads what the first one made. A concurrent duplicate waits on the index for the first transaction.

A task of a queue lives longer than a lease: when a worker crashes, the record of dedup expires before the queue hands the task out again. Keep its effect in your own database with the id of the task as the key, as above, and pass a key down to an external call.

A key down: an external system that takes an idempotency key closes the gap between an effect and its record. Derive the key from what is stable between repeats — the id of a message, of a task, of the domain — and send hex(sha256(...)) of it: a fixed length that does not expose the data.

Example

An error of fn is not stored: it frees the key, and the repeat runs fn again. The first success is stored and handed to the repeats after it.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/assanoff/skit/dedup"
)

func main() {
	k := dedup.NewMemory(dedup.WithTTL(time.Hour))
	ctx := context.Background()

	attempt := 0
	charge := func(context.Context) (string, error) {
		attempt++
		if attempt == 1 {
			return "", errors.New("payments: timeout")
		}
		return fmt.Sprintf("charge-%d", attempt), nil
	}
	for range 3 {
		id, err := k.Do(ctx, "charge/42", charge)
		fmt.Printf("%q %v\n", id, err)
	}
}
Output:
"" payments: timeout
"charge-2" <nil>
"charge-2" <nil>

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInProgress means another call holds the key: its fn is still running.
	ErrInProgress = errors.New("dedup: in progress")
	// ErrUnavailable means the store failed and fn was not called.
	ErrUnavailable = errors.New("dedup: store unavailable")
)

Functions

This section is empty.

Types

type Keeper

type Keeper struct {
	// contains filtered or unexported fields
}

Keeper runs an operation once per key and hands the stored result of its first success to the repeats. It is safe for concurrent use.

func New

func New(uri string, log *slog.Logger, opts ...Option) (*Keeper, error)

New builds a Keeper on the store the scheme of uri names, so a service picks its store in its config:

  • mem:// — the memory of the process, as NewMemory;
  • redis://[user:password@]host:port/db, rediss:// for TLS, unix:// for a socket — a client of redis.ParseURL, with its query parameters such as dial_timeout, as NewRedis. Close closes the client.

Any other uri, an empty one included, is an error. log is the one of NewRedis.

Example

The service names its store in its config: mem:// for one replica, redis://host:port/db for many.

package main

import (
	"context"
	"fmt"
	"log/slog"
	"time"

	"github.com/assanoff/skit/dedup"
)

func main() {
	k, err := dedup.New("mem://", slog.Default(), dedup.WithTTL(time.Hour))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() { _ = k.Close() }()

	v, err := k.Do(context.Background(), "greeting/1", func(context.Context) (string, error) {
		return "hello", nil
	})
	fmt.Println(v, err)
}
Output:
hello <nil>

func NewMemory

func NewMemory(opts ...Option) *Keeper

NewMemory builds a Keeper whose records live in the memory of the process: tests and a service of one replica. Its warnings go to slog.Default.

func NewRedis

func NewRedis(client redis.Cmdable, log *slog.Logger, opts ...Option) *Keeper

NewRedis builds a Keeper whose records live in Redis under the prefix "dedup:", over client (a *redis.Client or *redis.ClusterClient). log receives the failures to complete or release a key; nil means slog.Default.

Example

The replicas of a service share their records through Redis.

package main

import (
	"log/slog"
	"time"

	"github.com/redis/go-redis/v9"

	"github.com/assanoff/skit/dedup"
)

func main() {
	client := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
	defer func() { _ = client.Close() }()

	k := dedup.NewRedis(client, slog.Default(),
		dedup.WithTTL(time.Hour), dedup.WithLease(30*time.Second))
	_ = k
}

func (*Keeper) Close

func (k *Keeper) Close() error

Close closes the Redis client New opened. It does nothing for a Keeper of NewMemory, or of NewRedis, whose client belongs to the caller.

func (*Keeper) Do

func (k *Keeper) Do[T any](ctx context.Context, key string, fn func(ctx context.Context) (T, error)) (T, error)

Do returns the stored result of key, or runs fn and stores its success for the TTL. A repeat while fn runs gets ErrInProgress. An error of fn is returned as it is, with the value of fn, and frees the key, as a panic of fn does; the key is never stored then. A failure of the store before fn wraps ErrUnavailable.

Example

The second call with the same key gets the stored result; fn runs once.

package main

import (
	"context"
	"fmt"

	"github.com/assanoff/skit/dedup"
)

func main() {
	k := dedup.NewMemory()
	ctx := context.Background()

	calls := 0
	refund := func(context.Context) (string, error) {
		calls++
		return "refund-1", nil
	}
	for range 2 {
		id, err := k.Do(ctx, "refund/42", refund)
		fmt.Println(id, err)
	}
	fmt.Println("calls:", calls)
}
Output:
refund-1 <nil>
refund-1 <nil>
calls: 1
Example (AtMostOnce)

An effect where a loss is better than a duplicate: the mark goes first, and only the call that set it sends.

package main

import (
	"context"
	"fmt"

	"github.com/assanoff/skit/dedup"
)

func main() {
	k := dedup.NewMemory()
	ctx := context.Background()

	send := func(id, text string) error {
		first := false
		_, err := k.Do(ctx, "sms/"+id, func(context.Context) (struct{}, error) {
			first = true
			return struct{}{}, nil
		})
		if err != nil || !first {
			return err
		}
		fmt.Println("sent:", text)
		return nil
	}
	fmt.Println(send("n-1", "your code is 1234"))
	fmt.Println(send("n-1", "your code is 1234"))
}
Output:
sent: your code is 1234
<nil>
<nil>
Example (Cron)

Two replicas fire on the same slot of a schedule: one runs the job.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/assanoff/skit/dedup"
)

func main() {
	k := dedup.NewMemory() // NewRedis in production: the replicas share it
	ctx := context.Background()

	// time.Now().UTC().Truncate(time.Minute) on every replica.
	slot := time.Date(2026, 11, 1, 9, 30, 0, 0, time.UTC)
	key := "daily-report/" + slot.Format(time.RFC3339)
	for _, replica := range []string{"a", "b"} {
		_, err := k.Do(ctx, key, func(context.Context) (struct{}, error) {
			fmt.Println("replica", replica, "runs the report")
			return struct{}{}, nil
		})
		if errors.Is(err, dedup.ErrInProgress) {
			continue // another replica runs it now
		}
		if err != nil {
			fmt.Println(err)
		}
	}
}
Output:
replica a runs the report
Example (Http)

A retry of a POST with the same Idempotency-Key gets the same status and body, and the order is created once.

package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/assanoff/skit/dedup"
)

// response is what an idempotent HTTP handler stores: a retry gets it back.
type response struct {
	Status int    `json:"status"`
	Type   string `json:"type"`
	Body   []byte `json:"body"`
}

// errServerError marks a response that is not stored: a retry runs the
// handler again.
var errServerError = errors.New("server error")

// idempotent runs next once per Idempotency-Key of the caller.
func idempotent(k *dedup.Keeper, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		key := r.Header.Get("Idempotency-Key")
		if key == "" {
			next.ServeHTTP(w, r)
			return
		}
		subject := r.Header.Get("X-Subject")
		resp, err := k.Do(r.Context(), subject+"/"+key, func(ctx context.Context) (response, error) {
			rec := httptest.NewRecorder()
			next.ServeHTTP(rec, r.WithContext(ctx))
			resp := response{
				Status: rec.Code,
				Type:   rec.Header().Get("Content-Type"),
				Body:   rec.Body.Bytes(),
			}
			if rec.Code >= http.StatusInternalServerError {
				return resp, errServerError
			}
			return resp, nil
		})
		switch {
		case errors.Is(err, dedup.ErrInProgress):
			w.Header().Set("Retry-After", "1")
			http.Error(w, "the request is in progress", http.StatusConflict)
			return
		case errors.Is(err, dedup.ErrUnavailable):
			http.Error(w, "try again later", http.StatusServiceUnavailable)
			return
		case err != nil && !errors.Is(err, errServerError):
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", resp.Type)
		w.WriteHeader(resp.Status)
		_, _ = w.Write(resp.Body)
	})
}

func main() {
	k := dedup.NewMemory()
	orders := 0
	create := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		orders++
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		fmt.Fprintf(w, `{"id":%d}`, orders)
	})
	h := idempotent(k, create)

	for range 2 {
		r := httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader("{}"))
		r.Header.Set("X-Subject", "user-7")
		r.Header.Set("Idempotency-Key", "8e0f")
		w := httptest.NewRecorder()
		h.ServeHTTP(w, r)
		fmt.Println(w.Code, w.Body.String())
	}
	fmt.Println("orders:", orders)
}
Output:
201 {"id":1}
201 {"id":1}
orders: 1

type Option

type Option func(*options)

Option customizes a Keeper.

func WithLease

func WithLease(d time.Duration) Option

WithLease sets the deadline of fn and the life of the record of a running call: a crashed holder blocks its key no longer than that. The default is 1m.

func WithTTL

func WithTTL(d time.Duration) Option

WithTTL sets how long the stored success of a key is handed to repeats, counted from its completion. The default is 24h.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL