MCPcopy Index your code
hub / github.com/Trendyol/kafka-konsumer

github.com/Trendyol/kafka-konsumer @v2.4.15

Chat with this repo
repository ↗ · DeepWiki ↗ · release v2.4.15 ↗ · + Follow
399 symbols 1,241 edges 60 files 23 documented · 6%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Kafka Konsumer

🔨Build And Test 🔨IntegrationTest Go Report Card

Description

Kafka Konsumer provides an easy implementation of Kafka consumer with a built-in retry/exception manager (kafka-cronsumer).

Migration Guide

V2 Release Notes

  • Added ability for manipulating kafka message headers.
  • Added transactional retry feature. Set false if you want to use exception/retry strategy to only failed messages.
  • Enable manuel commit at both single and batch consuming modes.
  • Enabling consumer resume/pause functionality. Please refer to its example and how it works documentation.
  • Bumped kafka-cronsumer to the latest version:
    • Backoff strategy support (linear, exponential options)
    • Added message key for retried messages
    • Added x-error-message to see what was the error of the message during processing
  • Reduce memory allocation.
  • Increase TP on changing internal concurrency structure.

How to migrate from v1 to v2?

You can get latest version via go get github.com/Trendyol/kafka-konsumer/v2@latest

  • You need to change import path from github.com/Trendyol/kafka-konsumer to github.com/Trendyol/kafka-konsumer/v2

  • You need to change your consume function with pointer signature.

  • We moved messageGroupDuration from batchConfiguration.messageGroupDuration to root level. Because this field is used single (non-batch) consumer too.

Installation

go get github.com/Trendyol/kafka-konsumer/v2@latest

Examples

You can find a number of ready-to-run examples at this directory.

After running docker-compose up command, you can run any application you want.

Simple Consumer

func main() {
    consumerCfg := &kafka.ConsumerConfig{
        Reader: kafka.ReaderConfig{
            Brokers: []string{"localhost:29092"},
            Topic:   "standart-topic",
            GroupID: "standart-cg",
        },
        ConsumeFn:    consumeFn,
        RetryEnabled: false,
    }

    consumer, _ := kafka.NewConsumer(consumerCfg)
    defer consumer.Stop()

    consumer.Consume()
}

func consumeFn(message kafka.Message) error {
    fmt.Printf("Message From %s with value %s", message.Topic, string(message.Value))
    return nil
}

Simple Consumer With Retry/Exception Option

func main() {
    consumerCfg := &kafka.ConsumerConfig{
        Reader: kafka.ReaderConfig{
            Brokers: []string{"localhost:29092"},
            Topic:   "standart-topic",
            GroupID: "standart-cg",
        },
        RetryEnabled: true,
        RetryConfiguration: kafka.RetryConfiguration{
            Topic:         "retry-topic",
            StartTimeCron: "*/1 * * * *",
            WorkDuration:  50 * time.Second,
            MaxRetry:      3,
        },
        ConsumeFn: consumeFn,
    }

    consumer, _ := kafka.NewConsumer(consumerCfg)
    defer consumer.Stop()

    consumer.Consume()
}

func consumeFn(message kafka.Message) error {
    fmt.Printf("Message From %s with value %s", message.Topic, string(message.Value))
    return nil
}

With Batch Option

func main() {
    consumerCfg := &kafka.ConsumerConfig{
        Reader: kafka.ReaderConfig{
            Brokers: []string{"localhost:29092"},
            Topic:   "standart-topic",
            GroupID: "standart-cg",
        },
        LogLevel:     kafka.LogLevelDebug,
        RetryEnabled: true,
        RetryConfiguration: kafka.RetryConfiguration{
            Brokers:       []string{"localhost:29092"},
            Topic:         "retry-topic",
            StartTimeCron: "*/1 * * * *",
            WorkDuration:  50 * time.Second,
            MaxRetry:      3,
        },
        MessageGroupDuration: time.Second,
        BatchConfiguration: kafka.BatchConfiguration{
            MessageGroupLimit:    1000,
            BatchConsumeFn:       batchConsumeFn,
        },
    }

    consumer, _ := kafka.NewConsumer(consumerCfg)
    defer consumer.Stop()

    consumer.Consume()
}

func batchConsumeFn(messages []kafka.Message) error {
    fmt.Printf("%d\n comes first %s", len(messages), messages[0].Value)
    return nil
}

With Disabling Transactional Retry

func main() {
    consumerCfg := &kafka.ConsumerConfig{
        Reader: kafka.ReaderConfig{
            Brokers: []string{"localhost:29092"},
            Topic:   "standart-topic",
            GroupID: "standart-cg",
        },
        LogLevel:     kafka.LogLevelDebug,
        RetryEnabled: true,
        TransactionalRetry: kafka.NewBoolPtr(false),
        RetryConfiguration: kafka.RetryConfiguration{
            Brokers:       []string{"localhost:29092"},
            Topic:         "retry-topic",
            StartTimeCron: "*/1 * * * *",
            WorkDuration:  50 * time.Second,
            MaxRetry:      3,
        },
        MessageGroupDuration: time.Second,
        BatchConfiguration: kafka.BatchConfiguration{
            MessageGroupLimit:    1000,
            BatchConsumeFn:       batchConsumeFn,
        },
    }

    consumer, _ := kafka.NewConsumer(consumerCfg)
    defer consumer.Stop()

    consumer.Consume()
}

func batchConsumeFn(messages []kafka.Message) error {
    // you can add custom error handling here & flag messages
    for i := range messages {
        if i%2 == 0 {
            messages[i].IsFailed = true
        }
    }

    // you must return err here to retry failed messages
    return errors.New("err")
}

With Producer Interceptor

Please refer to Producer Interceptor Example

With Distributed Tracing Support

Please refer to Tracing Example

With Pause & Resume Consumer

Please refer to Pause Resume Example

With Grafana & Prometheus

In this example, we are demonstrating how to create Grafana dashboard and how to define alerts in Prometheus. You can see the example by going to the with-grafana folder in the examples folder and running the infrastructure with docker compose up and then the application.

grafana

With SASL-PLAINTEXT Authentication

Under the examples - with-sasl-plaintext folder, you can find an example of a consumer integration with SASL/PLAIN mechanism. To try the example, you can run the command docker compose up under the specified folder and then start the application.

With Send Direct To Dead Letter

This feature lets you send a message directly to a dead-letter topic by setting message.SendDirectToDeadLetter = true inside your ConsumeFn (or selectively for items in BatchConsumeFn). When this flag is set and your ConsumeFn returns an error, the message is produced to the configured dead-letter topic with an x-error-message header.

  • Dead letter topic resolution order: if consumer.DeadLetterTopic is set, it is used; otherwise retryConfiguration.deadLetterTopic is used.
  • You can set message.ErrDescription to override the error header value written as x-error-message.

Please refer to Send Direct To Dead Letter Example to run both single and batch scenarios.

Configurations

config description default
reader Describes all segmentio kafka reader configurations
consumeFn Kafka consumer function, if retry enabled it, is also used to consume retriable messages
skipMessageByHeaderFn Function to filter messages based on headers, return true if you want to skip the message nil
logLevel Describes log level; valid options are debug, info, warn, and error info
concurrency Number of goroutines used at listeners 1
retryEnabled Retry/Exception consumer is working or not false
transactionalRetry Set false if you want to use exception/retry strategy to only failed messages true
deadLetterTopic Dead-letter topic name to produce messages when message.SendDirectToDeadLetter is true. If empty, retryConfiguration.deadLetterTopic will be used. ""
commitInterval indicates the interval at which offsets are committed to the broker. 1s
rack

Extension points exported contracts — how you extend this code

ProducerInterceptor (Interface)
(no doc) [3 implementers]
producer_interceptor.go
Reader (Interface)
(no doc) [3 implementers]
consumer_base.go
Producer (Interface)
(no doc) [3 implementers]
producer.go
API (Interface)
(no doc) [2 implementers]
api.go
Layer (Interface)
(no doc) [2 implementers]
layer.go
LoggerInterface (Interface)
LoggerInterface is a logger that supports log levels, context and structured logging.
logger.go
OtelKafkaKonsumerWriter (Interface)
(no doc) [1 implementers]
otel_producer.go
BatchConsumeFn (FuncType)
(no doc)
consumer_config.go

Core symbols most depended-on inside this repo

Errorf
called by 77
logger.go
Error
called by 71
logger.go
NewZapLogger
called by 38
zap.go
Stop
called by 27
consumer_base.go
String
called by 26
producer_config.go
Consume
called by 26
consumer_base.go
Add
called by 19
sub_process.go
process
called by 13
batch_consumer.go

Shape

Function 172
Method 158
Struct 47
Interface 11
TypeAlias 7
FuncType 4

Languages

Go100%

Modules by API surface

consumer_base.go28 symbols
consumer_config.go27 symbols
message.go18 symbols
batch_consumer_test.go18 symbols
test/integration/integration_test.go17 symbols
logger.go14 symbols
consumer_test.go14 symbols
producer.go13 symbols
batch_consumer.go13 symbols
balancer_test.go13 symbols
consumer_config_test.go12 symbols
producer_test.go11 symbols

For agents

$ claude mcp add kafka-konsumer \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page