kafkajs and node-rdkafka are the two leading Apache Kafka clients for Node.js, but they solve the connectivity problem in fundamentally different ways. kafkajs is a pure JavaScript implementation that runs directly on the Node.js event loop, requiring no external dependencies or compilation steps. It prioritizes ease of installation and seamless integration with containerized environments. node-rdkafka, conversely, is a high-performance wrapper around librdkafka (a C++ library). It offloads heavy network I/O and protocol parsing to native threads, offering superior throughput and stricter protocol compliance at the cost of complex installation requirements involving C++ toolchains and native binaries.
Connecting Node.js applications to Apache Kafka is a common requirement for building event-driven architectures. While the goal is the same โ producing and consuming messages reliably โ the two dominant libraries, kafkajs and node-rdkafka, take completely different paths to get there. One is built entirely in JavaScript, while the other relies on native C++ code. This choice impacts everything from your deployment pipeline to your application's performance ceiling.
The most critical difference lies in how these libraries handle network operations and protocol parsing.
kafkajs is written 100% in JavaScript. It runs on the main Node.js event loop. This means it shares CPU time with your application logic. If you are parsing massive JSON payloads or doing heavy computation in your consumer callback, you might block the event loop, delaying the next batch of Kafka messages from being processed.
// kafkajs: Runs on the main event loop
const { Kafka } = require('kafkajs');
const kafka = new Kafka({ clientId: 'my-app', brokers: ['localhost:9092'] });
const consumer = kafka.consumer({ groupId: 'test-group' });
await consumer.connect();
await consumer.subscribe({ topic: 'test-topic', fromBeginning: true });
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
// Heavy computation here blocks the entire Node.js process
const data = JSON.parse(message.value.toString());
await processHeavyLoad(data);
},
});
node-rdkafka acts as a bridge to librdkafka, a robust C++ library. The heavy lifting โ network sockets, SSL handshakes, and message compression โ happens in native threads outside the Node.js event loop. This keeps your JavaScript thread free to handle HTTP requests or UI logic, even while ingesting gigabytes of data.
// node-rdkafka: Offloads work to native threads
const Kafka = require('node-rdkafka');
const consumer = new Kafka.KafkaConsumer({
'group.id': 'test-group',
'metadata.broker.list': 'localhost:9092',
}, {});
consumer.connect();
consumer.on('data', function(message) {
// This callback is triggered from a native thread queue
// The event loop remains responsive even under high load
const data = JSON.parse(message.value.toString());
processHeavyLoad(data);
});
consumer.subscribe(['test-topic']);
consumer.consume();
For frontend architects managing CI/CD pipelines, the installation experience is often the deciding factor.
kafkajs is a standard npm package. It has no system dependencies. You can install it on any machine with Node.js, and it works immediately. It is exceptionally friendly to Docker (using lightweight alpine images) and serverless platforms like AWS Lambda or Vercel, where you cannot install system-level compilers.
# kafkajs: Instant installation anywhere
npm install kafkajs
node-rdkafka requires a C++ compiler, Python, and specific system libraries (like libsasl and openssl) to be present on the build machine. In a Docker environment, you often need to install build essentials, compile the module, and then strip them out to keep the image size down. If your CI runner doesn't match your production OS exactly, you may face cryptic compilation errors.
# node-rdkafka: Requires system dependencies
# On Ubuntu/Debian, you typically need:
# apt-get install -y libssl-dev libsasl2-dev
npm install node-rdkafka
When throughput matters, the architectural differences become visible.
kafkajs performs admirably for most microservice use cases. However, because it processes messages on the event loop, you must manually manage backpressure. If your consumer logic is slower than the incoming message rate, you need to pause the consumer explicitly to prevent memory exhaustion.
// kafkajs: Manual backpressure handling
await consumer.run({
eachBatch: async ({ batch, resolveOffset, pause }) => {
for (const message of batch.messages) {
await processMessage(message);
// If processing is slow, we must manually pause
if (isSystemOverloaded()) {
pause();
break;
}
resolveOffset(message.offset);
}
},
});
node-rdkafka handles backpressure internally within the C++ layer. It maintains its own queue and can fetch messages from the broker faster than JavaScript can process them, holding them safely in native memory until your app is ready. This makes it more resilient to sudden traffic spikes without custom code.
// node-rdkafka: Native queue management
const consumer = new Kafka.KafkaConsumer({
'queue.buffering.max.messages': 100000, // Configured in C++ layer
'fetch.message.max.bytes': 1048576
}, {});
// The library automatically pauses fetching from the broker
// if the internal queue is full, protecting the JS heap.
consumer.consume(10);
Kafka is a complex system with many configuration options. The two libraries differ in how much of this they expose.
kafkajs implements the Kafka protocol in JavaScript. While it covers all standard use cases (SASL, SSL, transactions), adding support for very new or obscure Kafka features depends on the maintainers updating the JS code. It offers a clean, promise-based API that feels natural to JavaScript developers.
// kafkajs: Promise-based, modern JS API
const admin = kafka.admin();
await admin.connect();
// Creating topics is straightforward and async/await friendly
await admin.createTopics({
topics: [{ topic: 'new-topic', numPartitions: 3, replicationFactor: 1 }]
});
await admin.disconnect();
node-rdkafka exposes almost the entire configuration surface of librdkafka. If a feature exists in the C++ library, you can usually access it in Node.js by passing the right config string. This is powerful but can be verbose and less "JavaScript-like" since it relies heavily on string-based configuration keys and event emitters rather than promises.
// node-rdkafka: String-based config, event-driven
const producer = new Kafka.Producer({
'client.id': 'my-app',
'metadata.broker.list': 'localhost:9092',
'compression.codec': 'snappy', // Direct mapping to C++ config
'statistics.interval.ms': 5000
});
producer.connect();
producer.on('ready', () => {
producer.produce('topic-name', null, Buffer.from('message'));
});
You are building an AWS Lambda function triggered by API Gateway to log events to Kafka.
kafkajsnode-rdkafka increases cold start time. kafkajs loads instantly, has no binary dependencies to mismatch with the Lambda runtime, and the throughput of a single Lambda function won't saturate a JS client.You are building a service that consumes 50,000 messages per second to update real-time dashboards.
node-rdkafkakafkajs. node-rdkafka allows the C++ layer to ingest data at line speed while the JS layer focuses on aggregating results. The native compression and batching algorithms are also more optimized.You have a cluster of Node.js services communicating via Kafka for order processing.
kafkajs| Feature | kafkajs | node-rdkafka |
|---|---|---|
| Implementation | 100% JavaScript | C++ (librdkafka) Wrapper |
| Installation | Simple (npm install) | Complex (Requires C++ toolchain) |
| Event Loop | Blocks loop on heavy load | Offloads I/O to native threads |
| Backpressure | Manual management required | Handled automatically by native queue |
| Serverless Ready | โ Yes (Lightweight) | โ Difficult (Binary deps) |
| API Style | Promises / Async-Await | Events / Callbacks |
| Config Flexibility | Standard Kafka Options | Full librdkafka Exposure |
For the vast majority of Node.js applications โ especially those running in containers, serverless environments, or standard microservice architectures โ kafkajs is the pragmatic choice. It removes the friction of native bindings and provides a clean, modern API that fits well with modern JavaScript development practices.
Reserve node-rdkafka for specialized high-performance scenarios where you have measured a clear bottleneck in the JavaScript event loop or require specific low-level configurations only available in the C++ client. The performance gain is real, but it comes with a significant tax on developer experience and deployment complexity.
Choose kafkajs if you prioritize developer experience, easy deployment, and pure JavaScript compatibility. It is the ideal choice for serverless functions (like AWS Lambda), Docker containers where minimizing image size is critical, or teams that want to avoid the headaches of compiling native C++ modules. It works well for standard microservice communication where throughput requirements are moderate and the simplicity of npm install is a key factor.
Choose node-rdkafka if your application demands maximum throughput, ultra-low latency, or strict adherence to complex Kafka configurations that only the C++ client supports. It is the right fit for high-volume data ingestion pipelines, real-time analytics engines, or environments where you can manage native dependencies (like dedicated VMs or specialized CI/CD pipelines). Avoid this if you are deploying to restricted serverless environments or lack the system permissions to install native build tools.
A modern Apache Kafkaยฎ client for Node.js
Get Started ยป
Read the Docs
ยท
Report Bug
ยท
Request Feature
KafkaJS is a modern Apache Kafka client for Node.js. It is compatible with Kafka 0.10+ and offers native support for 0.11 features.
KAFKA is a registered trademark of The Apache Software Foundation and has been licensed for use by KafkaJS. KafkaJS has no affiliation with and is not endorsed by The Apache Software Foundation.
Upstash: Serverless Kafka
|
Get help directly from a KafkaJS developer
|
To become a sponsor, reach out in our Slack community to get in touch with one of the maintainers. Also consider becoming a Github Sponsor by following any of the links under "Sponsor this project" in the sidebar.
npm install kafkajs
# yarn add kafkajs
const { Kafka } = require('kafkajs')
const kafka = new Kafka({
clientId: 'my-app',
brokers: ['kafka1:9092', 'kafka2:9092']
})
const producer = kafka.producer()
const consumer = kafka.consumer({ groupId: 'test-group' })
const run = async () => {
// Producing
await producer.connect()
await producer.send({
topic: 'test-topic',
messages: [
{ value: 'Hello KafkaJS user!' },
],
})
// Consuming
await consumer.connect()
await consumer.subscribe({ topic: 'test-topic', fromBeginning: true })
await consumer.run({
eachMessage: async ({ topic, partition, message }) => {
console.log({
partition,
offset: message.offset,
value: message.value.toString(),
})
},
})
}
run().catch(console.error)
Learn more about using KafkaJS on the official site!
Read something on the website that didn't work with the latest stable version?
Check the pre-release versions - the website is updated on every merge to master.
KafkaJS is an open-source project where development takes place in the open on GitHub. Although the project is maintained by a small group of dedicated volunteers, we are grateful to the community for bug fixes, feature development and other contributions.
See Developing KafkaJS for information on how to run and develop KafkaJS.
We welcome contributions to KafkaJS, but we also want to see a thriving third-party ecosystem. If you would like to create an open-source project that builds on top of KafkaJS, please get in touch and we'd be happy to provide feedback and support.
Here are some projects that we would like to build, but haven't yet been able to prioritize:
See LICENSE for more details.
Apache Kafka and Kafka are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. KafkaJS has no affiliation with the Apache Software Foundation.