Building Microservices With Node.js and Kafka
Topics, partitions and consumer groups explained through two small Node.js services.
- kafka
- microservices
- node.js
- event-driven
On this page ยท 15 sections
Synchronous HTTP calls between services are simple and fragile. When the order service calls billing, which calls inventory, which calls email, one slow or failed hop breaks the whole chain, and every new consumer means editing the producer. Event-driven architecture reverses this: services publish facts ("order placed") to a log, and any number of other services react independently. Apache Kafka is the standard platform for that log. This guide builds two small Node.js services that communicate through Kafka and covers the details that decide whether such a system is reliable: keys, consumer groups, idempotency, retries and dead-letter topics.
The architecture
- 1Orders service
writes the order, publishes order.placed
- 2Kafka topic
durable, ordered log split into partitions
- 3Consumer groups
billing, inventory and email each read every event
- 4Dead-letter topic
messages that keep failing
Core concepts you need
| Concept | Meaning |
|---|---|
| Topic | A named stream of events (for example orders.placed) |
| Partition | A topic is split into partitions; order is guaranteed within one partition |
| Offset | A message's position in a partition; consumers track how far they have read |
| Key | Decides which partition a message goes to; same key, same partition |
| Consumer group | Consumers that share a topic's partitions; each partition goes to one member |
| Retention | Kafka keeps messages for a configured time or size, independent of whether they were read |
Two consequences drive design: ordering is per key (choose keys deliberately), and parallelism is limited by partition count.
Run Kafka locally
A single-node broker is enough for development:
docker run -d --name kafka -p 9092:9092 apache/kafka:latestnpm install kafkajs zodCreate the topics up front, including a dead-letter topic:
// src/kafka/admin.tsimport { Kafka } from "kafkajs";export const kafka = new Kafka({ clientId: "orders-platform", brokers: (process.env.KAFKA_BROKERS ?? "localhost:9092").split(","),});export async function ensureTopics() { const admin = kafka.admin(); await admin.connect(); await admin.createTopics({ topics: [ { topic: "orders.placed", numPartitions: 3, replicationFactor: 1 }, { topic: "orders.placed.dlq", numPartitions: 1, replicationFactor: 1 }, ], }); await admin.disconnect();}Use a replication factor of at least 3 in production so a single broker failure does not lose data.
Define the event contract
Events are an API. Give them an envelope with an id, type, version and timestamp, and validate them on the way in:
// src/events/order-placed.tsimport { z } from "zod";export const orderPlacedV1 = z.object({ eventId: z.uuid(), type: z.literal("order.placed"), version: z.literal(1), occurredAt: z.iso.datetime(), data: z.object({ orderId: z.string(), customerId: z.string(), totalCents: z.number().int().nonnegative(), items: z.array(z.object({ sku: z.string(), quantity: z.number().int().positive() })), }),});export type OrderPlacedV1 = z.infer<typeof orderPlacedV1>;Rules that keep contracts healthy: only add optional fields in a given version, bump the version for breaking changes, and let consumers ignore fields they do not know. For larger systems consider a schema registry with Avro or Protobuf.
The producer
// src/orders/publisher.tsimport { randomUUID } from "node:crypto";import { kafka } from "../kafka/admin";import type { OrderPlacedV1 } from "../events/order-placed";const producer = kafka.producer({ idempotent: true }); // avoids duplicates on producer retrieslet connected = false;export async function publishOrderPlaced(order: OrderPlacedV1["data"]) { if (!connected) { await producer.connect(); connected = true; } const event: OrderPlacedV1 = { eventId: randomUUID(), type: "order.placed", version: 1, occurredAt: new Date().toISOString(), data: order, }; await producer.send({ topic: "orders.placed", acks: -1, // wait for all in-sync replicas messages: [ { key: order.orderId, // same order, same partition, so ordered value: JSON.stringify(event), headers: { "event-type": event.type, "event-version": "1" }, }, ], });}acks: -1 trades a little latency for durability. The key guarantees that all events for one order stay in sequence.
The consumer with retries and a dead-letter topic
// src/billing/consumer.tsimport { kafka } from "../kafka/admin";import { orderPlacedV1 } from "../events/order-placed";const consumer = kafka.consumer({ groupId: "billing-service" });const dlqProducer = kafka.producer();const MAX_ATTEMPTS = 3;const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));export async function startBillingConsumer() { await Promise.all([consumer.connect(), dlqProducer.connect()]); await consumer.subscribe({ topic: "orders.placed", fromBeginning: false }); await consumer.run({ eachMessage: async ({ message, partition }) => { const raw = message.value?.toString() ?? ""; for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { try { const event = orderPlacedV1.parse(JSON.parse(raw)); await handleOrderPlaced(event); return; // success: the offset is committed automatically } catch (err) { if (attempt === MAX_ATTEMPTS) { await dlqProducer.send({ topic: "orders.placed.dlq", messages: [{ key: message.key, value: message.value, headers: { error: String(err), "original-partition": String(partition) }, }], }); return; // moved to the DLQ, so do not block the partition } await sleep(2 ** attempt * 200); // simple exponential backoff } } }, });}Never let a single poisonous message block a partition forever. After a few attempts, park it in the dead-letter topic and continue. Alert on DLQ growth and build a way to inspect and replay those messages.
Make handlers idempotent
Kafka's default guarantee is at least once. Rebalances, retries and restarts mean the same event can be delivered again, so processing must be safe to repeat. The simplest pattern is to record processed event ids in the same transaction as the side effect:
async function handleOrderPlaced(event: OrderPlacedV1) { await db.transaction(async (tx) => { // INSERT ... ON CONFLICT DO NOTHING; returns 0 rows if this event was already processed const inserted = await tx.insertProcessedEvent(event.eventId, "billing-service"); if (!inserted) return; await tx.createInvoice({ orderId: event.data.orderId, amountCents: event.data.totalCents, }); });}A unique constraint on (consumer, event_id) makes duplicates harmless.
Avoid the "dual write" problem
A common bug: the service saves the order to its database, then publishes to Kafka, and crashes between the two. The order exists but no event does (or the reverse). The transactional outbox pattern fixes it. Write the event into an outbox table in the same database transaction as the order, then have a small relay process publish outbox rows to Kafka and mark them sent:
await db.transaction(async (tx) => { const order = await tx.insertOrder(input); await tx.insertOutbox({ topic: "orders.placed", key: order.id, payload: buildOrderPlacedEvent(order), });});// A separate relay reads unsent outbox rows, publishes them, and marks them sent.Together with idempotent consumers, this gives you reliable end-to-end delivery without distributed transactions.
Scaling and ordering
- More throughput: add consumer instances in the same group, up to the number of partitions. Extra instances beyond that sit idle.
- Ordering: only within a partition, so use meaningful keys. If you must process strictly in order per customer, key by customer id.
- Hot keys: a single very busy key concentrates load on one partition; watch for skew.
- Rebalancing: when consumers join or leave, partitions move. Keep handlers quick and idempotent, and shut down gracefully:
for (const signal of ["SIGINT", "SIGTERM"] as const) { process.on(signal, async () => { await consumer.disconnect(); // commits offsets and leaves the group cleanly await producer.disconnect(); process.exit(0); });}Security considerations
- Use TLS and SASL authentication for brokers outside a trusted network, and ACLs so each service can only access its own topics.
- Do not put secrets or unnecessary personal data in events; events are retained and replayable.
- Validate every incoming message, since a topic may receive data from more than one producer.
- Encrypt sensitive fields or reference them by id.
Performance considerations
- Batch sends (
messages: [...]) and tunelinger/batch settings for throughput. - Use compression (for example gzip or snappy where supported) for large payloads.
- Keep messages small; store large blobs elsewhere and send a reference.
- Monitor consumer lag, the difference between the latest offset and the consumer's position, which is the most important health metric for event-driven systems.
Testing
- Unit test handlers as pure functions with a fake database, including the duplicate-event case.
- Contract tests validate that producers emit events matching the schema consumers expect.
- Integration tests run against a real broker (Docker in CI): publish an event, assert the side effect, publish it again, assert nothing changes.
- Test the failure path: send a malformed message and confirm it lands in the dead-letter topic without blocking later messages.
Common mistakes
- Treating Kafka as a request/response mechanism.
- No keys, so related events are processed out of order.
- Non-idempotent consumers that double-charge or double-email.
- Publishing after the database commit with no outbox.
- Unbounded retries that block a partition.
- Changing event shapes without versioning.
- Too few partitions, which later caps scaling.
Best practices
- Name topics and events after facts that happened, in the past tense.
- Version events and validate on both sides.
- Use keys deliberately, make consumers idempotent and add a dead-letter path.
- Monitor lag, DLQ size and error rates.
- Start simple: one topic, one producer, one consumer group, then grow.
Conclusion
Kafka does not remove complexity; it moves it into well-defined places: contracts, keys, idempotency and failure handling. Get those four right and services can evolve and scale independently, with new consumers added without touching producers. Start with a single event and a single consumer, add the outbox and the dead-letter topic early, and watch consumer lag as your first health signal.
Frequently asked questions
+When should I use Kafka instead of a simple message queue?
Use Kafka when you need a durable, replayable event log, high throughput, multiple independent consumers of the same events, or ordering per key. For simple task queues with one consumer and no replay, a queue such as SQS or a Redis-based job queue is usually simpler.
+What is a consumer group?
A set of consumers that share the work of reading a topic. Kafka assigns each partition to exactly one consumer in the group, so adding consumers scales processing up to the number of partitions. Different groups each receive every message independently.
+How do I preserve message ordering?
Kafka guarantees order only within a partition. Give related messages the same key (for example an order id) so they land on the same partition and are processed in order.
+Does Kafka deliver messages exactly once?
By default, delivery is at least once, so consumers can see duplicates after retries or rebalances. Make handlers idempotent (for example by recording processed event ids). Exactly-once semantics exist for specific Kafka-to-Kafka pipelines but add complexity.
+What happens when a message keeps failing?
Retry a limited number of times with backoff, then publish it to a dead-letter topic with error details so the consumer can move on and the message can be inspected or replayed later.
+How many partitions should a topic have?
Enough to allow your target consumer parallelism and throughput, because partitions cap the number of active consumers in a group. Increasing partitions later changes key-to-partition mapping, so plan ahead.
+Is kafkajs still the right Node.js client?
It is widely used and good for learning and many production systems, but check its maintenance status and consider alternatives such as the Confluent JavaScript client for new projects. The concepts in this guide apply to either.