question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question: best way to pass a callback to Producer.produce()

See original GitHub issue

If I want to invoke a callback function upon delivery of the message to Kafka, what’s the best/recommended way to handle this since Producer.produce() doesn’t accept a callback or return a Promise, and reports deliveries via events?

I have implemented this by passing a function as the opaque value, and then calling opaque on the delivery-report handler. Is this a typical pattern, or is the fire & forget pattern what others do?

Below is the snippet of code that shows what I’ve come up with:

producer.on('delivery-report', (err, report) => {
  if (typeof report.opaque === 'function') {
    report.opaque.call(null, err, report);
  }
});

producer.on('ready', () => {
  publishMessage('Awesome key', new Buffer('Awesome message'), (err) => {
    if (err) {
      console.log('Message failed', {err});
      return;
    }
    console.log('Message published successfully!');
  });
});

function publishMessage(messageKey, messageValue, callback) {
  try {
    const topicName = 'Test';
    const partition = -1;
    const timestamp = Date.now();

    producer.produce(topicName, partition, messageValue, messageKey, timestamp, callback);
  } catch (err) {
    callback(err);
  }
}

Thanks!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
umarrasydancommented, Sep 6, 2018

If someone is looking for a promise version of this

const Kafka = require('node-rdkafka');

const producer = new Kafka.Producer({
    'metadata.broker.list': 'host:9092',
    dr_cb: true
});

producer.connect();

producer.setPollInterval(10);

producer.on('delivery-report', (err, report) => {
    if (typeof report.opaque === 'function') {
        report.opaque.call(null, err, report);
    }
});

producer.on('ready', async () => {
    console.log('ready');
    try {
        const report = await produceMessage({
            foo: 'bar'
        });
        console.log('report', report);
        console.log('message published');
    } catch (e) {
        console.log(e);
    }
});

function produceMessage(messageValue) {
    return new Promise((resolve, reject) => {
        try {
            producer.produce(
                'some-topic',
                null,
                new Buffer(JSON.stringify(messageValue)),
                null,
                Date.now(),
                (err, report) => {
                    if (err) return reject(err);
                    return resolve(report);
                }
            );
        } catch (e) {
            return reject(e);
        }
    });
}

0reactions
stale[bot]commented, Mar 11, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Kafka Producer Callbacks - Javatpoint
The callback function used by the producer is the onCompletion(). Basically, this method requires two arguments: Metadata of the Record: Metadata of the...
Read more >
How to build an Apache KafkaProducer application with ...
In this tutorial, learn how to build an Kafka producer application and handle responses using the Callback interface using Confluent, with step-by-step ...
Read more >
Apache Kafka Callback and Acks - Learning Journal
Asynchronous Producer. In this method, we send a message and provide a call back function to receive acknowledgment. We don't wait for success...
Read more >
Best way of passing callback function parameters in C++
Simply do call( std::ref( your callback ) ) . std::ref overrides operator() and forwards it to the contained object. Simularly, with template< ...
Read more >
Solved: Kafka Producer Async Send with Callback - Error Ha...
Problem Statement: How do I get access to the Producer Record when I encounter an exception from my asynchronous send method returned within ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found