KafkaJS
Modern Apache Kafka client for Node.js with producers, consumer groups, and admin APIs over a pure TCP protocol.
Official Documentation ↗v2. Check the official docs for the latest API surface.Installation
npm install kafkajspnpm add kafkajsMethods
No methods match this filter.
Modern Apache Kafka client for Node.js with producers, consumer groups, and admin APIs over a pure TCP protocol.
Overview
KafkaJS speaks the Kafka wire protocol directly from Node.js, so no JVM sits in the deployment. A Kafka instance holds brokers and credentials; producers publish keyed batches, and consumers join groups that split partitions among members with automatic rebalancing.
The library leans explicit: you connect before use, decide compression per producer, and control commit behavior through eachMessage or eachBatch patterns. Admin APIs cover topic and group operations, and instrumentation hooks surface lag and rebalance events for observability.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
new Kafka— Constructs the client entry point holding broker addresses plus optional TLS and SASL authentication.producer.send— Publishes a batch of messages to a topic; keys decide partition placement for ordering guarantees.producer.sendBatch— Writes across multiple topics in one atomic batch request, reducing round trips for fan-out events.consumer.run— Joins a consumer group, subscribes to topics, and invokes eachMessage per record; committing happens after the handler.
Usage Notes
- Choose message keys that map to your ordering domain; the partitioner hashes them deterministically.
- Instrument consumer instrumentation events to watch lag and rebalance storms before users feel them.
- Set idempotent producers and retries in configuration when exactly-once-adjacent semantics matter for billing.
Common Pitfalls
- A throwing eachMessage retries the same offset forever; design poison-pill handling from day one.
- Deploying more consumers than partitions leaves members idle, a common scaling surprise.
- Rebalances pause consumption; keep heartbeats healthy by avoiding blocking work inside the handler path.
FAQ
- How is ordering guaranteed?
- Ordering exists per partition, and messages with the same non-null key land in the same partition. Use business-entity keys such as order ID; null-keyed messages round-robin and have no ordering promise.
- What happens when eachMessage throws?
- The consumer pauses that partition and retries the message; a poison record therefore blocks the partition. Wrap handlers, dead-letter bad records into another topic, and keep processing moving.
- How do I tune consumer throughput?
- Raise partitions and consumers in lockstep, and use eachBatch with autoCommit thresholds to amortize commits. Keep handlers fast and offload slow work to a queue so the broker heartbeat and rebalance timing stay healthy.
Report a problem with this API docOpens a pre-filled issue on GitHub.