DEV Community

Cover image for Kafka from Fundamentals to Production, Part 1: Topics, Partitions, and Consumer Groups
Juan Gómez
Juan Gómez

Posted on

Kafka from Fundamentals to Production, Part 1: Topics, Partitions, and Consumer Groups

Kafka from Fundamentals to Production, Part 1: Topics, Partitions, and Consumer Groups

I scaled a Kafka consumer from one replica to five, and two of the five processed exactly zero events for the whole run. No error, no warning. They connected, joined the group, printed processed 0 once a second, and that was all they ever did.

If you learned messaging on RabbitMQ, that is backwards. In the RabbitMQ series on this blog, five consumers on one queue split the work five ways. On a Kafka topic with three partitions, at most three of them do anything. It is a very Kafka way to fail: you wake up one morning, everything looks normal, and you have been assigned nothing.

That is one of four things a RabbitMQ user gets wrong about Kafka on day one, and none of them is exotic. Reading a message does not remove it. Order holds inside a partition and nowhere else. And every time a consumer joins or leaves, the group has to hand out its partitions again, and part of the topic goes unread meanwhile: a few seconds when a consumer joins, about 45 seconds when one is killed without warning. This post measures each of them on Kafka 4.4 with Node 24, on the same coffee shop the RabbitMQ series used.

Three conveyor belts full of coffee cups, each ending at a robot that is picking cups up, while two more robots stand to the side with empty hands, asleep

A topic is a log, not a queue

A RabbitMQ queue holds a message until a consumer acknowledges it, and then the message is gone. That is what a queue is for: a list of jobs that shrinks as they get done.

A Kafka topic is an append-only log, split into one or more partitions; most of this post is about those, and for now each one is simply a log of its own. The producer adds events at the end, and the broker keeps them for the topic's retention period (seven days by default) whether anyone read them or not. Each event gets an offset: its position in its partition, 0, 1, 2 and so on. Consumers do not delete anything. They remember how far they got.

That memory belongs to a consumer group: a name, such as billing, under which Kafka stores one committed offset per partition, meaning "this group has processed everything before this position". Two groups with different names read the same events independently, each with its own bookmark.

A long row of numbered tiles with new empty slots being added at its right end, and two robots, one cyan and one purple, each tied to its own flag at a different point along the row

Here is the whole idea in one run. Checkout produced 3,000 orders, three events each, before any consumer existed. Then a consumer in group billing started, ran for 15 seconds and stopped. Its first six lines, and the last three, with the total it printed as it left the group:

14:45:44.726  partitions -  processed 0  max wait 0 ms  out of order 0
14:45:45.727  partitions -  processed 0  max wait 0 ms  out of order 0
14:45:46.728  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
14:45:47.728  partitions 0,1,2  processed 9000  max wait 9192 ms  out of order 0
14:45:48.728  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
14:45:49.728  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
…
14:45:57.731  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
SIGTERM: finishing the current event, committing offsets, leaving the group
left the group: 9000 events processed, 0 out of order
Enter fullscreen mode Exit fullscreen mode

A second consumer, in a new group called analytics, started afterwards. It read the same 9,000 events, all of them in its first second, and the oldest had been waiting 26 seconds since checkout produced it:

14:46:04.428  partitions 0,1,2  processed 9000  max wait 25953 ms  out of order 0
14:46:05.427  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
…
SIGTERM: finishing the current event, committing offsets, leaving the group
left the group: 9000 events processed, 0 out of order
Enter fullscreen mode Exit fullscreen mode

Then billing started again, with the same group name:

14:46:33.188  partitions 0,1,2  processed 0  max wait 0 ms  out of order 0
SIGTERM: finishing the current event, committing offsets, leaving the group
left the group: 0 events processed, 0 out of order
Enter fullscreen mode Exit fullscreen mode

Zero, because the group's committed offsets said it had already read everything. And the events both groups read are still there. Kafka ships a tool that prints each partition's earliest and latest offset:

docker compose exec kafka /opt/kafka/bin/kafka-get-offsets.sh --bootstrap-server kafka:19092 --topic orders --time -2
docker compose exec kafka /opt/kafka/bin/kafka-get-offsets.sh --bootstrap-server kafka:19092 --topic orders --time -1
Enter fullscreen mode Exit fullscreen mode
orders:0:0
orders:1:0
orders:2:0
orders:0:2952
orders:1:3078
orders:2:2970
Enter fullscreen mode Exit fullscreen mode

Three consequences follow, and they shape everything else:

  • Replay is free. A new service can start a new group and read history from the beginning, and a group can be rewound to reprocess. RabbitMQ cannot do either once a message is acknowledged.
  • "Was it processed?" is a question about a group, not about the event. The event has no status. Each group has a position.
  • Retention deletes data, consumption does not. A topic's disk use is throughput times retention, however fast or slow the consumers are.

The lab

Everything runs in Docker: one Kafka broker and the Node scripts, in Compose.

The broker is Kafka 4.4.0 in KRaft mode, which means no ZooKeeper: Kafka 4.0 removed it, and the broker now keeps its own metadata. Pin the version. On the day I wrote this, apache/kafka:latest still pointed at 4.3.1, a month after 4.4.0 shipped.

The client is Confluent's @confluentinc/kafka-javascript 1.11.0. For years the default Node client was KafkaJS, whose last release, 2.2.4, came out in February 2023. Confluent's client wraps librdkafka 2.16.0, the same C library under Confluent's .NET, Python and Go clients, and offers a KafkaJS-compatible API, so most KafkaJS tutorials still read correctly. Its README lists prebuilt binaries for Node 18 to 24. On Node 26 the install found no prebuilt binary (a 404 from the download URL), fell back to compiling librdkafka from source and failed on my machine, which is one more reason the scripts run in node:24-alpine (Node 24.22.3 when I ran them).

The whole stack is in the appendix: compose.yaml, the Dockerfile and package.json. Three things in it matter for what follows:

  • The broker listens on two addresses: kafka:19092 for containers in the Compose network, and localhost:9092 for a client on your own machine, bound to 127.0.0.1 so nothing outside it can connect. The third listener in the file, CONTROLLER, is KRaft's internal channel, which the broker uses to manage its own metadata.
  • Topic auto-creation is off, on the broker and in the consumer, so a typo in a topic name fails instead of quietly creating a new topic. This client turns consumer-side auto-creation on by default, which is why the consumer below switches it off again.
  • One broker means one copy of everything. Kafka keeps its own bookkeeping in internal topics (committed offsets among them), and those default to three replicas; the file sets them to one. On a real cluster you want three, for your topics too. The data lives inside the container, so docker compose down -v gives you a clean broker, which is what a lab wants. Keep the -v: the Kafka image declares three anonymous volumes, and a plain down leaves them behind. A day of fresh brokers left me 153 of them.

Docker Compose prints its own progress lines (Container … Started) around every command; they are left out of all the output below.

Node 24 runs the .ts files directly by stripping the types, with no build step. One module holds the client, the topic name and the shape of an order event:

// src/kafka.ts: the broker address, the topic, and the shape of an order event.
import { KafkaJS } from '@confluentinc/kafka-javascript';

export const TOPIC = 'orders';

export type OrderEventType = 'placed' | 'paid' | 'shipped';
export const STEPS: readonly OrderEventType[] = ['placed', 'paid', 'shipped'];

export type OrderEvent = {
  orderId: string;
  type: OrderEventType;
  seq: number;        // 1, 2, 3: the order in which checkout emitted them
  totalCents: number;
  producedAt: number; // epoch ms, so a consumer can tell how long the event waited
};

export function parseOrderEvent(value: Buffer | null): OrderEvent | null {
  if (value === null) return null;
  try {
    const event = JSON.parse(value.toString('utf8')) as Partial<OrderEvent>;
    const valid =
      typeof event.orderId === 'string' &&
      STEPS.includes(event.type as OrderEventType) &&
      Number.isInteger(event.seq) &&
      Number.isInteger(event.totalCents) &&
      typeof event.producedAt === 'number';
    return valid ? (event as OrderEvent) : null;
  } catch {
    return null;
  }
}

export const kafka = new KafkaJS.Kafka({
  kafkaJS: {
    brokers: (process.env.KAFKA_BROKERS ?? 'localhost:9092').split(','),
    clientId: process.env.CLIENT_ID ?? 'aurora',
    logLevel: KafkaJS.logLevel.WARN,
  },
});
Enter fullscreen mode Exit fullscreen mode

The producer: one key per order

Checkout emits three events per order, placed, paid and shipped, 50 ms apart. Every event carries the order id as its key, which decides the partition it lands on; the ordering section below shows why that matters.

// src/produce-orders.ts: simulates checkout. Each order emits placed, paid, shipped, STEP_MS apart.
import { randomUUID } from 'node:crypto';
import { setTimeout as sleep } from 'node:timers/promises';
import { kafka, STEPS, TOPIC, type OrderEvent } from './kafka.ts';

const ORDERS = Number(process.env.ORDERS ?? 3_000);
const RATE = Number(process.env.RATE ?? 200);       // new orders per second
const STEP_MS = Number(process.env.STEP_MS ?? 50);  // gap between one order's events
const KEYED = process.env.KEYED !== 'false';        // KEYED=false drops the key, on purpose

const producer = kafka.producer({ kafkaJS: { idempotent: true } });
await producer.connect();

let stopping = false;
process.once('SIGINT', () => { stopping = true; });
process.once('SIGTERM', () => { stopping = true; });

let sent = 0;
let failedOrders = 0;

async function runOrder(orderId: string, totalCents: number): Promise<void> {
  for (const [index, type] of STEPS.entries()) {
    if (index > 0) await sleep(STEP_MS);
    const event: OrderEvent = { orderId, type, seq: index + 1, totalCents, producedAt: Date.now() };
    // send() resolves once the broker has the event (acks=all, idempotent).
    await producer.send({
      topic: TOPIC,
      messages: [{ key: KEYED ? orderId : null, value: JSON.stringify(event) }],
    });
    sent++;
  }
}

const started = performance.now();
const inFlight = new Set<Promise<void>>();
let orders = 0;

for (; orders < ORDERS && !stopping; orders++) {
  const wait = started + (orders * 1_000) / RATE - performance.now();
  if (wait > 0) await sleep(wait);
  const order: Promise<void> = runOrder(`ord-${randomUUID().slice(-12)}`, 900 + Math.floor(Math.random() * 4_000))
    .catch((error: unknown) => {
      failedOrders++;
      console.error('order not fully published:', error);
    })
    .finally(() => inFlight.delete(order));
  inFlight.add(order);
}

await Promise.all(inFlight);
await producer.disconnect();

const seconds = (performance.now() - started) / 1_000;
console.log(`${sent} events for ${orders} orders in ${seconds.toFixed(1)} s, ${KEYED ? 'keyed by order id' : 'no key'}`);
if (failedOrders > 0) {
  console.error(`${failedOrders} orders were not fully published`);
  process.exitCode = 1;
}
Enter fullscreen mode Exit fullscreen mode

idempotent: true does two things here. The broker discards a duplicate if the producer has to retry a send after a timeout, and one producer's events keep the order it sent them in. It also makes send() wait for the broker's confirmation that it has the event (on a cluster, that every copy of the partition that is keeping up has it), so a resolved send() means stored, not just sent. Part 2 of this series takes producer guarantees apart properly; for now it is enough that nothing is lost or written twice on the way in.

The consumer: one line per second

// src/billing-consumer.ts: one member of a consumer group. Prints one line per second.
import { KafkaJS } from '@confluentinc/kafka-javascript';
import { kafka, parseOrderEvent, TOPIC } from './kafka.ts';

const GROUP_ID = process.env.GROUP_ID ?? 'billing';
const PROTOCOL = process.env.GROUP_PROTOCOL === 'classic' ? 'classic' : 'consumer';
// Classic protocol only: the members pick the assignor, and this client's default is eager round-robin.
// Under the consumer protocol the broker assigns partitions itself.
const COOPERATIVE = process.env.ASSIGNOR === 'cooperative-sticky';

const consumer = kafka.consumer({
  kafkaJS: {
    groupId: GROUP_ID,
    fromBeginning: true,
    allowAutoTopicCreation: false, // this client defaults it to true: a typo would create a topic
    ...(PROTOCOL === 'classic' && COOPERATIVE
      ? { partitionAssigners: [KafkaJS.PartitionAssigners.cooperativeSticky] }
      : {}),
  },
  'group.protocol': PROTOCOL,
});

// Per-order progress: an event is out of order when it is not the step after the last one seen.
const lastSeq = new Map<string, number>();
const MAX_TRACKED_ORDERS = 100_000;
let outOfOrder = 0;
let total = 0;
let processed = 0;
let maxWaitMs = 0;
let skipped = 0;

function track(orderId: string, seq: number): void {
  const previous = lastSeq.get(orderId) ?? 0;
  if (seq !== previous + 1) outOfOrder++;
  if (seq === 3 && previous === 2) {
    lastSeq.delete(orderId); // finished in order: nothing left to check
    return;
  }
  lastSeq.set(orderId, Math.max(previous, seq));
  if (lastSeq.size > MAX_TRACKED_ORDERS) {
    lastSeq.delete(lastSeq.keys().next().value as string); // oldest entry
  }
}

await consumer.connect();
await consumer.subscribe({ topics: [TOPIC] });

const ticker = setInterval(() => {
  const partitions = consumer.assignment().map(({ partition }) => partition).sort((a, b) => a - b);
  console.log(
    `${new Date().toISOString().slice(11, 23)}  partitions ${partitions.join(',') || '-'}` +
    `  processed ${processed}  max wait ${maxWaitMs} ms  out of order ${outOfOrder}` +
    (skipped > 0 ? `  skipped ${skipped}` : ''),
  );
  processed = 0;
  maxWaitMs = 0;
}, 1_000);

await consumer.run({
  eachMessage: async ({ message }) => {
    const event = parseOrderEvent(message.value);
    if (event === null) {
      skipped++; // not an order event; a real service would park it on a dead-letter topic
      return;
    }
    track(event.orderId, event.seq);
    processed++;
    total++;
    maxWaitMs = Math.max(maxWaitMs, Date.now() - event.producedAt);
  },
});

let stopping = false;
async function shutdown(signal: NodeJS.Signals): Promise<void> {
  if (stopping) return;
  stopping = true;
  clearInterval(ticker);
  console.log(`${signal}: finishing the current event, committing offsets, leaving the group`);
  try {
    await consumer.disconnect(); // an event already in eachMessage completes before this resolves
    console.log(`left the group: ${total} events processed, ${outOfOrder} out of order`);
    process.exit(0);
  } catch (error) {
    console.error('disconnect failed:', error);
    process.exit(1);
  }
}
process.once('SIGTERM', () => void shutdown('SIGTERM'));
process.once('SIGINT', () => void shutdown('SIGINT'));
Enter fullscreen mode Exit fullscreen mode

Four things in it matter for this article:

  • 'group.protocol': 'consumer' opts into the newer way a group divides its partitions, which Kafka 4.0 made generally available. The broker has it switched on by default, but the client still defaults to the older, classic protocol and has to ask. GROUP_PROTOCOL and ASSIGNOR exist only so the rebalance section can compare the two; ignore them until then.
  • fromBeginning: true applies only when the group has no committed offset yet: a brand-new group starts at offset 0 instead of at the end of the log.
  • An event it cannot parse is counted and skipped. A real service would move it to a separate topic for someone to inspect, a dead-letter topic, rather than drop it.
  • Each line reports four things for the last second: the partitions this member owns, how many events it processed, max wait (the longest any of those events had waited since checkout produced it) and a running count of events that arrived out of order for their order id. max wait is the number to watch when a partition goes unread: events pile up, and the first ones processed afterwards show how long they waited.

Create the topic with three partitions:

docker compose up -d kafka
docker compose run --rm tools node src/create-topic.ts 3
Enter fullscreen mode Exit fullscreen mode

The run in the first section, on a fresh broker with the topic created, was checkout first, then one consumer at a time, each stopped with SIGTERM:

docker compose run --rm -e ORDERS=3000 -e RATE=1000 tools node src/produce-orders.ts

docker compose run -d --name billing-run -e GROUP_ID=billing -e CLIENT_ID=billing tools node src/billing-consumer.ts
sleep 15
docker stop billing-run && docker logs billing-run && docker rm billing-run
Enter fullscreen mode Exit fullscreen mode

I ran that consumer three times: as billing for 15 seconds, as analytics for 15, and as billing again for 10.

src/create-topic.ts, src/describe-group.ts and src/where-keys-land.ts are in the appendix at the end.

Partitions decide how many consumers work

A topic is split into partitions, and each partition is a separate log with its own offsets. Inside a consumer group, each partition is assigned to exactly one member at a time. That rule is how Kafka keeps a partition's events in order without any locking: one reader per partition, reading front to back.

The rule has a direct consequence. Here are five billing consumers on the three-partition topic, ten seconds into a 20-second run of 2,000 orders:

docker compose up -d --scale billing=5 billing
sleep 8
docker compose run --rm -e ORDERS=2000 -e RATE=100 tools node src/produce-orders.ts &
sleep 10
docker compose run --rm tools node src/describe-group.ts billing
Enter fullscreen mode Exit fullscreen mode
group billing: stable, consumer protocol, 5 members
  member Pxyxhg3g  partitions none
  member oV7dv4hg  partitions 1
  member /0aQTdcA  partitions 0
  member XhE5zDTQ  partitions 2
  member OlFvMH3Q  partitions none
  partition 0  committed 938  end 1041  lag 103
  partition 1  committed 889  end 1117  lag 228
  partition 2  committed 1190  end 1240  lag 50
Enter fullscreen mode Exit fullscreen mode

Two members own nothing. When the run ended, each consumer printed its total as it left the group (the SIGTERM line each one printed just before is left out):

billing-5  | left the group: 2115 events processed, 0 out of order
billing-4  | left the group: 1851 events processed, 0 out of order
billing-2  | left the group: 0 events processed, 0 out of order
billing-3  | left the group: 0 events processed, 0 out of order
billing-1  | left the group: 2034 events processed, 0 out of order
Enter fullscreen mode Exit fullscreen mode

Two of five consumers did nothing for the whole run, and no metric on the consumer side would tell you why.

The last three lines of describe-group show lag: how far the group's committed offset is behind the end of each partition, in events. It is the number to alert on, because it grows whenever a group falls behind, for any reason. Read it with one detail in mind: this client commits every five seconds by default (autoCommitInterval), so the committed offset trails the work by about five seconds, and lag measured from it always looks a little worse than the truth.

The idle members are not useless: they are standbys, and they take over a partition when its owner leaves. How fast that happens is the rebalance section's problem.

So the partition count is the ceiling on a group's parallelism, and you choose it when you create the topic. Partitions are not free on the broker either, but a few more than today's consumers need is the cheap mistake. Too few is the expensive one, because, as the ordering section shows, adding partitions later moves keys.

Kafka 4.2 and later: share groups

There is one exception, and it is new. Share groups, production-ready since Kafka 4.2 (the design is KIP-932; a KIP is a Kafka Improvement Proposal), let the members of a group share partitions. The broker hands each record to one member and waits for that member to acknowledge it, record by record, so the partition count stops capping the number of members. It is the RabbitMQ model inside Kafka. The 4.4 broker in this lab has them on by default, so here are five members of a share group on the same three partitions, using the console consumer that ships with Kafka:

# A new share group starts at the end of the log; this one starts at the beginning.
docker compose exec kafka /opt/kafka/bin/kafka-configs.sh --bootstrap-server kafka:19092 \
  --alter --entity-type groups --entity-name billing-share --add-config share.auto.offset.reset=earliest
# Five members, each running in the background inside the broker container for 50 seconds.
for n in 1 2 3 4 5; do
  docker compose exec -d kafka sh -c "timeout 50 /opt/kafka/bin/kafka-console-share-consumer.sh \
    --bootstrap-server kafka:19092 --topic orders --group billing-share \
    > /tmp/share-$n.txt 2>/tmp/share-$n.err"
done
# Once they have joined, 1,000 orders, 3,000 events, while they listen.
sleep 15
docker compose run --rm -e ORDERS=1000 -e RATE=100 tools node src/produce-orders.ts
# Once they have exited: one line per record each member printed.
sleep 30
docker compose exec kafka sh -c 'cd /tmp && wc -l share-1.txt share-2.txt share-3.txt share-4.txt share-5.txt'
Enter fullscreen mode Exit fullscreen mode
   525 share-1.txt
   625 share-2.txt
   842 share-3.txt
   480 share-4.txt
   528 share-5.txt
  3000 total
Enter fullscreen mode Exit fullscreen mode

All five got work, and all 3,000 records were delivered; a second run split them 686, 976, 265, 846 and 227. Two details in the commands matter, and I learned both by getting them wrong. A new share group starts at the end of the log (share.auto.offset.reset is latest), so its members only get what is produced after the group is ready: my first two attempts kept that default, and one got all 3,000 records while the other got 2,618. And the members start before checkout. In an attempt that produced everything first and then started them, all 3,000 records arrived, but two members took them all and three got none.

Two catches. A share group keeps records in order only within one batch a member receives, with no guarantee across batches, members or redeliveries, so it fits independent jobs, not an order's sequence of events. And the Node client in this article cannot join one: version 1.11.0 exposes no share-consumer API, only configuration properties that librdkafka documents for it. For now, share groups are something you use from Java or from the CLI.

Order holds inside a partition, and only there

A Kafka consumer reads each partition in offset order. Across partitions there is no order at all: a consumer that owns partitions 0 and 2 may process a later event from partition 2 before an earlier one from partition 0.

The producer decides which partition an event goes to. With a key, it hashes the key and takes the result modulo the partition count, so every event with the same key lands on the same partition, and is read in the order it was written. This client hashes keys with murmur2, a fast non-cryptographic hash, and it is the same function the Java client uses, so a Java and a Node producer agree on where a key goes. Without a key, the producer spreads events across partitions.

For Aurora's billing, the order that matters is per order: paid must not be processed after shipped. Keying by order id gives exactly that, and nothing more. Events of different orders interleave freely, which is fine, because nothing depends on their relative order.

On the left, three lanes, each holding tiles of a single color in the same repeating sequence of shapes; on the right, the same tiles scattered across all three lanes, with a warning sign over a triangle that broke its sequence

To see what the key buys, I ran a single consumer, so that every event of every order passed through the same process and its out-of-order count was a fair check, against 3,000 orders produced with and without a key. Each producer ran in two situations: with the consumer keeping up live, and with the consumer started only after checkout had finished, which is what happens after an outage or a slow deploy. Every run started from a fresh broker.

# live: the consumer is already running while checkout produces
docker compose up -d --scale billing=1 billing
sleep 8
docker compose run --rm -e KEYED=false tools node src/produce-orders.ts
sleep 4
docker compose stop billing

# catching up: checkout produces first, the consumer starts afterwards
docker compose run --rm -e KEYED=false tools node src/produce-orders.ts
docker compose up -d --scale billing=1 billing
sleep 15
docker compose stop billing
Enter fullscreen mode Exit fullscreen mode

The keyed runs are the same commands without -e KEYED=false.

Producer Consumer Events processed Out of order
Producer Consumer Events processed Out of order
--- --- --- ---
keyed by order id live 9,000 0
keyed by order id catching up 9,000 0
no key live 9,000 0
no key catching up 9,000 3,845

Assembled from the last line each consumer printed, which follows in the same order.

billing-1  | left the group: 9000 events processed, 0 out of order
billing-1  | left the group: 9000 events processed, 0 out of order
billing-1  | left the group: 9000 events processed, 0 out of order
billing-1  | left the group: 9000 events processed, 3845 out of order
Enter fullscreen mode Exit fullscreen mode

Without a key, with the consumer keeping up, the check found nothing. An order's three events were 50 ms apart, and the consumer was never more than a few tens of milliseconds behind, so each event was processed before the next one existed, whatever partition it landed on. That is the dangerous part: a missing key passes every test that runs against a consumer that keeps up.

Catching up, the same producer gave 3,845 of 9,000 events out of order, 43%. A consumer with a backlog fetches events from each partition in batches, so a run of one partition's events is processed before the next partition's, and an order's shipped, early in one batch, comes before its paid, later in another. Keyed, the same backlog had none, because all three events of an order sat in one partition, in the order checkout wrote them.

Adding partitions moves keys

The key goes to hash(key) % partitionCount. Change the partition count and the same key can land on a different partition. Kafka lets you add partitions to a live topic, and it does not move the events already written, so for a while an order's placed sits in one partition and its paid in another.

I sent one event for each of the same 1,000 order ids three times: once to set a baseline, once more with nothing changed as a control, and once after growing orders from three partitions to six:

docker compose run --rm -T tools node src/where-keys-land.ts > before.json
docker compose run --rm -T tools node src/where-keys-land.ts --compare < before.json > again.json
docker compose exec kafka /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:19092 \
  --alter --topic orders --partitions 6
docker compose run --rm -T tools node src/where-keys-land.ts --compare < before.json > after.json
Enter fullscreen mode Exit fullscreen mode

The script writes the key-to-partition map on standard output, so it lands in a file on your machine with no volume to mount, and prints its summary on standard error.

What the three runs printed on standard error, in order; the --alter printed nothing. The warning at the top shows up on the first producer after a fresh broker starts, while the broker is still loading the coordinator that hands out producer ids, and the client retries on its own:

{
  message: '[thrd:main]: Failed to acquire idempotence PID from broker kafka:19092/1: Broker: Coordinator load in progress: retrying',
  fac: 'GETPID',
  timestamp: 1795186284601,
  name: 'checkout#producer-1'
}
1000 keys over 3 partitions: p0=341 p1=317 p2=342
1000 keys over 3 partitions: p0=341 p1=317 p2=342
0 of 1000 keys land on a different partition than in the earlier run
1000 keys over 6 partitions: p0=172 p1=170 p2=155 p3=169 p4=147 p5=187
503 of 1000 keys land on a different partition than in the earlier run
Enter fullscreen mode Exit fullscreen mode

The control moved nothing: the hash is deterministic, so the same key goes to the same partition every time the count stays put. After the change, 503 of 1,000 keys moved, about half, which is what the arithmetic predicts. A key whose hash leaves a remainder of 1 when divided by 6 also leaves 1 when divided by 3, so it stays on partition 1. A key whose hash leaves 4 divided by 6 left 1 divided by 3, so it moves from partition 1 to partition 4. Remainders 0, 1 and 2 stay and 3, 4 and 5 move: half of all keys. The --alter command itself printed nothing, no warning and no confirmation.

For half of Aurora's orders, then, any order in progress during the change has its first events in one partition and the rest in another. Two partitions can be read by two different consumers at two different speeds, and nothing stops shipped from overtaking paid.

If a topic's partition count may ever need to grow and per-key order matters, the usual way out is a new topic with more partitions, with producers switched over once the consumers have drained the old one. It is a migration, which is the reason to pick a generous number at the start.

Rebalances: the group stops to hand out partitions

When a member joins or leaves, the partitions have to be divided again. That is a rebalance, and while it runs, the partitions that are changing hands have no reader.

Every member of a group sends the broker a small "still here" message every few seconds, a heartbeat. Heartbeats are how the group notices a member is gone, and also how members hear that a rebalance has started. Two decisions shape what a rebalance costs: the protocol, meaning who runs it, and, in the classic protocol, the assignor, meaning the rule that decides which member gets which partition. This client speaks both protocols:

  • The classic protocol. The members run the rebalance themselves: one of them, the leader, computes the new assignment and the broker passes it on. With an eager assignor (range or roundrobin, this client's default), every member first gives up all its partitions, then the leader hands all of them out again. With cooperative-sticky, it takes two rounds: in the first, members give up only the partitions that will move; in the second, those are handed to their new owners. Every other partition keeps its reader throughout.
  • The consumer protocol, generally available since Kafka 4.0 (the design is KIP-848). The broker computes the assignment, and each member learns what to give up or take in the reply to its regular heartbeat. Only the partitions that move stop, and no member waits for the others.

A third consumer joins

Two consumers shared the three partitions under a steady 600 events per second, and 15 seconds in, a third one joined. GROUP_PROTOCOL and ASSIGNOR pick the protocol through compose.yaml:

# one of these three, on a fresh broker with the topic created
docker compose up -d --scale billing=2 billing                                                  # consumer protocol
GROUP_PROTOCOL=classic docker compose up -d --scale billing=2 billing                           # classic, eager
GROUP_PROTOCOL=classic ASSIGNOR=cooperative-sticky docker compose up -d --scale billing=2 billing  # classic, cooperative

sleep 10
docker compose run --rm -e ORDERS=9000 -e RATE=200 tools node src/produce-orders.ts &
sleep 15
docker compose up -d --scale billing=3 --no-recreate billing   # same variables as the first command
Enter fullscreen mode Exit fullscreen mode

I ran each protocol three times. The table gives, for each run, the worst max wait in the 14 seconds after the new member subscribed: how long the partitions that changed hands went unread.

Protocol What changed hands Worst wait, 3 runs
classic, eager (roundrobin, this client's default) every partition 121, 50, 87 ms
classic, cooperative-sticky 1 partition 3,133, 3,112, 3,297 ms
consumer 1 partition 4,356, 398, 2,994 ms

Assembled from the consumers' per-second lines. Two of the runs follow, cut to the seconds around the handover.

The consumer protocol, run 1. billing-2 gives up partition 1 a moment after billing-3 appears, and billing-3 gets it about four and a half seconds later, with that much of partition 1's events waiting for it:

billing-1  | 14:54:04.036  partitions 2  processed 195  max wait 88 ms  out of order 0
billing-2  | 14:54:04.568  partitions 0,1  processed 399  max wait 27 ms  out of order 0
billing-1  | 14:54:05.037  partitions 2  processed 209  max wait 29 ms  out of order 0
billing-3  | 14:54:05.174  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 14:54:05.568  partitions 0  processed 254  max wait 163 ms  out of order 0
billing-1  | 14:54:06.037  partitions 2  processed 207  max wait 23 ms  out of order 0
billing-3  | 14:54:06.174  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 14:54:06.568  partitions 0  processed 228  max wait 25 ms  out of order 0
billing-1  | 14:54:07.037  partitions 2  processed 181  max wait 24 ms  out of order 0
billing-3  | 14:54:07.175  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 14:54:07.571  partitions 0  processed 168  max wait 36 ms  out of order 0
billing-1  | 14:54:08.037  partitions 2  processed 204  max wait 60 ms  out of order 0
billing-3  | 14:54:08.176  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 14:54:08.571  partitions 0  processed 203  max wait 94 ms  out of order 0
billing-1  | 14:54:09.038  partitions 2  processed 174  max wait 96 ms  out of order 0
billing-3  | 14:54:09.177  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 14:54:09.571  partitions 0  processed 223  max wait 44 ms  out of order 0
billing-1  | 14:54:10.038  partitions 2  processed 184  max wait 48 ms  out of order 0
billing-3  | 14:54:10.188  partitions 1  processed 1117  max wait 4356 ms  out of order 7
billing-2  | 14:54:10.572  partitions 0  processed 177  max wait 41 ms  out of order 0
billing-1  | 14:54:11.039  partitions 2  processed 198  max wait 41 ms  out of order 0
billing-3  | 14:54:11.189  partitions 1  processed 195  max wait 37 ms  out of order 7
Enter fullscreen mode Exit fullscreen mode

The classic eager protocol, run 2. One second after billing-3 appears, every member owns a different partition than before, and all three out of order counters jump. In the other two runs, round-robin happened to hand two of the partitions back to their previous owners:

billing-2  | 15:00:17.777  partitions 0,2  processed 374  max wait 35 ms  out of order 0
billing-1  | 15:00:18.355  partitions 1  processed 172  max wait 22 ms  out of order 0
billing-3  | 15:00:18.656  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 15:00:18.777  partitions 0,2  processed 428  max wait 28 ms  out of order 0
billing-1  | 15:00:19.355  partitions 1  processed 218  max wait 14 ms  out of order 0
billing-3  | 15:00:19.656  partitions -  processed 0  max wait 0 ms  out of order 0
billing-2  | 15:00:19.777  partitions 0,2  processed 386  max wait 23 ms  out of order 0
billing-1  | 15:00:20.355  partitions 2  processed 226  max wait 11 ms  out of order 0
billing-3  | 15:00:20.657  partitions 0  processed 84  max wait 33 ms  out of order 11
billing-2  | 15:00:20.777  partitions 1  processed 291  max wait 32 ms  out of order 6
billing-1  | 15:00:21.355  partitions 2  processed 193  max wait 31 ms  out of order 6
billing-3  | 15:00:21.657  partitions 0  processed 143  max wait 11 ms  out of order 11
billing-2  | 15:00:21.777  partitions 1  processed 230  max wait 10 ms  out of order 6
Enter fullscreen mode Exit fullscreen mode

The result surprised me, and it is worth reading slowly. In this lab the eager rebalance was the fastest. Every partition was given up and handed out again, and the worst waits stayed within the range max wait covers when nothing moves at all (11 to 205 ms in these runs), so the stop, if there was one, was too short to tell apart from normal jitter. The incremental protocols never stopped the other partitions, but the one that moved sat unread for about three seconds with cooperative-sticky and anywhere from under half a second to four and a half with the consumer protocol.

The gaps have plain causes. cooperative-sticky needs its two rounds, and members hear about each round in a heartbeat reply, three seconds apart by default. The consumer protocol hands a partition over through heartbeats too, every five seconds by default on the broker (group.consumer.heartbeat.interval.ms), so the wait depends on where in that cycle the new member lands.

Nothing was lost or processed twice in any of the nine runs as far as the counts can tell: the three consumers' totals added up to the 27,000 events checkout produced every time. That fits how the client works: with auto-commit on, librdkafka commits the offsets of every partition it gives up, so the next owner starts where the last one stopped.

The out of order counter in both excerpts is not Kafka reordering anything. Each consumer tracks an order's progress in its own memory, and that memory does not travel with the partition. When billing-3 took over a partition, the first events it read included the paid and shipped of orders whose placed the previous owner had already processed, so from where billing-3 stood they had skipped a step. Any per-key state you keep in a consumer's memory (a running total, a deduplication cache, a state machine) has the same problem after every rebalance: the new owner starts empty. Keep it in a database, or rebuild it from the topic.

So why opt into the consumer protocol, if eager won here? Because eager's costs do not show up in a lab with three members and handlers that take microseconds. An eager rebalance cannot finish until every member has given up all its partitions and rejoined, so the whole group waits for the slowest member, up to the rebalance timeout, which this client sets to ten minutes (it doubles max.poll.interval.ms). Every partition changes owner every time, so every member's in-memory state is thrown away, as the out of order counts above show. And a rolling deploy of 50 members means a leave and a join per member: 100 rebalances, each of which stops everyone. The consumer protocol removes all three, and charges one thing in exchange: a partition that moves waits for a heartbeat or two.

A consumer leaves: SIGTERM versus SIGKILL

A member that shuts down cleanly tells the group it is leaving, and its partitions are reassigned at once. A member that is killed tells nobody. The group finds out only when its heartbeats have been missing for a full session timeout.

Three conveyor lanes: robots work the first two, while the third lane's station stands unattended and its pieces pile up next to two hourglasses, as a spare robot raises its arm, ready to take over

Three consumers, checkout producing 16,000 orders (48,000 events) at 200 orders a second, and 15 seconds in, billing-3 leaves: either with docker stop, which sends SIGTERM, or with docker kill, which sends SIGKILL. Its partition's new owner is visible in the per-second lines, so the time with no reader is measured from the moment billing-3 left to the first line in which another member lists that partition:

docker compose up -d --scale billing=3 billing     # GROUP_PROTOCOL=classic in front for the classic rows
sleep 10
docker compose run --rm -e ORDERS=16000 -e RATE=200 tools node src/produce-orders.ts &
sleep 15
docker stop aurora-kafka-billing-3                 # or: docker kill aurora-kafka-billing-3
Enter fullscreen mode Exit fullscreen mode
Protocol How billing-3 left Its partition unread for Oldest event the new owner processed Processed twice
consumer docker stop, 3 runs at most 1.4 s 1.36, 0.87, 0.35 s 0
consumer docker kill, 2 runs 44–48 s, 45–49 s 48.8, 49.2 s at least 484, at least 283
classic, eager docker stop, 2 runs at most 1.4 s 1.37, 1.01 s 0
classic, eager docker kill, 1 run 28–31 s 32.5 s at least 440

Assembled from the consumers' lines and the totals they printed when they left the group. The first kill under the consumer protocol follows, cut around the seconds in which partition 1 had no reader.

billing-3  | 15:18:46.089  partitions 1  processed 244  max wait 72 ms  out of order 0
billing-2  | 15:18:46.251  partitions 0  processed 223  max wait 58 ms  out of order 0
billing-1  | 15:18:46.478  partitions 2  processed 190  max wait 48 ms  out of order 0
billing-3  | 15:18:47.089  partitions 1  processed 183  max wait 80 ms  out of order 0
billing-2  | 15:18:47.251  partitions 0  processed 209  max wait 103 ms  out of order 0
billing-1  | 15:18:47.478  partitions 2  processed 201  max wait 87 ms  out of order 0
billing-2  | 15:18:48.251  partitions 0  processed 208  max wait 96 ms  out of order 0
billing-1  | 15:18:48.479  partitions 2  processed 205  max wait 151 ms  out of order 0
…
billing-2  | 15:19:32.303  partitions 0  processed 223  max wait 189 ms  out of order 0
billing-1  | 15:19:32.509  partitions 2  processed 208  max wait 181 ms  out of order 0
billing-1  | 15:19:33.513  partitions 2  processed 184  max wait 53 ms  out of order 0
billing-1  | 15:19:34.524  partitions 2  processed 214  max wait 138 ms  out of order 0
billing-2  | 15:19:34.756  partitions 0,1  processed 9815  max wait 48815 ms  out of order 8
billing-1  | 15:19:35.523  partitions 2  processed 227  max wait 54 ms  out of order 0
billing-2  | 15:19:35.758  partitions 0,1  processed 989  max wait 1781 ms  out of order 8
Enter fullscreen mode Exit fullscreen mode

With SIGTERM, both protocols handed the partition over within a second and a half. Every run's totals came to exactly 48,000, and the group's lag was 0 on all three partitions afterwards: billing-3 finished the event in hand, committed and left, and its successor started exactly where it stopped.

With SIGKILL, the partition sat unread for about a session timeout: 44 to 49 seconds under the consumer protocol, whose broker default is 45 seconds, and 28 to 31 under the classic one, which this client sets to 30. The ranges are a few seconds wide because they come from per-second lines: from the last line billing-3 printed to the first line in which another member owns its partition. Meanwhile the partition's events piled up, and when billing-2 finally took it, it worked through 9,815 of them in one second.

The kill cost one more thing. billing-3 died holding events it had processed but not yet committed (this client commits every five seconds), so its successor started from the last committed offset and processed them again. That is why the oldest event the new owner processed had waited 48.8 seconds, longer than the gap itself, and why the three consumers processed at least 484 events more than the 48,000 checkout produced. This is at-least-once delivery: Kafka will not skip an event a group has not committed, and in exchange some events arrive twice. Part 2 is about living with that.

An unclean exit leaves its partitions unread for most of a session timeout, and that is the number in this article worth remembering. Out-of-memory kills, docker kill, a machine that loses power and a Kubernetes pod that ignores SIGTERM until its grace period runs out all look the same to Kafka. Handle the signal, call disconnect(), and give the process enough grace period to finish it.

Can you lower the timeout? Under the consumer protocol it is the broker's setting, not the client's: group.consumer.session.timeout.ms is 45 seconds, and on this broker the floor, group.consumer.min.session.timeout.ms, is 45 seconds as well, so no group gets less without a broker change. The classic protocol lets each client choose, down to the broker's group.min.session.timeout.ms, 6 seconds here. Either way the trade is the same: a shorter timeout notices a dead member sooner, and also evicts a live one that stalls for a moment, a long garbage-collection pause or a slow network, and each eviction is another rebalance.

When Kafka is overkill

Kafka earns its keep when the log itself is the point:

  • Several independent consumers of the same events, each at its own pace: billing, analytics, a fraud model, a search index.
  • Replay: a new service backfills from history, or a bug fix reprocesses last Tuesday.
  • Per-key ordering at high throughput, spread over many partitions and consumers.
  • High, sustained volume, where a log's sequential writes and batched reads matter.

It is overkill, or the wrong shape, when:

  • The work is a job queue. Per-message acknowledgement, retries with delay, priorities, dead-lettering and routing by pattern are what RabbitMQ is built for; Part 1 of the RabbitMQ series covers them. Share groups bring some of this to Kafka, but not to Node yet.
  • Volume is low and nobody needs replay. A RabbitMQ queue, or a table in the Postgres you already run, is less to operate.
  • You need request and reply. Kafka can carry it, but you build correlation and timeouts yourself.

Running Kafka got simpler with KRaft, and there is still more to it than a queue: partition counts, retention, consumer lag and rebalances become yours to watch. If your team would rather not, the managed options (Confluent Cloud, Amazon MSK, Azure Event Hubs with its Kafka endpoint) take the broker off your hands. The partitioning, ordering and rebalance rules in this article still apply to every one of them.

Key takeaways

  • A topic is a log. Reading does not delete. Each consumer group keeps its own offset per partition, and retention, not consumption, decides when data goes away.
  • The partition count caps a group's parallelism. Five consumers on three partitions left two idle for the whole run. Choose the count up front, with room to grow.
  • Order is per partition, so key by the thing whose order matters. Unkeyed events passed the live test with none out of order and failed on catch-up with 3,845 of 9,000. Growing a topic from three to six partitions moved 503 of 1,000 keys.
  • Shut consumers down gracefully. A killed consumer's partition went unread for about 45 seconds and at least 484 events were processed twice; one stopped with SIGTERM handed its partition over within about a second and a half, and the totals matched what was produced.
  • The consumer protocol is opt-in on the client. The broker has had it on since Kafka 4.0; group.protocol: 'consumer' turns it on. It keeps every partition that is not moving at work during a rebalance, and a partition that moves waits up to a heartbeat interval, five seconds by default.

Next in the series: Kafka from Fundamentals to Production, Part 2: Building a Real Event Streaming Platform, on offsets you commit yourself, what happens to the events in flight during a rebalance, delivery guarantees from at-least-once to exactly-once, and a failure that stops a partition rather than skipping an event.

Appendix: the stack and the helper scripts

compose.yaml
# compose.yaml
name: aurora-kafka

services:
  kafka:
    image: apache/kafka:4.4.0
    hostname: kafka
    ports:
      - "127.0.0.1:9092:9092"   # clients on this machine only: localhost:9092
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller   # KRaft: no ZooKeeper
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_LISTENERS: INTERNAL://:19092,HOST://:9092,CONTROLLER://:9093
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:19092,HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false"
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      # One broker, so every internal topic gets one replica.
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR: 1
    healthcheck:
      test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server kafka:19092 > /dev/null 2>&1"]
      interval: 5s
      timeout: 10s
      retries: 24

  billing:
    build: .
    image: aurora-kafka-lab
    init: true
    command: ["node", "src/billing-consumer.ts"]
    environment:
      KAFKA_BROKERS: kafka:19092
      CLIENT_ID: billing
      GROUP_ID: billing
      GROUP_PROTOCOL: ${GROUP_PROTOCOL:-consumer}
      ASSIGNOR: ${ASSIGNOR:-}
    depends_on:
      kafka:
        condition: service_healthy

  tools:
    build: .
    image: aurora-kafka-lab
    init: true
    profiles: ["tools"]
    environment:
      KAFKA_BROKERS: kafka:19092
      CLIENT_ID: checkout
    depends_on:
      kafka:
        condition: service_healthy
Enter fullscreen mode Exit fullscreen mode

Dockerfile
# Dockerfile
FROM node:24-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src
USER node
Enter fullscreen mode Exit fullscreen mode

package.json
{
  "name": "aurora-kafka",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24" },
  "dependencies": {
    "@confluentinc/kafka-javascript": "1.11.0"
  },
  "devDependencies": {
    "@types/node": "24.19.2",
    "typescript": "7.0.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

src/create-topic.ts
// src/create-topic.ts: creates the orders topic with a fixed number of partitions.
import { kafka, TOPIC } from './kafka.ts';

const partitions = Number(process.argv[2] ?? 3);
// One copy of each partition is all a one-broker lab can hold. On a real cluster use 3.
const replicationFactor = Number(process.argv[3] ?? 1);
for (const [name, value] of [['partition count', partitions], ['replication factor', replicationFactor]] as const) {
  if (!Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer, got ${value}`);
}

const admin = kafka.admin();
await admin.connect();
try {
  const created = await admin.createTopics({
    topics: [{ topic: TOPIC, numPartitions: partitions, replicationFactor }],
  });
  console.log(created
    ? `created "${TOPIC}" with ${partitions} partitions`
    : `"${TOPIC}" already exists; partition count left as it was`);
} finally {
  await admin.disconnect();
}
Enter fullscreen mode Exit fullscreen mode

src/describe-group.ts
// src/describe-group.ts: which member owns which partition, and how far behind each partition is.
import { kafka, TOPIC } from './kafka.ts';

const groupId = process.argv[2] ?? 'billing';
const STATES = ['unknown', 'preparing rebalance', 'completing rebalance', 'stable', 'dead', 'empty'];
const TYPES = ['unknown', 'consumer', 'classic'];

const admin = kafka.admin();
await admin.connect();
try {
  const { groups: [group] } = await admin.describeGroups([groupId]);
  if (group === undefined || group.error) throw new Error(`cannot describe ${groupId}: ${group?.error?.message}`);
  console.log(`group ${groupId}: ${STATES[group.state]}, ${TYPES[group.type]} protocol, ${group.members.length} members`);
  for (const member of group.members) {
    const owned = member.assignment.topicPartitions
      .filter(({ topic }) => topic === TOPIC)
      .map(({ partition }) => partition)
      .sort((a, b) => a - b);
    console.log(`  member ${member.memberId.slice(-8)}  partitions ${owned.length > 0 ? owned.join(',') : 'none'}`);
  }

  const [committed] = await admin.fetchOffsets({ groupId, topics: [TOPIC] });
  const ends = await admin.fetchTopicOffsets(TOPIC);
  for (const { partition, high } of ends.sort((a, b) => a.partition - b.partition)) {
    const offset = committed?.partitions.find((p) => p.partition === partition)?.offset ?? '-1';
    const done = Number(offset) < 0 ? 0 : Number(offset);
    console.log(`  partition ${partition}  committed ${done}  end ${high}  lag ${Number(high) - done}`);
  }
} finally {
  await admin.disconnect();
}
Enter fullscreen mode Exit fullscreen mode

src/where-keys-land.ts
// src/where-keys-land.ts: sends one event for each of 1,000 fixed order ids and prints, as JSON on stdout,
// the partition each one landed on. With --compare, it reads an earlier run's JSON from stdin and
// reports on stderr how many keys moved.
import { text } from 'node:stream/consumers';
import { kafka, TOPIC, type OrderEvent } from './kafka.ts';

const compare = process.argv.includes('--compare');
const previous = compare ? (JSON.parse(await text(process.stdin)) as Record<string, number>) : null;

const keys = Array.from({ length: 1_000 }, (_, i) => `ord-key-${String(i).padStart(4, '0')}`);
const producer = kafka.producer({ kafkaJS: { idempotent: true } });
await producer.connect();

const landed: Record<string, number> = {};
try {
  await Promise.all(keys.map(async (orderId) => {
    const event: OrderEvent = { orderId, type: 'placed', seq: 1, totalCents: 1_000, producedAt: Date.now() };
    const [metadata] = await producer.send({ topic: TOPIC, messages: [{ key: orderId, value: JSON.stringify(event) }] });
    if (metadata === undefined) throw new Error(`no delivery report for ${orderId}`);
    landed[orderId] = metadata.partition;
  }));
} finally {
  await producer.disconnect();
}
process.stdout.write(`${JSON.stringify(landed)}\n`);

const perPartition = new Map<number, number>();
for (const partition of Object.values(landed)) perPartition.set(partition, (perPartition.get(partition) ?? 0) + 1);
const spread = [...perPartition].sort(([a], [b]) => a - b).map(([p, n]) => `p${p}=${n}`).join(' ');
console.error(`${keys.length} keys over ${perPartition.size} partitions: ${spread}`);

if (previous !== null) {
  const moved = keys.filter((key) => previous[key] !== landed[key]).length;
  console.error(`${moved} of ${keys.length} keys land on a different partition than in the earlier run`);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)