Search code examples
node.jsapache-kafkakafka-producer-api

How to send data to multiple Kafka topic partitions in Node JS


In Node js application when I am trying to send messages on to Kafka topic all are going to Partition 0. The topic was created with 4 partitions and want to publish in round-robin mechanism, I tried multiple options but no luck.

Is there any way to solve this? Below is the snippet of the code.

payloads = [
    { topic: 'test-topic', messages: ['TestMessage1', 'TestMessage2', 'TestMessage3', 'TestMessage4']},
];
producer.on('ready', function(){
    producer.send(payloads, function(err, data){
        console.log("Successfully written onto Kafka");
    });

Solution

  • In Kafka, messages with the same key are placed in the same partition. You can either define the partition manually:

    // Force partitioning - default partition is 0
    payloads = [ 
        { topic: 'test-topic', messages: ['TestMessage1'], partition: 0 },
        { topic: 'test-topic', messages: ['TestMessage2'], partition: 1 },
        { topic: 'test-topic', messages: ['TestMessage3'], partition: 2 },
        { topic: 'test-topic', messages: ['TestMessage4'], partition: 3 }
    ];
    

    or use a different key for each message:

    payloads = [ 
        { topic: 'test-topic', messages: ['TestMessage1'], key: '1' },
        { topic: 'test-topic', messages: ['TestMessage2'], key: '2' },
        { topic: 'test-topic', messages: ['TestMessage3'], key: '3' },
        { topic: 'test-topic', messages: ['TestMessage4'], key: '4' }
    ];
    
    // Alternatively, you can use KeyedMessage
    km = new KeyedMessage('1', 'TestMessage1'),
    km2 = new KeyedMessage('2', 'TestMessage2'),
    payloads = [
        { topic: 'test-topic', messages: [ km , km2 ] },
    ];