MCPcopy Index your code
hub / github.com/Blizzard/node-rdkafka

github.com/Blizzard/node-rdkafka @v3.6.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v3.6.1 ↗ · + Follow
586 symbols 1,262 edges 75 files 188 documented · 32% 2 cross-repo links updated 7mo agov3.6.1 · 2025-12-03★ 2,205105 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

node-rdkafka - Node.js wrapper for Kafka C/C++ library

Copyright (c) 2016 Blizzard Entertainment.

https://github.com/blizzard/node-rdkafka

Build Status

npm version

Looking for Collaborators!

I am looking for your help to make this project even better! If you're interested, check this out

Overview

The node-rdkafka library is a high-performance NodeJS client for Apache Kafka that wraps the native librdkafka library. All the complexity of balancing writes across partitions and managing (possibly ever-changing) brokers should be encapsulated in the library.

This library currently uses librdkafka version 2.12.0.

Reference Docs

To view the reference docs for the current version, go here

Contributing

For guidelines on contributing please see CONTRIBUTING.md

Code of Conduct

Play nice; Play fair.

Requirements

  • Apache Kafka >=0.9
  • Node.js >=16
  • Linux/Mac
  • Windows?! See below
  • OpenSSL

Mac OS High Sierra / Mojave

OpenSSL has been upgraded in High Sierra and homebrew does not overwrite default system libraries. That means when building node-rdkafka, because you are using openssl, you need to tell the linker where to find it:

export CPPFLAGS=-I/usr/local/opt/openssl/include
export LDFLAGS=-L/usr/local/opt/openssl/lib

Then you can run npm install on your application to get it to build correctly.

NOTE: From the librdkafka docs

WARNING: Due to a bug in Apache Kafka 0.9.0.x, the ApiVersionRequest (as sent by the client when connecting to the broker) will be silently ignored by the broker causing the request to time out after 10 seconds. This causes client-broker connections to stall for 10 seconds during connection-setup before librdkafka falls back on the broker.version.fallback protocol features. The workaround is to explicitly configure api.version.request to false on clients communicating with <=0.9.0.x brokers.

Alpine

Using Alpine Linux? Check out the docs.

Windows

Windows build is not compiled from librdkafka source but it is rather linked against the appropriate version of NuGet librdkafka.redist static binary that gets downloaded from https://globalcdn.nuget.org/packages/librdkafka.redist.2.12.0.nupkg during installation. This download link can be changed using the environment variable NODE_RDKAFKA_NUGET_BASE_URL that defaults to https://globalcdn.nuget.org/packages/ when it's no set.

Requirements: * node-gyp for Windows

Note: I still do not recommend using node-rdkafka in production on Windows. This feature was in high demand and is provided to help develop, but we do not test against Windows, and windows support may lag behind Linux/Mac support because those platforms are the ones used to develop this library. Contributors are welcome if any Windows issues are found :)

Tests

This project includes two types of unit tests in this project: * end-to-end integration tests * unit tests

You can run both types of tests by using Makefile. Doing so calls mocha in your locally installed node_modules directory.

  • Before you run the tests, be sure to init and update the submodules:
  • git submodule init
  • git submodule update
  • To run the unit tests, you can run make lint or make test.
  • To run the integration tests, you must have a running Kafka installation available. By default, the test tries to connect to localhost:9092; however, you can supply the KAFKA_HOST environment variable to override this default behavior. Run make e2e.

Usage

You can install the node-rdkafka module like any other module:

npm install node-rdkafka

To use the module, you must require it.

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

Configuration

You can pass many configuration options to librdkafka. A full list can be found in librdkafka's Configuration.md

Configuration keys that have the suffix _cb are designated as callbacks. Some of these keys are informational and you can choose to opt-in (for example, dr_cb). Others are callbacks designed to return a value, such as partitioner_cb.

Not all of these options are supported. The library will throw an error if the value you send in is invalid.

The library currently supports the following callbacks: * partitioner_cb * dr_cb or dr_msg_cb * event_cb * rebalance_cb (see Rebalancing) * offset_commit_cb (see Commits)

Librdkafka Methods

This library includes two utility functions for detecting the status of your installation. Please try to include these when making issue reports where applicable.

You can get the features supported by your compile of librdkafka by reading the variable "features" on the root of the node-rdkafka object.

const Kafka = require('node-rdkafka');
console.log(Kafka.features);

// #=> [ 'gzip', 'snappy', 'ssl', 'sasl', 'regex', 'lz4' ]

You can also get the version of librdkafka

const Kafka = require('node-rdkafka');
console.log(Kafka.librdkafkaVersion);

// #=> 2.12.0

Sending Messages

A Producer sends messages to Kafka. The Producer constructor takes a configuration object, as shown in the following example:

const producer = new Kafka.Producer({
  'metadata.broker.list': 'kafka-host1:9092,kafka-host2:9092'
});

A Producer requires only metadata.broker.list (the Kafka brokers) to be created. The values in this list are separated by commas. For other configuration options, see the Configuration.md file described previously.

The following example illustrates a list with several librdkafka options set.

const producer = new Kafka.Producer({
  'client.id': 'kafka',
  'metadata.broker.list': 'localhost:9092',
  'compression.codec': 'gzip',
  'retry.backoff.ms': 200,
  'message.send.max.retries': 10,
  'socket.keepalive.enable': true,
  'queue.buffering.max.messages': 100000,
  'queue.buffering.max.ms': 1000,
  'batch.num.messages': 1000000,
  'dr_cb': true
});

Stream API

You can easily use the Producer as a writable stream immediately after creation (as shown in the following example):

// Our producer with its Kafka brokers
// This call returns a new writable stream to our topic 'topic-name'
const stream = Kafka.Producer.createWriteStream({
  'metadata.broker.list': 'kafka-host1:9092,kafka-host2:9092'
}, {}, {
  topic: 'topic-name'
});

// Writes a message to the stream
const queuedSuccess = stream.write(Buffer.from('Awesome message'));

if (queuedSuccess) {
  console.log('We queued our message!');
} else {
  // Note that this only tells us if the stream's queue is full,
  // it does NOT tell us if the message got to Kafka!  See below...
  console.log('Too many messages in our queue already');
}

// NOTE: MAKE SURE TO LISTEN TO THIS IF YOU WANT THE STREAM TO BE DURABLE
// Otherwise, any error will bubble up as an uncaught exception.
stream.on('error', (err) => {
  // Here's where we'll know if something went wrong sending to Kafka
  console.error('Error in our kafka stream');
  console.error(err);
})

If you do not want your code to crash when an error happens, ensure you have an error listener on the stream. Most errors are not necessarily fatal, but the ones that are will immediately destroy the stream. If you use autoClose, the stream will close itself at the first sign of a problem.

Standard API

The Standard API is more performant, particularly when handling high volumes of messages. However, it requires more manual setup to use. The following example illustrates its use:

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

// Connect to the broker manually
producer.connect();

// Wait for the ready event before proceeding
producer.on('ready', () => {
  try {
    producer.produce(
      // Topic to send the message to
      'topic',
      // optionally we can manually specify a partition for the message
      // this defaults to -1 - which will use librdkafka's default partitioner (consistent random for keyed messages, random for unkeyed messages)
      null,
      // Message to send. Must be a buffer
      Buffer.from('Awesome message'),
      // for keyed messages, we also specify the key - note that this field is optional
      'Stormwind',
      // you can send a timestamp here. If your broker version supports it,
      // it will get added. Otherwise, we default to 0
      Date.now(),
      // you can send an opaque token here, which gets passed along
      // to your delivery reports
    );
  } catch (err) {
    console.error('A problem occurred when sending our message');
    console.error(err);
  }
});

// Any errors we encounter, including connection errors
producer.on('event.error', (err) => {
  console.error('Error from producer');
  console.error(err);
})

// We must either call .poll() manually after sending messages
// or set the producer to poll on an interval (.setPollInterval).
// Without this, we do not get delivery events and the queue
// will eventually fill up.
producer.setPollInterval(100);

To see the configuration options available to you, see the Configuration section.

Methods
Method Description
producer.connect() Connects to the broker.

The connect() method emits the ready event when it connects successfully. If it does not, the error will be passed through the callback. | |producer.disconnect()| Disconnects from the broker.

The disconnect() method emits the disconnected event when it has disconnected. If it does not, the error will be passed through the callback. | |producer.poll() | Polls the producer for delivery reports or other events to be transmitted via the emitter.

In order to get the events in librdkafka's queue to emit, you must call this regularly. | |producer.setPollInterval(interval) | Polls the producer on this interval, handling disconnections and reconnection. Set it to 0 to turn it off. | |producer.produce(topic, partition, msg, key, timestamp, opaque)| Sends a message.

The produce() method throws when produce would return an error. Ordinarily, this is just if the queue is full. | |producer.flush(timeout, callback)| Flush the librdkafka internal queue, sending all messages. Default timeout is 500ms | |producer.initTransactions(timeout, callback)| Initializes the transactional producer. | |producer.beginTransaction(callback)| Starts a new transaction. | |producer.sendOffsetsToTransaction(offsets, consumer, timeout, callback)| Sends consumed topic-partition-offsets to the broker, which will get committed along with the transaction. | |producer.abortTransaction(timeout, callback)| Aborts the ongoing transaction. | |producer.commitTransaction(timeout, callback)| Commits the ongoing transaction. |

Events

Some configuration properties that end in _cb indicate that an event should be generated for that option. You can either:

  • provide a value of true and react to the event
  • provide a callback function directly

The following example illustrates an event:

const producer = new Kafka.Producer({
  'client.id': 'my-client', // Specifies an identifier to use to help trace activity in Kafka
  'metadata.broker.list': 'localhost:9092', // Connect to a Kafka instance on localhost
  'dr_cb': true // Specifies that we want a delivery-report event to be generated
});

// Poll for events every 100 ms
producer.setPollInterval(100);

producer.on('delivery-report', (err, report) => {
  // Report of delivery statistics here:
  //
  console.log(report);
});

The following table describes types of events.

Event Description
disconnected The disconnected event is emitted when the broker has disconnected.

This event is emitted only when .disconnect is called. The wrapper will always try to reconnect otherwise. | | ready | The ready event is emitted when the Producer is ready to send messages. | | event | The event event is emitted when librdkafka reports an event (if you opted in via the event_cb option). | | event.log | The event.log event is emitted when logging events come in (if you opted into logging via the event_cb option).

You will need to set a value for debug if you want to send information. | | event.stats | The event.stats event is emitted when librdkafka reports stats (if you opted in by setting the statistics.interval.ms to a non-zero value). | | event.error | The event.error event is emitted when librdkafka reports an error | | event.throttle | The event.throttle event emitted when librdkafka reports throttling. | | delivery-report | The delivery-report event is emitted when a delivery report has been found via polling.

To use this event, you must set request.required.acks to 1 or -1 in topic configuration and dr_cb (or dr_msg_cb if you want the report to contain the message payload) to true in the Producer constructor options. |

Extension points exported contracts — how you extend this code

GlobalConfig (Interface)
(no doc)
config.d.ts
LibrdKafkaError (Interface)
(no doc)
index.d.ts
ProducerGlobalConfig (Interface)
(no doc)
config.d.ts
ReadyInfo (Interface)
(no doc)
index.d.ts
ConsumerGlobalConfig (Interface)
(no doc)
config.d.ts
ClientMetrics (Interface)
(no doc)
index.d.ts
TopicConfig (Interface)
(no doc)
config.d.ts
MetadataOptions (Interface)
(no doc)
index.d.ts

Core symbols most depended-on inside this repo

Match
called by 149
cpplint.py
Search
called by 127
cpplint.py
err
called by 69
src/errors.cc
connect
called by 44
index.d.ts
disconnect
called by 39
index.d.ts
create
called by 32
src/config.cc
next
called by 26
lib/client.js
NumLines
called by 17
cpplint.py

Shape

Method 278
Function 212
Class 71
Interface 25

Languages

C++49%
Python30%
TypeScript21%

Modules by API surface

cpplint.py173 symbols
src/workers.cc48 symbols
src/workers.h43 symbols
src/callbacks.cc39 symbols
index.d.ts36 symbols
src/kafka-consumer.cc34 symbols
src/producer.cc20 symbols
src/callbacks.h20 symbols
src/common.cc16 symbols
src/admin.cc14 symbols
src/connection.cc13 symbols
lib/producer/high-level-producer.js11 symbols

Used by 2 indexed graphs manifest dependencies, hub-wide

For agents

$ claude mcp add node-rdkafka \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page