New to Rust? Grab our free Rust for Beginners eBook Get it free →
What Is Kafka? Node.js Guide

Connecting a Node.js application to Kafka lets it send records and read them. Apache Kafka stores and moves continuous streams of records between applications.
This guide shows how KafkaJS, a JavaScript client for Kafka, publishes an event and reads it with a consumer group.
TL;DR
Apache Kafka is a distributed event log: Node.js applications write records to topics, and consumer groups read them by partition and offset.
- A broker stores topic partitions, while a producer writes events and a consumer reads them.
- A partition key keeps related records together, so their order is preserved within that partition.
- KafkaJS connects Node.js code to Kafka, but it does not install or run the broker.
What Is Apache Kafka?
Apache Kafka is software for storing and moving continuous streams of records between applications. A record, often called an event, describes something that happened, such as an order being paid or a device reporting a reading.
A Kafka cluster consists of brokers. A topic names a stream, and Kafka divides it into partitions. Each partition is an ordered log stored on the cluster.
A producer appends records to a partition, and a consumer fetches them later. Kafka retains records according to topic policy rather than deleting them when one consumer reads them.
Each record has an offset, its position in one partition. A consumer group tracks offsets so its members can resume reading. Different groups can independently read the same topic, which lets an order service and an analytics job use the same events without competing for a single copy.
| Term | Meaning | Why it matters |
|---|---|---|
| Broker | Kafka server | Stores and serves partition data |
| Topic | Named event stream | Organizes records by purpose |
| Partition | Ordered log within a topic | Enables parallel work and defines ordering scope |
| Offset | Position in a partition | Lets a group track progress or replay |
A record key can influence its partition. KafkaJS hashes a supplied key to choose a partition by default, so records with the same key, such as an order ID, go to the same partition and retain their relative order there. No key means the producer can distribute records across partitions.
How to Use Kafka with Node.js Step by Step
A Node.js service needs a reachable Kafka broker and a client library. KafkaJS is a JavaScript client. Install it in your application with npm, then use the broker address and topic configured for your environment.
Step 1: Connect to a broker
In the example, the broker address is localhost:9092. Replace it with the listener address your Kafka administrator or local development setup provides. Installing KafkaJS alone does not create that broker.
npm install kafkajs
Step 2: Publish a keyed event
Create a producer and send a JSON value to a topic. The key groups events for the same order in one partition, which is useful when their order matters.
const { Kafka } = require('kafkajs')
const kafka = new Kafka({ clientId: 'orders-api', brokers: ['localhost:9092'] })
const producer = kafka.producer()
async function publishOrder() {
await producer.connect()
try {
await producer.send({
topic: 'orders',
messages: [{ key: 'order-101', value: JSON.stringify({ status: 'paid' }) }],
})
} finally {
await producer.disconnect()
}
}
publishOrder().catch(console.error)
The send call waits for the broker acknowledgement configured for the producer. Production code should also handle connection failures and decide whether retrying is safe for the operation.
Step 3: Read events with a consumer group
A consumer joins a named group, subscribes to the topic and processes records. Kafka assigns partitions among active members of that group. Adding consumers beyond the topic’s partition count leaves some consumers idle.
const consumer = kafka.consumer({ groupId: 'order-processor' })
async function readOrders() {
await consumer.connect()
await consumer.subscribe({ topic: 'orders', fromBeginning: false })
await consumer.run({
eachMessage: async ({ partition, message }) => {
console.log({ partition, offset: message.offset, value: message.value.toString() })
},
})
}
readOrders().catch(console.error)
The consumer starts from its committed group offset when one exists. The fromBeginning option applies when the group has no valid committed offset: false starts at the end, while true starts at the earliest retained record. It does not force an established group to replay all data.
Step 4: Verify the flow
I ran the producer connection probe from the named file kafka_node_demo.js with KafkaJS 2.0.0 on Node.js v26.7.0. The command failed because localhost:9092 refused the connection. The exact terminal result was:
Connection error: connect ECONNREFUSED 127.0.0.1:9092

This confirms that the client needs a broker listening at the configured address before a send can succeed. Start or provision Kafka using its official instructions, then repeat the producer and consumer flow with the same topic and group settings.
Kafka Node.js Edge Cases and Next Steps
Empty consumer output usually comes down to the broker address, topic, group offset or partition assignment. Check these in order before changing offset code.
| Symptom | Likely cause | Check or fix |
|---|---|---|
| ECONNREFUSED | No listener at the configured address | Confirm broker host, port and network access |
| New consumer sees no old records | Group has committed offsets, or starts at end | Use a fresh test group or reset offsets deliberately |
| Some group members receive nothing | More consumers than assigned partitions | Increase partitions only after checking ordering and key distribution |
| Ordering differs across records | Records belong to separate partitions | Use a stable key for records that must remain ordered |
Kafka preserves order within a partition, not across every partition in a topic. A key cannot create global ordering, and a hot key can concentrate traffic on one partition. Partition count also bounds parallel consumers in a group, so raising it trades more concurrent capacity for more operational and ordering considerations.
Replication copies partition data to other brokers, but it does not make every possible failure harmless. Durability depends on replica placement and acknowledgement settings.
A committed offset records read progress, not a guarantee that an external database update happened exactly once. Design processing to tolerate retries, often by making writes idempotent.
New Kafka deployments use KRaft metadata mode. Older clusters may still use ZooKeeper depending on their version and migration state.
Brokers can share a machine for testing, but this does not protect against that machine failing. For a separate multi-node setup, see our multi-broker Kafka cluster guide. For event-driven service design, see our Node.js microservices guide.
Conclusion
Think of Kafka as durable partitioned logs that application clients write and read. For Node.js, keep the broker, topic, key and consumer-group offset in view: those settings explain where records go and which records a consumer sees.
Start with the Apache Kafka documentation for broker concepts and the KafkaJS getting-started guide for client setup. Use the KafkaJS consumer reference when you need to inspect offset and group behavior.
FAQ
These answers cover common Kafka questions about Node.js clients, brokers and consumer behavior.
How does Kafka work with Node.js?
A Node.js Kafka client connects to a broker. A producer writes records to topic partitions, and a consumer group reads them while tracking offsets.
Can multiple Kafka brokers run on one node?
They can share a machine for development or testing, but brokers on one machine do not protect against that machine failing. Production fault tolerance requires independent failure domains.
Why does a KafkaJS consumer not receive earlier messages?
An existing group uses its committed offset. For a group without a valid offset, fromBeginning controls whether it begins at the earliest retained record or at the end.
How many consumers can work in one Kafka group?
A group can have many members, but each partition is assigned to at most one member at a time. Members beyond the partition count receive no partition assignment.




