Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions kafka/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# Kafka

Consumer processing failures are classified by the application. The SDK controls
retry timing, offset commits, and confirmed dead-letter publication.

## Processing policy

`ConsumerOptions.RetryPolicy` is optional. With no policy, the consumer allows
three retries with jittered exponential backoff under a ten-second total budget,
then returns an error wrapping `ErrConsumerPaused`. The failed record and later
unprocessed records are not committed. Earlier successful records may commit.

A non-nil policy uses `MaxRetries` literally: zero means no retries. Backoff and
elapsed-time fields default when zero. Handlers must honor their context.

| Classification | Behavior |
| --- | --- |
| `UnknownFailure` (default) | Bounded retries, then stop and preserve input; never automatically DLQ |
| `RetryableFailure` | Bounded retries, then stop; park only with explicit `OnExhausted: DeadLetter` |
| `PermanentFailure` | Skip retries; park if configured, otherwise stop and preserve input |
| `DependencyUnavailable` | Stop immediately; optional recovery probes gate a fresh consumer |
| `ConfigurationFailure` | Stop immediately for operator intervention |

Use `errors.Is` or typed errors to classify application failures. Do not classify
by matching error-message text. Shutdown cancellation bypasses classification and
leaves unfinished work uncommitted. `ProcessingError` exposes `Kind`, `Attempts`
and the original wrapped error; the returned error also names the source topic,
partition and offset. Retry budgets and attempt metadata apply per invocation;
supervisors must not repeatedly restart unknown/configuration failures.

## Dead-letter topic configuration

A nil `DeadLetter` disables parking. Example for an existing topic:

```go
options := kafka.ConsumerOptions{
RetryPolicy: &kafka.RetryPolicy{
Classify: classifyApplicationError,
MaxRetries: 3,
MaxElapsedTime: 10 * time.Second,
OnExhausted: kafka.DeadLetter,
},
DeadLetter: &kafka.DeadLetterConfig{
Topic: "cards.failed",
Provision: kafka.UseExisting,
Partitions: 3,
ReplicationFactor: 3,
Configs: map[string]string{
"retention.ms": "604800000",
"retention.bytes": "1073741824",
"min.insync.replicas": "2",
},
},
}
```

`OnExhausted: DeadLetter` requires a configured destination, and only applies to
explicitly retryable errors. Unknown errors remain preserved even with a DLQ.

`UseExisting` checks topic existence and any specified partition, replication,
and topic-config requirements before polling. Zero partition/replication fields
in this mode mean no requirement. `Declare` creates the topic if absent and
requires explicit positive partitions/replication. Existing incompatible topics
cause startup failure rather than silent reconfiguration. Topic configuration
validation requires the relevant Kafka describe permissions. Provisioning needs
create permissions. If exactly one source topic is configured, an empty
configured destination name defaults to `<source>.dlq`.

The consumer's client must use `AllISRAcks` for DLQ writes and cannot be
transactional. Consumers require a group, must disable auto-commit and use
`BlockRebalanceOnPoll`; `NewKafkaClientFromConfig` configures those group options.
The SDK waits for synchronous publication before committing the original offset.
A failed publication returns `ErrDLQPublish` and preserves the input. Retention,
replication and ISR policy determine broker-side durability.

Payload, key and application headers are preserved. Reserved `fiddle.dlq.*`
headers hold source topic/partition/offset, classification, attempts and failure
time. Error metadata defaults to an error class/type; opt into sanitized details
with `DeadLetterConfig.ErrorFormatter`. A dead-letter topic must differ from
source topics. Redrive is explicit; the SDK never sends a DLQ back to its source.

## Recovery without consuming an outage backlog

`Start` returns on an outage, allowing the application to release the client.
Do not reuse a client that has fetched past a failed record. Use the same group
with a fresh client so broker-committed offsets determine redelivery.

```go
err := kafka.RunWithRecovery(ctx, kafka.RecoveryPolicy{
Probe: checkCardServiceHealth, // application dependency, not broker health
Interval: 30 * time.Second,
Timeout: 5 * time.Second,
}, func(ctx context.Context) error {
client, err := kafka.NewKafkaClientFromConfig(ctx, cfg)
if err != nil { return err }
defer client.Close()
err = kafka.NewConsumer(client, options).Start(ctx, handleCard)
// Record err here so the original cause is observable while probing.
return err
})
```

Only a classified dependency outage triggers probes. No consumer exists while
probing; a successful, timely probe permits one fresh consumer run. Unknown,
configuration, setup, and DLQ transfer failures return to the caller. The outer
context bounds recovery; probes must honor their contexts.

Delivery is at least once. A crash after DLQ publication but before offset commit
can create duplicates. Handlers and redrive tools must be idempotent.

## Migration and verification

Previously, exhausted failures could be committed with no DLQ. They now stop.
`DLQProducer` is deprecated and rejected at startup; use `DeadLetterConfig` so the
SDK can verify topology, acknowledgements and metadata. The standalone
`Producer.SendToDLQ` convenience method also requires `AllISRAcks`.

Run `make check` from this module with Go 1.27.2 and the configured lint tools.
Unit tests use fake broker-operation interfaces. The optional broker test verifies
that a fresh consumer redelivers a failed record after earlier offsets commit:

```sh
FIDDLE_KAFKA_BROKERS=localhost:9092 go test -run TestIntegration -count=1 -timeout 60s
```

Use a disposable plaintext cluster: the test creates/deletes a uniquely named
topic; the unique consumer group follows broker offset retention. Without the
environment variable it is skipped. No
Docker orchestration is needed by the test suite.
26 changes: 26 additions & 0 deletions kafka/adr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Processing failures and dead-letter delivery

Status: implemented; executable verification pending the declared Go toolchain.

The application classifies business failures; the SDK owns retry budgets and
settlement. Unknown failures stop without committing. Dependency outages stop
immediately; an optional SDK recovery loop probes before constructing a fresh
consumer. Only permanent failures or explicitly configured retry exhaustion are
parked. This avoids moving an outage backlog into a DLQ.

Keep the existing Handler signature and add optional RetryPolicy/DeadLetterConfig.
Validate topic requirements before polling. Use the managed consumer's native
synchronous producer with AllISRAcks rather than an arbitrary DLQ producer whose
acknowledgement and metadata behavior cannot be verified. Reject automatic group
offset commits, which could advance past failures. Preserve the original cause
and record location for application observability.

Use franz-go/kadm's topic APIs for provisioning and validation. Existing topics
are not silently altered. Kafka partition/replication/retention settings remain
explicit operational choices. Do not add a shared policy module dependency to
this standalone multi-module repository; RabbitMQ has the same policy contract.

At-least-once semantics permit duplicate processing or parking after a crash.
Fresh-client recovery uses broker-committed offsets. Caller-owned resources must
be closed before entering the probe loop. Budgets are per run, and user callbacks
must respect context deadlines. Unknown errors never authorize deletion.
7 changes: 4 additions & 3 deletions kafka/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ type Producer interface {
// handler can stop on shutdown. With Config.EnableOTel it also carries the
// record's receive span, so spans started from it join the producer's trace.
//
// A non-nil error is retried (ConsumerOptions.MaxRetries) and then sent to the
// DLQ. The record's dlq_error header holds the error's class or type, not its
// message (see WithDLQClass and WithDLQErrorFormatter).
// RetryPolicy classifies a non-nil error. Unknown errors have a bounded retry
// budget and then stop consumption without advancing offsets. Permanent errors
// can be parked through DeadLetterConfig; dependency outages stop immediately.
// DLQ error text is opt-in through DeadLetterConfig.ErrorFormatter.
type Handler func(ctx context.Context, record *kgo.Record) error

// Consumer consumes messages from Kafka topics.
Expand Down
154 changes: 79 additions & 75 deletions kafka/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,31 @@ const commitTimeout = 10 * time.Second

// ConsumerOptions configures consumer behavior.
type ConsumerOptions struct {
// RetryPolicy is optional. An explicit policy overrides legacy retry fields.
RetryPolicy *RetryPolicy
DeadLetter *DeadLetterConfig
// Deprecated: configure DeadLetter instead. Setting DLQProducer is rejected
// before consumption because its topology and write guarantees are unknown.
DLQProducer Producer
OnDLQPublish func(topic string, err error)
MaxRetries int
RetryBackoff time.Duration
Logger *slog.Logger
}

// recordIO captures the broker operations that settle one poll.
type recordIO interface {
CommitRecords(context.Context, ...*kgo.Record) error
ProduceSync(context.Context, ...*kgo.Record) kgo.ProduceResults
}

// consumer implements the Consumer interface.
type consumer struct {
client *kgo.Client
records recordIO
options ConsumerOptions
policy RetryPolicy
initErr error
}

// NewConsumer creates a new Consumer with the given client and options.
Expand All @@ -46,10 +60,31 @@ func NewConsumer(client *kgo.Client, opts ...ConsumerOptions) Consumer {
if o.Logger != nil {
options.Logger = o.Logger
}
if o.RetryPolicy != nil {
options.RetryPolicy = o.RetryPolicy
}
if o.DeadLetter != nil {
options.DeadLetter = o.DeadLetter
}
options.DLQProducer = o.DLQProducer
options.OnDLQPublish = o.OnDLQPublish
}
return &consumer{client: client, options: options}
var topics []string
if client != nil {
topics, _ = client.OptValue(kgo.ConsumeTopics).([]string)
}
options.DeadLetter = options.DeadLetter.normalized(topics)
policy := options.RetryPolicy.normalized()
if options.RetryPolicy == nil {
policy.MaxRetries = options.MaxRetries
policy.InitialBackoff = options.RetryBackoff
policy.MaxBackoff = max(policy.MaxBackoff, policy.InitialBackoff)
}
initErr := errors.Join(policy.validate(options.DeadLetter != nil), options.DeadLetter.validate(topics))
if options.DLQProducer != nil {
initErr = errors.Join(initErr, errors.New("DLQProducer is deprecated; configure DeadLetter instead"))
}
return &consumer{client: client, records: client, options: options, policy: policy, initErr: initErr}
}

// Start begins consuming messages and processing them with the handler.
Expand All @@ -58,11 +93,30 @@ func NewConsumer(client *kgo.Client, opts ...ConsumerOptions) Consumer {
// Offsets of processed records are committed once per poll, so records still in
// flight at shutdown are redelivered on restart (at-least-once).
//
// If publishing a failed record to the DLQ fails, Start returns an error
// wrapping ErrDLQPublish without committing that record or any later one. The
// If processing stops or publishing to the DLQ fails, Start returns an error
// without committing that record or any later one. DLQ failures wrap ErrDLQPublish. The
// client has already fetched past them, so close it and create a new one to have
// them redelivered.
func (c *consumer) Start(ctx context.Context, handler Handler) error {
if c.initErr != nil {
return c.initErr
}
if c.client == nil || handler == nil {
return errors.New("consumer requires a client and handler")
}
if group, _ := c.client.OptValue(kgo.ConsumerGroup).(string); group == "" {
return errors.New("reliable consumption requires a consumer group")
} else {
if disabled, _ := c.client.OptValue(kgo.DisableAutoCommit).(bool); !disabled {
return errors.New("consumer requires DisableAutoCommit")
}
if blocked, _ := c.client.OptValue(kgo.BlockRebalanceOnPoll).(bool); !blocked {
return errors.New("consumer requires BlockRebalanceOnPoll")
}
}
if err := prepareDeadLetter(ctx, c.client, c.options.DeadLetter); err != nil {
return fmt.Errorf("prepare dead-letter topic: %w", err)
}
for {
if err := ctx.Err(); err != nil {
return err
Expand All @@ -88,11 +142,14 @@ func (c *consumer) Start(ctx context.Context, handler Handler) error {
func (c *consumer) processFetches(ctx context.Context, fetches kgo.Fetches, handler Handler) error {
logger := c.options.Logger

// A fetch error on one partition must not drop records fetched from healthy ones.
// Process healthy partitions before returning fetch errors; never busy-loop
// on a persistent broker/authorization failure.
var fetchErr error
fetches.EachError(func(topic string, partition int32, err error) {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
fetchErr = errors.Join(fetchErr, fmt.Errorf("fetch topic %s partition %d: %w", topic, partition, err))
logger.Error("fetch error", "topic", topic, "partition", partition, "error", err)
})

Expand All @@ -114,87 +171,34 @@ func (c *consumer) processFetches(ctx context.Context, fetches kgo.Fetches, hand
// redeliver records that were already handled.
commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), commitTimeout)
defer cancel()
if err := c.client.CommitRecords(commitCtx, processed...); err != nil {
logger.Error("commit error", "error", err)
if err := c.records.CommitRecords(commitCtx, processed...); err != nil {
return errors.Join(procErr, fetchErr, fmt.Errorf("commit processed offsets: %w", err))
}
}

return procErr
return errors.Join(procErr, fetchErr)
}

// handleRecord runs handler with retries and routes a final failure to the DLQ.
// A non-nil error means the record must not be committed.
// handleRecord leaves all settlement to processFetches. A non-nil error
// stops the poll at this record; neither it nor later records are committed.
func (c *consumer) handleRecord(ctx context.Context, r *kgo.Record, handler Handler) error {
logger := c.options.Logger

var lastErr error
for attempt := 0; attempt <= c.options.MaxRetries; attempt++ {
if attempt > 0 {
backoff := time.Duration(attempt) * c.options.RetryBackoff
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff):
}
}

if lastErr = handler(recordContext(ctx, r), r); lastErr == nil {
return nil
}
// A handler that failed because Start's ctx was cancelled did not fail
// on its merits: neither retry it nor dead-letter the record. It stays
// uncommitted and is redelivered after restart.
if err := ctx.Err(); err != nil {
return err
}
logger.Warn("handler error, retrying",
"topic", r.Topic,
"partition", r.Partition,
"offset", r.Offset,
"attempt", attempt+1,
"max_retries", c.options.MaxRetries,
"error", lastErr,
)
failure := c.policy.process(ctx, func(attemptCtx context.Context) error { return handler(recordContext(attemptCtx, r), r) })
if err := ctx.Err(); err != nil {
return err
}

return c.deadLetter(ctx, r, lastErr)
}

// deadLetter publishes a record whose handler kept failing to the DLQ. A
// non-nil error means the record must not be committed.
func (c *consumer) deadLetter(ctx context.Context, r *kgo.Record, handlerErr error) error {
logger := c.options.Logger

if c.options.DLQProducer == nil {
logger.Error("handler failed, no DLQ configured",
"topic", r.Topic,
"partition", r.Partition,
"offset", r.Offset,
"error", handlerErr,
)
if failure.err == nil {
return nil
}

if err := c.options.DLQProducer.SendToDLQ(ctx, r.Topic, r.Value, r.Key, handlerErr); err != nil {
logger.Error("failed to send message to DLQ",
"error", err,
"topic", r.Topic,
"partition", r.Partition,
"offset", r.Offset,
"dlq_error", handlerErr,
)
return fmt.Errorf("%w: topic %s partition %d offset %d: %w", ErrDLQPublish, r.Topic, r.Partition, r.Offset, err)
}

logger.Error("message sent to DLQ",
"topic", r.Topic,
"partition", r.Partition,
"offset", r.Offset,
"dlq_topic", dlqTopic(r.Topic),
"error", handlerErr,
)
if !failure.park || c.options.DeadLetter == nil || c.options.DeadLetter.Topic == r.Topic {
return fmt.Errorf("topic %s partition %d offset %d: %w", r.Topic, r.Partition, r.Offset, failure.paused())
}
publishCtx, cancel := context.WithTimeout(ctx, c.options.DeadLetter.Timeout)
defer cancel()
if err := c.records.ProduceSync(publishCtx, deadLetterRecord(c.options.DeadLetter, r, failure)).FirstErr(); err != nil {
return fmt.Errorf("%w: topic %s partition %d offset %d: %w", ErrDLQPublish, r.Topic, r.Partition, r.Offset, errors.Join(failure.paused(), err))
}
if c.options.OnDLQPublish != nil {
c.options.OnDLQPublish(r.Topic, handlerErr)
c.options.OnDLQPublish(r.Topic, failure.err)
}
return nil
}
Expand Down
Loading
Loading