Middleware

Introduction

Middleware wraps handlers with functionality that is important, but not relevant for the primary handler’s logic. Examples include retrying the handler after an error was returned, or recovering from a panic in the handler and capturing the stacktrace.

Middleware wraps the handler function like this:

// ...
// HandlerMiddleware allows us to write something like decorators to HandlerFunc.
// It can execute something before handler (for example: modify consumed message)
// or after (modify produced messages, ack/nack on consumed message, handle errors, logging, etc.).
//
// It can be attached to the router by using `AddMiddleware` method.
//
// Example:
//
//	func ExampleMiddleware(h message.HandlerFunc) message.HandlerFunc {
//		return func(message *message.Message) ([]*message.Message, error) {
//			fmt.Println("executed before handler")
//			producedMessages, err := h(message)
//			fmt.Println("executed after handler")
//
//			return producedMessages, err
//		}
//	}
type HandlerMiddleware func(h HandlerFunc) HandlerFunc
// ...

Full source: github.com/ThreeDotsLabs/watermill/message/router.go

Usage

Middleware can be executed for all as well as for a specific handler in a router. When middleware is added directly to a router it will be executed for all handlers provided for a router. If a middleware should be executed only for a specific handler, it needs to be added to handler in the router.

Example usage is shown below:

// ...
router, err := message.NewRouter(message.RouterConfig{}, logger)
if err != nil {
	panic(err)
}

// SignalsHandler will gracefully shutdown Router when SIGTERM is received.
// You can also close the router by just calling `r.Close()`.
router.AddPlugin(plugin.SignalsHandler)

// Router level middleware are executed for every message sent to the router
router.AddMiddleware(
	// CorrelationID will copy the correlation id from the incoming message's metadata to the produced messages
	middleware.CorrelationID,

	// The handler function is retried if it returns an error.
	// After MaxRetries, the message is Nacked and it's up to the PubSub to resend it.
	middleware.Retry{
		MaxRetries:      3,
		InitialInterval: time.Millisecond * 100,
		Logger:          logger,
	}.Middleware,

	// Recoverer handles panics from handlers.
	// In this case, it passes them as errors to the Retry middleware.
	middleware.Recoverer,
)

// For simplicity, we are using the gochannel Pub/Sub here,
// You can replace it with any Pub/Sub implementation, it will work the same.
pubSub := gochannel.NewGoChannel(gochannel.Config{}, logger)

// Producing some incoming messages in background
go publishMessages(pubSub)

// AddHandler returns a handler which can be used to add handler level middleware
// or to stop handler.
handler := router.AddHandler(
	"struct_handler",          // handler name, must be unique
	"incoming_messages_topic", // topic from which we will read events
	pubSub,
	"outgoing_messages_topic", // topic to which we will publish events
	pubSub,
	structHandler{}.Handler,
)

// Handler level middleware is only executed for a specific handler
// Such middleware can be added the same way the router level ones
handler.AddMiddleware(func(h message.HandlerFunc) message.HandlerFunc {
	return func(message *message.Message) ([]*message.Message, error) {
		log.Println("executing handler specific middleware for ", message.UUID)

		return h(message)
	}
})

// just for debug, we are printing all messages received on `incoming_messages_topic`
router.AddConsumerHandler(
	"print_incoming_messages",
	"incoming_messages_topic",
	pubSub,
	printMessages,
)

// just for debug, we are printing all events sent to `outgoing_messages_topic`
router.AddConsumerHandler(
	"print_outgoing_messages",
	"outgoing_messages_topic",
	pubSub,
	printMessages,
)

// Now that all handlers are registered, we're running the Router.
// Run is blocking while the router is running.
// ...

Full source: github.com/ThreeDotsLabs/watermill/_examples/basic/3-router/main.go

Available middleware

Below are the middleware provided by Watermill and ready to use. You can also easily implement your own. For example, if you’d like to store every received message in some kind of log, it’s the best way to do it.

Timeout

// Timeout makes the handler cancel the incoming message's context after a specified time.
// Any timeout-sensitive functionality of the handler should listen on msg.Context().Done() to know when to fail.
func Timeout(timeout time.Duration) func(message.HandlerFunc) message.HandlerFunc {
	return func(h message.HandlerFunc) message.HandlerFunc {
		return func(msg *message.Message) ([]*message.Message, error) {
			ctx, cancel := context.WithTimeout(msg.Context(), timeout)
			defer func() {
				cancel()
			}()

			msg.SetContext(ctx)
			return h(msg)
		}
	}
}

Retry Errors

// permanentErrorCause returns the error that err marks as permanent: wrapped with Permanent,
// or with the deprecated backoff.Permanent, which is logged as deprecated.
func permanentErrorCause(err error, logger watermill.LoggerAdapter) (cause error, ok bool) {
	var permanent *PermanentError
	if errors.As(err, &permanent) {
		return permanent.Err, true
	}

	if cause, ok := deprecatedBackoffPermanentError(err); ok {
		logDeprecatedBackoffError(logger, "PermanentError", "Permanent", err)
		return cause, true
	}

	return nil, false
}
// retryAfterDelay returns the delay that err asks for: with RetryAfter,
// or with the deprecated backoff.RetryAfterError, which is logged as deprecated.
func retryAfterDelay(err error, logger watermill.LoggerAdapter) (delay time.Duration, ok bool) {
	var retryAfter *RetryAfterError
	if errors.As(err, &retryAfter) {
		return retryAfter.Delay, true
	}

	if delay, ok := deprecatedBackoffRetryAfterDelay(err); ok {
		logDeprecatedBackoffError(logger, "RetryAfterError", "RetryAfter", err)
		return delay, true
	}

	return 0, false
}
// PermanentError is an error that the Retry middleware does not retry.
// Handlers create it with Permanent.
type PermanentError struct {
	Err error
}
// Permanent wraps err so that the Retry middleware returns it without retrying.
// The middleware returns err itself, without the PermanentError around it,
// and calls none of its hooks for it.
// It returns nil if err is nil.
func Permanent(err error) error {
	if err == nil {
		return nil
	}
	return &PermanentError{Err: err}
}
// RetryAfterError is an error after which the Retry middleware waits Delay before the next retry,
// instead of the next delay of its backoff. Handlers create it with RetryAfter.
type RetryAfterError struct {
	Err   error
	Delay time.Duration
}
// RetryAfter wraps err so that the Retry middleware waits delay before the next retry,
// for example the delay that a rate-limited API asked for.
// The backoff then starts again from InitialInterval.
// MaxRetries, MaxElapsedTime and ShouldRetry still apply, and ShouldRetry gets delay.
// It returns nil if err is nil.
func RetryAfter(err error, delay time.Duration) error {
	if err == nil {
		return nil
	}
	return &RetryAfterError{Err: err, Delay: delay}
}

Recoverer

// RecoveredPanicError holds the recovered panic's error along with the stacktrace.
type RecoveredPanicError struct {
	V          interface{}
	Stacktrace string
}
// Recoverer recovers from any panic in the handler and appends RecoveredPanicError with the stacktrace
// to any error returned from the handler.
func Recoverer(h message.HandlerFunc) message.HandlerFunc {
	return func(event *message.Message) (events []*message.Message, err error) {
		panicked := true

		defer func() {
			if r := recover(); r != nil || panicked {
				err = errors.WithStack(RecoveredPanicError{V: r, Stacktrace: string(debug.Stack())})
			}
		}()

		events, err = h(event)
		panicked = false
		return events, err
	}
}

Retry

// RetryParams holds the parameters for a retry attempt
type RetryParams struct {
	// Err is the error that caused the retry attempt.
	Err error
	// RetryNum is the number of the retry attempt, starting from 1.
	RetryNum int
	// Delay is the delay for the next retry attempt.
	Delay time.Duration
}
// RetriesExhaustedParams holds the parameters passed to OnRetriesExhausted.
type RetriesExhaustedParams struct {
	// Err is the last error returned by the handler before retries were exhausted.
	Err error
	// RetryNum is the total number of attempts performed (1 initial + MaxRetries retries).
	// For MaxRetries=N this will equal N+1.
	RetryNum int
}
// Retry provides a middleware that retries the handler if errors are returned.
// The retry behaviour is configurable, with exponential backoff and maximum elapsed time.
//
// A handler can return an error wrapped with Permanent to stop the retries,
// or with RetryAfter to choose the delay before the next retry.
//
// The error types of github.com/cenkalti/backoff/v5, which this middleware used before,
// still work the same way: a handler can return backoff.Permanent(err) or a *backoff.RetryAfterError.
// This is deprecated; use Permanent and RetryAfter instead.
// The middleware logs an error each time a handler returns one of them.
type Retry struct {
	// MaxRetries is maximum number of times a retry will be attempted.
	// If negative, the number of retries is not limited.
	MaxRetries int

	// InitialInterval is the first interval between retries. Subsequent intervals will be scaled by Multiplier.
	InitialInterval time.Duration
	// MaxInterval sets the limit for the exponential backoff of retries. The interval will not be increased beyond MaxInterval.
	// If 0, the interval is not increased: every interval is InitialInterval.
	MaxInterval time.Duration
	// Multiplier is the factor by which the waiting interval will be multiplied between retries.
	// If 0, the interval is not increased: every interval is InitialInterval.
	Multiplier float64
	// MaxElapsedTime sets the time limit of how long retries will be attempted. Disabled if 0.
	MaxElapsedTime time.Duration
	// RandomizationFactor randomizes the spread of the backoff times within the interval of:
	// [currentInterval * (1 - RandomizationFactor), currentInterval * (1 + RandomizationFactor)].
	RandomizationFactor float64

	// OnRetryHook is an optional function that will be executed on each retry attempt.
	// The number of the current retry is passed as retryNum,
	OnRetryHook func(retryNum int, delay time.Duration)

	// OnRetriesExhausted is an optional function that will be executed when all retries are exhausted.
	// This is called when MaxRetries or MaxElapsedTime is reached and the handler still returns an error,
	// and when the message's context is canceled before the handler succeeded.
	// It is NOT called when ShouldRetry returns false.
	OnRetriesExhausted func(params RetriesExhaustedParams)

	// ShouldRetry is an optional function that will be executed before each retry attempt.
	// If ShouldRetry returns false, the retry will not be attempted.
	ShouldRetry func(params RetryParams) bool

	// ResetContextOnRetry indicates whether the message context should be reset on each retry attempt.
	// See more: https://github.com/ThreeDotsLabs/watermill/issues/467
	//
	// This is not enabled by default to keep backward compatibility
	// (in theory, someone may want to preserve context values between retries).
	ResetContextOnRetry bool

	Logger watermill.LoggerAdapter
}
// Middleware returns the Retry middleware.
func (r Retry) Middleware(h message.HandlerFunc) message.HandlerFunc {
	return func(msg *message.Message) ([]*message.Message, error) {
		ctx := msg.Context()
		startedAt := time.Now()

		delays := newExponentialBackoff(r)

		// retriesDone is the number of retries already made, 0 during the first attempt.
		retriesDone := 0
		// waited is the delay waited before the current attempt, 0 for the first one.
		var waited time.Duration

		// attempts includes the first attempt, so it is MaxRetries + 1 when the retries ran out.
		exhausted := func(producedMessages []*message.Message, err error, attempts int) ([]*message.Message, error) {
			if r.OnRetriesExhausted != nil {
				r.OnRetriesExhausted(RetriesExhaustedParams{
					Err:      err,
					RetryNum: attempts,
				})
			}
			return producedMessages, err
		}

		for {
			if ctx.Err() != nil {
				return exhausted(nil, context.Cause(ctx), retriesDone)
			}

			if r.ResetContextOnRetry {
				// message is passed as a pointer, so its context can be canceled
				// by the previous attempts -> it will break retries, because any
				// underlying logic that relies on the context will fail.
				// see more: https://github.com/ThreeDotsLabs/watermill/issues/467
				//
				// to avoid this, we need to reset the original context on each attempt
				// we may lose context value that was set by the previous attempt
				msg.SetContext(ctx)
			}

			producedMessages, err := h(msg)
			if err == nil {
				return producedMessages, nil
			}

			if cause, ok := permanentErrorCause(err, r.Logger); ok {
				return producedMessages, cause
			}

			if r.OnRetryHook != nil && retriesDone > 0 {
				r.OnRetryHook(retriesDone, waited)
			}

			// next advances the backoff, so it is called at most once per attempt:
			// this delay is given to ShouldRetry and then waited.
			var delay time.Duration
			if retryAfter, ok := retryAfterDelay(err, r.Logger); ok {
				delay = retryAfter
				delays.reset()
			} else {
				delay = delays.next()
			}

			nextRetry := retriesDone + 1

			// a negative MaxRetries means no limit
			if r.MaxRetries >= 0 && nextRetry > r.MaxRetries {
				return exhausted(producedMessages, err, retriesDone+1)
			}
			if r.MaxElapsedTime > 0 && time.Since(startedAt)+delay > r.MaxElapsedTime {
				return exhausted(producedMessages, err, retriesDone+1)
			}
			if ctx.Err() != nil {
				return exhausted(producedMessages, context.Cause(ctx), retriesDone+1)
			}

			if r.ShouldRetry != nil && !r.ShouldRetry(RetryParams{
				RetryNum: nextRetry,
				Err:      err,
				Delay:    delay,
			}) {
				return producedMessages, err
			}

			if r.Logger != nil {
				r.Logger.Error("Error occurred, retrying", err, watermill.LogFields{
					"retry_no":    nextRetry,
					"max_retries": r.MaxRetries,
					"wait_time":   delay,
				})
			}

			timer := time.NewTimer(delay)
			select {
			case <-timer.C:
			case <-ctx.Done():
				timer.Stop()
				return exhausted(producedMessages, context.Cause(ctx), retriesDone+1)
			}

			retriesDone = nextRetry
			waited = delay
		}
	}
}

Instant Ack

// InstantAck makes the handler instantly acknowledge the incoming message, regardless of any errors.
// It may be used to gain throughput, but at a cost:
// If you had exactly-once delivery, you may expect at-least-once instead.
// If you had ordered messages, the ordering might be broken.
func InstantAck(h message.HandlerFunc) message.HandlerFunc {
	return func(message *message.Message) ([]*message.Message, error) {
		message.Ack()
		return h(message)
	}
}

Randomfail

// RandomFail makes the handler fail with an error based on random chance. Error probability should be in the range (0,1).
func RandomFail(errorProbability float32) message.HandlerMiddleware {
	return func(h message.HandlerFunc) message.HandlerFunc {
		return func(message *message.Message) ([]*message.Message, error) {
			if shouldFail(errorProbability) {
				return nil, errors.New("random fail occurred")
			}

			return h(message)
		}
	}
}
// RandomPanic makes the handler panic based on random chance. Panic probability should be in the range (0,1).
func RandomPanic(panicProbability float32) message.HandlerMiddleware {
	return func(h message.HandlerFunc) message.HandlerFunc {
		return func(message *message.Message) ([]*message.Message, error) {
			if shouldFail(panicProbability) {
				panic("random panic occurred")
			}

			return h(message)
		}
	}
}

Ignore Errors

// IgnoreErrors provides a middleware that makes the handler ignore some explicitly whitelisted errors.
type IgnoreErrors struct {
	ignoredErrors map[string]struct{}
}
// NewIgnoreErrors creates a new IgnoreErrors middleware.
func NewIgnoreErrors(errs []error) IgnoreErrors {
	errsMap := make(map[string]struct{}, len(errs))

	for _, err := range errs {
		errsMap[err.Error()] = struct{}{}
	}

	return IgnoreErrors{errsMap}
}
// Middleware returns the IgnoreErrors middleware.
func (i IgnoreErrors) Middleware(h message.HandlerFunc) message.HandlerFunc {
	return func(msg *message.Message) ([]*message.Message, error) {
		events, err := h(msg)
		if err != nil {
			if _, ok := i.ignoredErrors[errors.Cause(err).Error()]; ok {
				return events, nil
			}

			return events, err
		}

		return events, nil
	}
}

Deduplicator

// Deduplicator drops similar messages if they are present
// in a [ExpiringKeyRepository]. The similarity is determined
// by a [MessageHasher]. Time out is applied to repository
// operations using [context.WithTimeout].
//
// Call [Deduplicator.Middleware] for a new middleware
// or [Deduplicator.Decorator] for a [message.PublisherDecorator].
//
// KeyFactory defaults to [NewMessageHasherAdler32] with read
// limit  set to [math.MaxInt64] for fast tagging.
// Use [NewMessageHasherSHA256] for minimal collisions.
//
// Repository defaults to [NewMapExpiringKeyRepository] with one
// minute retention window. This default setting is performant
// but **does not support distributed operations**. If you
// implement a [ExpiringKeyRepository] backed by Redis,
// please submit a pull request.
//
// Timeout defaults to one minute. If lower than
// five milliseconds, it is set to five milliseconds.
//
// [ExpiringKeyRepository] must expire values
// in a certain time window. If there is no expiration, only one
// unique message will be ever delivered as long as the repository
// keeps its state.
type Deduplicator struct {
	KeyFactory MessageHasher
	Repository ExpiringKeyRepository
	Timeout    time.Duration
}
// IsDuplicate returns true if the message hash tag calculated
// using a [MessageHasher] was seen in deduplication time window.
func (d *Deduplicator) IsDuplicate(m *message.Message) (bool, error) {
	key, err := d.KeyFactory(m)
	if err != nil {
		return false, err
	}
	ctx, cancel := context.WithTimeout(m.Context(), d.Timeout)
	defer cancel()
	return d.Repository.IsDuplicate(ctx, key)
}
// Middleware returns the [message.HandlerMiddleware]
// that drops similar messages in a given time window.
func (d *Deduplicator) Middleware(h message.HandlerFunc) message.HandlerFunc {
	d = applyDefaultsToDeduplicator(d)
	return func(msg *message.Message) ([]*message.Message, error) {
		isDuplicate, err := d.IsDuplicate(msg)
		if err != nil {
			return nil, err
		}
		if isDuplicate {
			return nil, nil
		}
		return h(msg)
	}
}
// NewMapExpiringKeyRepository returns a memory store
// backed by a regular hash map protected by
// a [sync.Mutex]. The state **cannot be shared or synchronized
// between instances** by design for performance.
//
// If you need to drop duplicate messages by orchestration,
// implement [ExpiringKeyRepository] interface backed by Redis
// or similar.
//
// Window specifies the minimum duration of how long the
// duplicate tags are remembered for. Real duration can
// extend up to 50% longer because it depends on the
// clean up cycle.
func NewMapExpiringKeyRepository(window time.Duration) (ExpiringKeyRepository, error) {
	if window < time.Millisecond {
		return nil, errors.New("deduplication window of less than a millisecond is impractical")
	}

	kr := &mapExpiringKeyRepository{
		window: window,
		mu:     &sync.Mutex{},
		tags:   make(map[string]time.Time),
	}
	ticker := time.NewTicker(window / 2)

	go kr.cleanOutLoop(context.Background(), ticker)
	return kr, nil
}
// Len returns the number of known tags that have not been
// cleaned out yet.
func (kr *mapExpiringKeyRepository) Len() (count int) {
	kr.mu.Lock()
	count = len(kr.tags)
	kr.mu.Unlock()
	return
}
// NewMessageHasherAdler32 generates message hashes using a fast
// Adler-32 checksum of the [message.Message] body. Read
// limit specifies how many bytes of the message are
// used for calculating the hash.
//
// Lower limit improves performance but results in more false
// positives. Read limit must be greater than
// [MessageHasherReadLimitMinimum].
func NewMessageHasherAdler32(readLimit int64) MessageHasher {
	if readLimit < MessageHasherReadLimitMinimum {
		readLimit = MessageHasherReadLimitMinimum
	}
	return func(m *message.Message) (string, error) {
		h := adler32.New()
		_, err := io.CopyN(h, bytes.NewReader(m.Payload), readLimit)
		if err != nil && err != io.EOF {
			return "", err
		}
		return string(h.Sum(nil)), nil
	}
}
// NewMessageHasherSHA256 generates message hashes using a slower
// but more resilient hashing of the [message.Message] body. Read
// limit specifies how many bytes of the message are
// used for calculating the hash.
//
// Lower limit improves performance but results in more false
// positives. Read limit must be greater than
// [MessageHasherReadLimitMinimum].
func NewMessageHasherSHA256(readLimit int64) MessageHasher {
	if readLimit < MessageHasherReadLimitMinimum {
		readLimit = MessageHasherReadLimitMinimum
	}

	return func(m *message.Message) (string, error) {
		h := sha256.New()
		_, err := io.CopyN(h, bytes.NewReader(m.Payload), readLimit)
		if err != nil && err != io.EOF {
			return "", err
		}
		return string(h.Sum(nil)), nil
	}
}
// NewMessageHasherFromMetadataField looks for a hash value
// inside message metadata instead of calculating a new one.
// Useful if a [MessageHasher] was applied in a previous
// [message.HandlerFunc].
func NewMessageHasherFromMetadataField(field string) MessageHasher {
	return func(m *message.Message) (string, error) {
		fromMetadata, ok := m.Metadata[field]
		if ok {
			return fromMetadata, nil
		}
		return "", fmt.Errorf("cannot recover hash value from metadata of message #%s: field %q is absent", m.UUID, field)
	}
}
// PublisherDecorator returns a decorator that
// acknowledges and drops every [message.Message] that
// was recognized by a [Deduplicator].
//
// The returned decorator provides the same functionality
// to a [message.Publisher] as [Deduplicator.Middleware]
// to a [message.Router].
func (d *Deduplicator) PublisherDecorator() message.PublisherDecorator {
	return func(pub message.Publisher) (message.Publisher, error) {
		if pub == nil {
			return nil, errors.New("cannot decorate a <nil> publisher")
		}

		return &deduplicatingPublisherDecorator{
			Publisher:    pub,
			deduplicator: applyDefaultsToDeduplicator(d),
		}, nil
	}
}

Delay On Error

// DelayOnError is a middleware that adds the delay metadata to the message if an error occurs.
//
// IMPORTANT: The delay metadata doesn't cause delays with all Pub/Subs! Using it won't have any effect on Pub/Subs that don't support it.
// See the list of supported Pub/Subs in the documentation: https://watermill.io/advanced/delayed-messages/
type DelayOnError struct {
	// InitialInterval is the first interval between retries. Subsequent intervals will be scaled by Multiplier.
	InitialInterval time.Duration
	// MaxInterval sets the limit for the exponential backoff of retries. The interval will not be increased beyond MaxInterval.
	MaxInterval time.Duration
	// Multiplier is the factor by which the waiting interval will be multiplied between retries.
	Multiplier float64
}

Throttle

// Throttle provides a middleware that limits the amount of messages processed per unit of time.
// This may be done e.g. to prevent excessive load caused by running a handler on a long queue of unprocessed messages.
type Throttle struct {
	ticker *time.Ticker
}
// NewThrottle creates a new Throttle middleware.
// Example duration and count: NewThrottle(10, time.Second) for 10 messages per second
func NewThrottle(count int64, duration time.Duration) *Throttle {
	return &Throttle{
		ticker: time.NewTicker(duration / time.Duration(count)),
	}
}
// Middleware returns the Throttle middleware.
func (t Throttle) Middleware(h message.HandlerFunc) message.HandlerFunc {
	return func(message *message.Message) ([]*message.Message, error) {
		// throttle is shared by multiple handlers, which will wait for their "tick"
		<-t.ticker.C

		return h(message)
	}
}

Retry Backoff

// exponentialBackoff computes the delays between retries.
//
// It computes the same delays as ExponentialBackOff from github.com/cenkalti/backoff/v5,
// which the Retry middleware used before, so existing configurations keep their waits.
// That includes zero values: with MaxInterval or Multiplier 0, every delay is InitialInterval.
type exponentialBackoff struct {
	initialInterval     time.Duration
	maxInterval         time.Duration
	multiplier          float64
	randomizationFactor float64

	// random returns a number from [0, 1).
	random func() float64

	// currentInterval is the delay before randomization; 0 means InitialInterval.
	currentInterval time.Duration
}
// next returns the delay before the next retry and advances the backoff.
// Each call returns the following delay, so it must be called once per retry.
func (b *exponentialBackoff) next() time.Duration {
	if b.currentInterval == 0 {
		b.currentInterval = b.initialInterval
	}

	delay := randomizeInterval(b.currentInterval, b.randomizationFactor, b.random())
	b.currentInterval = b.grow(b.currentInterval)

	return delay
}
// reset makes the next delay start again from initialInterval.
func (b *exponentialBackoff) reset() {
	b.currentInterval = 0
}
// grow returns interval multiplied by multiplier, but not more than maxInterval.
//
// With maxInterval 0, the result is 0. With multiplier 0, interval*multiplier is 0.
// next then starts again from initialInterval, so the delays do not grow.
func (b *exponentialBackoff) grow(interval time.Duration) time.Duration {
	// compared before multiplying, so that the multiplication cannot overflow
	if float64(interval) >= float64(b.maxInterval)/b.multiplier {
		return b.maxInterval
	}
	return time.Duration(float64(interval) * b.multiplier)
}
// randomizeInterval returns a value from [interval - factor*interval, interval + factor*interval],
// chosen by random, a number from [0, 1).
func randomizeInterval(interval time.Duration, factor float64, random float64) time.Duration {
	if factor == 0 {
		return interval
	}

	delta := factor * float64(interval)
	minInterval := float64(interval) - delta
	maxInterval := float64(interval) + delta

	// +1, so that maxInterval can be chosen as well
	return time.Duration(minInterval + random*(maxInterval-minInterval+1))
}

Circuit Breaker

// CircuitBreaker is a middleware that wraps the handler in a circuit breaker.
// Based on the configuration, the circuit breaker will fail fast if the handler keeps returning errors.
// This is useful for preventing cascading failures.
type CircuitBreaker struct {
	cb *gobreaker.CircuitBreaker
}
// NewCircuitBreaker returns a new CircuitBreaker middleware.
// Refer to the gobreaker documentation for the available settings.
func NewCircuitBreaker(settings gobreaker.Settings) CircuitBreaker {
	return CircuitBreaker{
		cb: gobreaker.NewCircuitBreaker(settings),
	}
}
// Middleware returns the CircuitBreaker middleware.
func (c CircuitBreaker) Middleware(h message.HandlerFunc) message.HandlerFunc {
	return func(msg *message.Message) ([]*message.Message, error) {
		out, err := c.cb.Execute(func() (interface{}, error) {
			return h(msg)
		})

		var result []*message.Message
		if out != nil {
			result = out.([]*message.Message)
		}

		return result, err
	}
}

Duplicator

// Duplicator is processing messages twice, to ensure that the endpoint is idempotent.
func Duplicator(h message.HandlerFunc) message.HandlerFunc {
	return func(msg *message.Message) ([]*message.Message, error) {
		firstProducedMessages, firstErr := h(msg)
		if firstErr != nil {
			return nil, firstErr
		}

		secondProducedMessages, secondErr := h(msg)
		if secondErr != nil {
			return nil, secondErr
		}

		return append(firstProducedMessages, secondProducedMessages...), nil
	}
}

Retry Deprecated Backoff Errors

// logDeprecatedBackoffError logs that a handler returned a deprecated backoff error.
// It logs at the Error level, as watermill.LoggerAdapter has no warning level.
func logDeprecatedBackoffError(logger watermill.LoggerAdapter, typeName string, replacement string, err error) {
	if logger == nil {
		return
	}
	logger.Error(
		"Deprecation warning: handler returned backoff."+typeName+", which is deprecated in the Retry middleware, use middleware."+replacement+" instead",
		err,
		nil,
	)
}
// deprecatedBackoffPermanentError returns the error wrapped by a *backoff.PermanentError in err's chain.
func deprecatedBackoffPermanentError(err error) (wrapped error, ok bool) {
	found := findDeprecatedBackoffError(err, "PermanentError")
	if found == nil {
		return nil, false
	}

	unwrapper, ok := found.(interface{ Unwrap() error })
	if !ok {
		return nil, false
	}
	return unwrapper.Unwrap(), true
}
// deprecatedBackoffRetryAfterDelay returns the Duration of a *backoff.RetryAfterError in err's chain.
func deprecatedBackoffRetryAfterDelay(err error) (delay time.Duration, ok bool) {
	found := findDeprecatedBackoffError(err, "RetryAfterError")
	if found == nil {
		return 0, false
	}

	field := reflect.ValueOf(found).Elem().FieldByName("Duration")
	if !field.IsValid() || field.Type() != reflect.TypeFor[time.Duration]() {
		return 0, false
	}
	return time.Duration(field.Int()), true
}
// findDeprecatedBackoffError returns the first error in err's chain, in the order errors.As uses,
// that is a pointer to typeName from the backoff package.
func findDeprecatedBackoffError(err error, typeName string) error {
	for err != nil {
		if isDeprecatedBackoffError(err, typeName) {
			return err
		}

		switch e := err.(type) {
		case interface{ Unwrap() error }:
			err = e.Unwrap()
		case interface{ Unwrap() []error }:
			for _, joined := range e.Unwrap() {
				if found := findDeprecatedBackoffError(joined, typeName); found != nil {
					return found
				}
			}
			return nil
		default:
			return nil
		}
	}
	return nil
}
// isDeprecatedBackoffError reports whether err is a pointer to typeName from the deprecated backoff package.
func isDeprecatedBackoffError(err error, typeName string) bool {
	t := reflect.TypeOf(err)
	return t.Kind() == reflect.Pointer &&
		t.Elem().PkgPath() == deprecatedBackoffPkgPath &&
		t.Elem().Name() == typeName
}

Poison

// PoisonQueue provides a middleware that salvages unprocessable messages and publishes them on a separate topic.
// The main middleware chain then continues on, business as usual.
func PoisonQueue(pub message.Publisher, topic string) (message.HandlerMiddleware, error) {
	if topic == "" {
		return nil, ErrInvalidPoisonQueueTopic
	}

	pq := poisonQueue{
		topic: topic,
		pub:   pub,
		shouldGoToPoisonQueue: func(err error) bool {
			return true
		},
	}

	return pq.Middleware, nil
}
// PoisonQueueWithFilter is just like PoisonQueue, but accepts a function that decides which errors qualify for the poison queue.
func PoisonQueueWithFilter(pub message.Publisher, topic string, shouldGoToPoisonQueue func(err error) bool) (message.HandlerMiddleware, error) {
	if topic == "" {
		return nil, ErrInvalidPoisonQueueTopic
	}

	pq := poisonQueue{
		topic: topic,
		pub:   pub,

		shouldGoToPoisonQueue: shouldGoToPoisonQueue,
	}

	return pq.Middleware, nil
}

Correlation

// SetCorrelationID sets a correlation ID for the message.
//
// SetCorrelationID should be called when the message enters the system.
// When message is produced in a request (for example HTTP),
// message correlation ID should be the same as the request's correlation ID.
func SetCorrelationID(id string, msg *message.Message) {
	if MessageCorrelationID(msg) != "" {
		return
	}

	msg.Metadata.Set(CorrelationIDMetadataKey, id)
}
// MessageCorrelationID returns correlation ID from the message.
func MessageCorrelationID(message *message.Message) string {
	return message.Metadata.Get(CorrelationIDMetadataKey)
}
// CorrelationID adds correlation ID to all messages produced by the handler.
// ID is based on ID from message received by handler.
//
// To make CorrelationID working correctly, SetCorrelationID must be called to first message entering the system.
func CorrelationID(h message.HandlerFunc) message.HandlerFunc {
	return func(message *message.Message) ([]*message.Message, error) {
		producedMessages, err := h(message)

		correlationID := MessageCorrelationID(message)
		for _, msg := range producedMessages {
			SetCorrelationID(correlationID, msg)
		}

		return producedMessages, err
	}
}

Check our online hands-on training