DEV Community

Cover image for Kafka from Fundamentals to Production, Part 2: Building a Real Event Streaming Platform
Juan Gómez
Juan Gómez

Posted on

Kafka from Fundamentals to Production, Part 2: Building a Real Event Streaming Platform

Kafka from Fundamentals to Production, Part 2: Building a Real Event Streaming Platform

I switched off auto-commit on a Kafka consumer to decide for myself when offsets get committed, and the first clean shutdown invoiced 206 orders twice. Not a crash: a plain SIGTERM, the kind every deploy sends.

My code did what I wrote. It committed after every 1,000 events, always after the invoice was written. What I had switched off was a commit I never knew was happening: auto-commit also commits whenever the consumer is about to lose a partition, on a rebalance or on shutdown. With it left on, the same stop produced zero duplicates.

That is what this part is about. Every delivery guarantee in Kafka comes down to when the offset is committed relative to the work, and every mechanism that commits for you also commits at moments you do not see. This post measures each of them on an invoicing service: the producer's retries, auto-commit, committing yourself, transactions for exactly-once, and an event that can never be processed. Kafka 4.4 and Node 24, on the same coffee shop as Part 1.

A robot stamps numbered tiles from a conveyor into checked invoices, while translucent helper robots move a bookmark flag along the belt and drop it into a box with a handover arrow

Where Part 1 left off

Part 1 ended with a consumer killed with SIGKILL. Its partition went unread for about 45 seconds, and when another member took it over, at least 484 events were processed a second time. For a consumer that only counts events, that is a number in a log. For one that sends invoices, it is 484 customers billed twice.

A consumer group stores one committed offset per partition: "everything before this position is done". Whether an event can be lost, or processed twice, depends only on when that offset moves compared with when the work happens:

  • At-most-once: commit first, then do the work. A crash between the two loses the event.
  • At-least-once: do the work, then commit. A crash between the two repeats it.
  • Exactly-once: do the work and commit in one step, so a crash undoes both. Kafka can do that only when the work itself is a write to Kafka.

Part 1's consumer was at-least-once, which is the right default. The rest of this post is about which events come back twice, when, and what it costs to make that number zero.

The lab

The stack is Part 1's: one Kafka 4.4.0 broker in KRaft mode (no ZooKeeper), Node 24 in node:24-alpine, and Confluent's @confluentinc/kafka-javascript 1.11.0, all in Docker Compose. That client wraps librdkafka 2.16.0, Confluent's C client library, behind a KafkaJS-compatible API. The appendix has every file. Three things are new:

  • A second topic, invoices, with three partitions, keyed by order id.
  • The invoicer: a consumer group, invoicer, that reads orders and writes one invoice to invoices for every paid event.
  • count-invoices.ts, which reads both topics from the beginning under a brand-new group and reports, for every paid order, whether it was invoiced once, more than once, or never. Every duplicate count in this post is its output.

Checkout is Part 1's producer: 16,000 orders at 200 a second, three events each, so 48,000 events over 80 seconds, each keyed by its order id. One run looks like this:

docker compose up -d kafka
docker compose run --rm tools node src/create-topic.ts orders 3
docker compose run --rm tools node src/create-topic.ts invoices 3
docker compose up -d --scale invoicer=3 invoicer
docker compose run --rm -e ORDERS=16000 -e RATE=200 tools node src/produce-orders.ts
docker compose run --rm tools node src/count-invoices.ts
docker compose down -v   # -v also removes the three anonymous volumes the Kafka image declares
Enter fullscreen mode Exit fullscreen mode

Docker Compose prints its own progress lines around every command; they are left out of the output below.

Here is the invoicer. It is long because it can commit two ways, and everything about committing yourself only matters for that section:

// src/invoicer.ts: one member of the invoicer group. Writes one invoice for every paid order.
import { KafkaJS } from '@confluentinc/kafka-javascript';
import { INVOICES, kafka, TOPIC, toInvoice, type Invoice } from './kafka.ts';

const CLIENT_ID = process.env.CLIENT_ID ?? 'invoicer';
// Unset: the client commits for us. A number N: we commit ourselves, after every N events of a partition.
const COMMIT_EVERY = process.env.COMMIT_EVERY ? Number(process.env.COMMIT_EVERY) : null;
if (COMMIT_EVERY !== null && (!Number.isInteger(COMMIT_EVERY) || COMMIT_EVERY < 1)) {
  throw new Error(`COMMIT_EVERY must be a positive integer, got ${process.env.COMMIT_EVERY}`);
}

// Each send is awaited, so there is never a batch to wait for: send at once instead of after linger.ms.
const producer = kafka.producer({ 'linger.ms': 0, kafkaJS: { idempotent: true } });

let stopping = false; // set once shutdown begins

// Only used when we commit ourselves.
const nextOffset = new Map<number, string>(); // partition -> offset after the last event processed
const sinceCommit = new Map<number, number>(); // partition -> events processed since its last commit

async function commit(partitions: number[]): Promise<void> {
  const offsets = partitions.flatMap((partition) => {
    const offset = nextOffset.get(partition);
    return offset === undefined ? [] : [{ topic: TOPIC, partition, offset }];
  });
  if (offsets.length > 0) await consumer.commitOffsets(offsets);
  for (const partition of partitions) sinceCommit.set(partition, 0);
}

type Revoked = { code: number };
type Assignment = { topic: string; partition: number }[];

const consumer = kafka.consumer({
  kafkaJS: {
    groupId: 'invoicer',
    fromBeginning: true,
    allowAutoTopicCreation: false,
    autoCommit: COMMIT_EVERY === null,
  },
  'group.protocol': 'consumer',
  // Runs when partitions are assigned or taken away. Returning nothing keeps the default handling.
  rebalance_cb: async (event: Revoked, assignment: Assignment, fns: { assignmentLost: () => boolean }) => {
    if (COMMIT_EVERY === null || event.code !== KafkaJS.ErrorCodes.ERR__REVOKE_PARTITIONS) return;
    const partitions = assignment.map(({ partition }) => partition);
    try {
      // Commit what was processed before the partitions go, or their next owner processes it again.
      // A lost assignment (this member was evicted) cannot commit: its successor has already started.
      // Shutting down, shutdown() has already committed, and disconnect() would refuse this commit.
      if (!fns.assignmentLost() && !stopping) await commit(partitions);
    } catch (error) {
      console.error(`commit on revoke failed, the next owner repeats what it missed: ${String(error)}`);
    } finally {
      for (const partition of partitions) {
        nextOffset.delete(partition);
        sinceCommit.delete(partition);
      }
    }
  },
});

let processed = 0;
let invoiced = 0;
let failed = 0;
let totalInvoiced = 0;

async function handle({ partition, message }: KafkaJS.EachMessagePayload): Promise<void> {
  let invoice: Invoice | null;
  try {
    invoice = toInvoice(message.value, CLIENT_ID);
  } catch (error) {
    failed++;
    throw error; // the client seeks back to this event and delivers it again
  }
  if (invoice !== null) {
    // Awaited: the client stores this event's offset only after eachMessage resolves.
    await producer.send({ topic: INVOICES, messages: [{ key: invoice.orderId, value: JSON.stringify(invoice) }] });
    invoiced++;
    totalInvoiced++;
  }
  processed++;

  if (COMMIT_EVERY !== null) {
    nextOffset.set(partition, String(Number(message.offset) + 1));
    const pending = (sinceCommit.get(partition) ?? 0) + 1;
    sinceCommit.set(partition, pending);
    if (pending >= COMMIT_EVERY) {
      try {
        await commit([partition]);
      } catch (error) {
        // Only local errors land here (the commit is queued, not acknowledged); failing the event would invoice it again.
        console.error(`partition ${partition}: commit failed, retrying after the next event: ${String(error)}`);
      }
    }
  }
}

await producer.connect();
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}  invoiced ${invoiced}` + (failed > 0 ? `  failed ${failed}` : ''),
  );
  processed = 0;
  invoiced = 0;
  failed = 0;
}, 1_000);

// A count alone never commits the last events of a partition that goes quiet: commit those every 5 s as well.
const committer = COMMIT_EVERY === null ? undefined : setInterval(() => {
  const pending = [...sinceCommit].filter(([, events]) => events > 0).map(([partition]) => partition);
  commit(pending).catch((error: unknown) => console.error(`timed commit failed, retrying in 5 s: ${String(error)}`));
}, 5_000);

let current: Promise<void> = Promise.resolve(); // the event being processed, if any
await consumer.run({
  eachMessage: async (payload) => {
    current = handle(payload);
    await current;
  },
});

async function shutdown(signal: NodeJS.Signals): Promise<void> {
  if (stopping) return;
  stopping = true;
  clearInterval(ticker);
  clearInterval(committer);
  console.log(`${signal}: finishing the current event, committing, leaving the group`);
  try {
    if (COMMIT_EVERY !== null) {
      // disconnect() refuses commits once it starts, so stop fetching, let the event in hand finish,
      // and commit before leaving.
      consumer.pause([{ topic: TOPIC }]);
      await current.catch(() => undefined);
      await commit([...nextOffset.keys()]);
    }
    await consumer.disconnect(); // waits for an event still in eachMessage
    await producer.disconnect();
    console.log(`left the group: ${totalInvoiced} invoices written`);
    process.exit(0);
  } catch (error) {
    console.error('shutdown failed:', error);
    process.exit(1);
  }
}
process.once('SIGTERM', () => void shutdown('SIGTERM'));
process.once('SIGINT', () => void shutdown('SIGINT'));
Enter fullscreen mode Exit fullscreen mode

What matters before the first experiment:

  • Each invoice is sent with await, inside eachMessage, the function the client calls with each event. Why that matters is the subject of the auto-commit section. linger.ms: 0 follows from it: the producer normally waits up to 5 ms to batch messages together, and a send that is awaited one at a time has nothing to batch with.
  • idempotent: true is the next section.
  • 'group.protocol': 'consumer' is the newer group protocol, as in Part 1: the broker decides which member gets which partition.
  • COMMIT_EVERY, rebalance_cb, the committer timer and the if block at the top of shutdown() are for committing yourself. With COMMIT_EVERY unset, the client commits.
  • toInvoice, in kafka.ts, throws InvalidOrderError for an event it cannot read or a total that is not positive. Checkout never sends either; the last section does. The appendix has the file.

On the way in: the producer's retries

Duplicates can be written before any consumer is involved. A send is a request to the broker, and if no answer comes back in time, the client sends it again. When the first request did reach the broker and only the answer was lost, the retry writes a second copy.

To force that, checkout ran with a 2-second wait for the broker's answers instead of 30, and once events were flowing, the broker was frozen with docker pause for 8 seconds (8.3 to 10.7 on the host clock, which also counts the two docker commands):

docker compose run --rm -e ORDERS=3000 -e RATE=200 -e IDEMPOTENT=false -e SOCKET_TIMEOUT_MS=2000 tools node src/produce-orders.ts &
# once the topic holds 600 events:
docker pause aurora-kafka-kafka-1 && sleep 8 && docker unpause aurora-kafka-kafka-1
Enter fullscreen mode Exit fullscreen mode

Afterwards the whole topic was read back with Kafka's console consumer, and its lines counted:

Producer Events checkout sent Events in the topic Duplicates
idempotence off, run 1 9,000 9,004 4
idempotence off, run 2 9,000 9,006 6
idempotence on, 2 runs 9,000 9,000 0

Assembled from checkout's last line and the count of the topic read back: one row per run, except the last, which sums up two identical ones.

IDEMPOTENT and SOCKET_TIMEOUT_MS are two flags added to Part 1's produce-orders.ts for this run; the appendix has the file. The second sets librdkafka's socket.timeout.ms, how long the client waits for an answer before it gives up on a request and sends it again. The producer setting called request.timeout.ms looks like the right one, and is not: librdkafka's documentation says only the broker enforces it, so lowering it would not have made the client retry any sooner.

With idempotence on, the producer gets an id from the broker and numbers every batch it sends to each partition. A retried batch carries the same number, and the broker, which has already written that number, acknowledges it without writing it again. It also keeps one producer's events in the order they were sent, which a plain retry does not guarantee.

This client leaves idempotence off unless you ask for it. librdkafka defaults enable.idempotence to false; the Java client turns it on by default since Kafka 3.0.1, 3.1.1 and 3.2.0. Every producer in this post sets it, and so should yours.

Who commits, and when: auto-commit

Left alone, the invoicer commits through auto-commit, and the client's source says exactly what that means. It switches off librdkafka's own offset storing (enable.auto.offset.store: false), and stores an event's offset itself, in memory, only after your eachMessage resolves. Every 5 seconds librdkafka commits whatever is stored. And librdkafka also commits the stored offsets of a partition when the partition is taken away: on a rebalance, when the group hands its partitions out again, and on disconnect().

Two consequences follow:

  • Anything you do not await inside eachMessage is not covered. If the invoice were sent without await, the offset would be stored as soon as the function returned, and a crash before the send finished would lose that invoice with its offset already on the way to being committed. That is at-most-once, from one missing keyword.
  • A crash loses at most the last 5 seconds of commits, and every event processed in that window is processed again by the partition's next owner.

Three invoicers, checkout running, and 15 to 19 seconds in, invoicer-3 leaves in one of three ways: killed with docker kill (SIGKILL), stopped with docker stop (SIGTERM), or, in a group that starts with two members, a third one joins. Then the group drains, everything is stopped cleanly, and the invoices are counted:

What happened to invoicer-3 Orders invoiced twice Never invoiced
killed, 3 runs 5, 145, 250 0
stopped with SIGTERM 0 0
joined a group of two 0 0

Assembled from the count-invoices.ts lines of five runs. Two of them, the third kill and the stop:

read_committed: 16000 paid orders, 15750 invoiced once, 250 invoiced more than once (250 extra invoices), 0 never invoiced
read_committed: 16000 paid orders, 16000 invoiced once, 0 invoiced more than once (0 extra invoices), 0 never invoiced
Enter fullscreen mode Exit fullscreen mode

The kills spread from 5 to 250 because of where each one landed in the 5-second cycle. The first came right after a commit; the other two came about two and four seconds after one. At 200 orders a second over three partitions, one partition sees about 67 paid orders a second, so the worst case is roughly 330. Nothing was lost in any run: that is at-least-once doing its job.

The stop and the join produced no duplicates at all, and that is the commit you do not see. When invoicer-3 received SIGTERM, disconnect() gave its partition back, and librdkafka committed what was stored on the way out. When the third member joined, the member giving a partition up committed it the same way. Part 1 never saw a duplicate on a join for the same reason.

Committing yourself

The usual reason to turn auto-commit off is control. My first version of it was the invoicer above with COMMIT_EVERY=1000 and three pieces missing: the rebalance_cb option, the committer timer, and the if block at the top of shutdown(). It committed every 1,000 events per partition, always after the invoice was written, and nothing else:

What happened to invoicer-3 Orders invoiced twice
stopped with SIGTERM 206
joined a group of two 99

The stop, from both sides, invoicer-3 leaving and invoicer-1 taking its partition over:

invoicer-3  | 18:03:18.489  partitions 1  processed 209  invoiced 69
invoicer-3  | SIGTERM: finishing the current event, committing, leaving the group
invoicer-3  | left the group: 872 invoices written
invoicer-1  | 18:03:20.804  partitions 1,2  processed 244  invoiced 81
invoicer-1  | 18:03:21.803  partitions 1,2  processed 1201  invoiced 401
Enter fullscreen mode Exit fullscreen mode

Lines from the two containers' logs, in time order. The shutdown message is shared by every version of the file; this one commits nothing at that point.

invoicer-3 left having invoiced 872 orders from partition 1, about 2,600 events. Its last commit was at offset 2,000, after its second thousand, so about 600 events had been processed and never committed, and a third of those were paid orders. invoicer-1 started from 2,000 and invoiced them again: that is the second in which it processed 1,201 events. On the join, the member that gave a partition up did the same.

So committing yourself means taking over every moment when auto-commit committed: on a timer, when a partition is taken away, and on shutdown.

When a partition is taken away, the client calls rebalance_cb, if you give it one, with a code that says whether partitions are being assigned or revoked, the partitions, and a few helper functions. In the invoicer above, a revoke commits the processed offsets of the partitions that are going, unless the assignment was lost: a member that was evicted for missing its heartbeats can no longer commit, because its partitions already have a new owner. If that commit fails, the listener logs it and lets the partitions go anyway; the next owner repeats what was missed, which is at-least-once doing its job again.

On shutdown, the listener is not enough, and I found that one by measuring it. disconnect() takes the partitions away, so the listener runs, but by then the client refuses to commit. With the listener as I first wrote it, without the stopping check, the timer or the block in shutdown(), the stopped member logged this as it left:

invoicer-3  | SIGTERM: finishing the current event, committing, leaving the group
invoicer-3  | commit on revoke failed, the next owner repeats what it missed: KafkaJSError: Commit can only be called while connected.
invoicer-3  | left the group: 1026 invoices written
Enter fullscreen mode Exit fullscreen mode
Listener only, no commit in shutdown() Orders invoiced twice
stopped with SIGTERM 25
joined a group of two 0

The 25 is however far that partition had got past its last thousand; it could have been anything up to about 330.

So shutdown() pauses the topic, waits for the event in hand, and commits before calling disconnect(), and the listener skips its own commit once shutdown has begun.

On a timer is the moment I almost missed. A count of 1,000 events per partition is not a schedule: the last few hundred events before a partition goes quiet are never committed, however long it stays quiet. One invoicer committing every 1,000 events, after it had caught up on a backlog and sat idle for minutes:

group invoicer: stable, consumer protocol, 1 members
  member Qkmoj7XA  partitions 0,1,2
  partition 0  committed 29000  end 29937  lag 937
  partition 1  committed 30000  end 30399  lag 399
  partition 2  committed 29000  end 29664  lag 664
Enter fullscreen mode Exit fullscreen mode

Every event had been processed and invoiced, and the group still reported 2,000 events of lag, which an alert on lag would have read as a stuck consumer. A crash at that point would also have repeated all 2,000. So the file above also commits, every 5 seconds, any partition that has processed events since its last commit. With the timer, the same backlog ended at lag 0. With every piece in place, the same experiments:

Every 1,000 events, with listener, shutdown() commit and timer Orders invoiced twice Never invoiced
stopped with SIGTERM 0 0
joined a group of two 0 0
killed, 2 runs 2, 188 0

What is left is the crash. A kill still repeats everything since the last commit; at 200 events a second per partition, 1,000 events is the same 5 seconds auto-commit waits. Committing after every event (COMMIT_EVERY=1) should shrink that to the event in hand, and it does not, because of something this client does not say. await consumer.commitOffsets() resolves once librdkafka has queued the commit, not once the broker has accepted it: the native call underneath is commitAsync. Every commit still waiting in that queue when the process dies is lost with it, and two kills repeated 0 and 6 invoices. The same detail means the catch blocks around the commits only ever see local errors, like the refusal during disconnect() above; a commit the broker rejects is reported only as an offset.commit event on the client's internal consumer. Clean stops and rebalances are not affected: librdkafka waits for outstanding commits before it gives partitions up or closes, which is why every stop and join here came to zero.

The price is a commit request for every event, each queued behind the last. One invoicer catching up on a backlog of 30,000 orders (90,000 events), alone:

How the invoicer commits Time to process 90,000 events
auto-commit 22 s
every 1,000 events, with the timer 23 s
after every event 50 s

Assembled from each run's per-second lines, from the first one with events processed to the last. One run each, measured one after another on Docker Desktop on Windows. An earlier round of the same runs, made while the machine was short of memory, took 62, 50 and 91 seconds; the ratio between the last row and the others is the part that held.

A robot walks away from its lane of numbered tiles still holding its bookmark flag, while on the next belt another robot starts from an older flag and stamps tiles a second time, leaving duplicate invoices crossed out in red

None of these modes reaches zero after a crash. An event can always be invoiced and not yet committed. That gap is what transactions close.

Exactly-once: transactions

Every mode so far has the same hole: the invoice is written, then the offset is committed, and a crash between the two repeats the invoice. A Kafka transaction removes the "between". The invoices and the group's new offset are written as one unit, and either all of it becomes visible or none of it does.

It takes two halves:

  • The invoicer commits its offsets through the producer, inside the transaction, with sendOffsets, instead of through the consumer. Its consumer's auto-commit is off.
  • Whoever reads invoices uses read_committed isolation: it is shown only records from transactions that committed. Records from an aborted transaction stay in the log, and a read_committed reader skips them. This client defaults to read_committed; count-invoices.ts and the invoice-reader.ts in the appendix accept READ_UNCOMMITTED=true to see everything.

Here is the transactional invoicer:

// src/invoicer-tx.ts: the invoicer with transactions. A batch's invoices and the offset after it are
// committed together, or not at all.
import { hostname } from 'node:os';
import { KafkaJS } from '@confluentinc/kafka-javascript';
import { InvalidOrderError, INVOICES, kafka, TOPIC, toInvoice } from './kafka.ts';

const CLIENT_ID = process.env.CLIENT_ID ?? 'invoicer';
const DEAD_LETTER = 'orders.dlt';
// Must be unique among running instances, and the same when this instance restarts.
const TRANSACTIONAL_ID = process.env.TRANSACTIONAL_ID ?? `invoicer-${hostname()}`;

const producer = kafka.producer({ kafkaJS: { transactionalId: TRANSACTIONAL_ID, idempotent: true } });
const consumer = kafka.consumer({
  kafkaJS: {
    groupId: 'invoicer',
    fromBeginning: true,
    allowAutoTopicCreation: false,
    autoCommit: false, // the offsets travel inside each transaction instead
  },
  'group.protocol': 'consumer',
  // One transaction per batch, and each costs several round trips however few events it holds: this client's default batch is 32.
  'js.consumer.max.batch.size': 500,
});

let processed = 0;
let invoiced = 0;
let deadLettered = 0;
let transactions = 0;
let totalInvoiced = 0;

await producer.connect(); // registers TRANSACTIONAL_ID, aborting any transaction its last run left open
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}  invoiced ${invoiced}  transactions ${transactions}` +
    (deadLettered > 0 ? `  dead-lettered ${deadLettered}` : ''),
  );
  processed = 0;
  invoiced = 0;
  deadLettered = 0;
  transactions = 0;
}, 1_000);

await consumer.run({
  eachBatch: async ({ batch }) => {
    const last = batch.messages[batch.messages.length - 1];
    if (last === undefined) return;

    const transaction = await producer.transaction();
    try {
      const invoices: KafkaJS.Message[] = [];
      const parked: KafkaJS.Message[] = [];
      for (const message of batch.messages) {
        try {
          const invoice = toInvoice(message.value, CLIENT_ID);
          if (invoice !== null) invoices.push({ key: invoice.orderId, value: JSON.stringify(invoice) });
        } catch (error) {
          if (!(error instanceof InvalidOrderError)) throw error;
          // Parked in the same transaction: the dead letter and the offset past it are committed together.
          parked.push({
            key: message.key,
            value: message.value,
            headers: { error: error.message, 'source-partition': String(batch.partition), 'source-offset': message.offset },
          });
        }
      }
      if (invoices.length > 0) await transaction.send({ topic: INVOICES, messages: invoices });
      if (parked.length > 0) await transaction.send({ topic: DEAD_LETTER, messages: parked });
      // The group's offset is written by the transaction, so it moves only if the invoices are kept.
      await transaction.sendOffsets({
        consumer,
        topics: [{ topic: batch.topic, partitions: [{ partition: batch.partition, offset: String(Number(last.offset) + 1) }] }],
      });
      await transaction.commit();
      processed += batch.messages.length;
      invoiced += invoices.length;
      deadLettered += parked.length;
      totalInvoiced += invoices.length;
      transactions++;
    } catch (error) {
      console.error(`partition ${batch.partition}: transaction failed, aborting: ${String(error)}`);
      try {
        // Nothing from this batch becomes visible to read_committed readers. The throw below makes the client
        // seek back to the batch's first event and deliver it again, in a new transaction.
        await transaction.abort();
      } catch (abortError) {
        // This producer was fenced, hit a fatal error, or still has a commit in flight: no later transaction
        // can start here. Leave the group and exit; a restart with the same TRANSACTIONAL_ID finishes or
        // aborts whatever this run left open.
        console.error('the transaction cannot be aborted, exiting:', abortError);
        void shutdown('cannot abort', 1);
      }
      throw error;
    }
  },
});

let stopping = false;
async function shutdown(reason: string, exitCode: number): Promise<void> {
  if (stopping) return;
  stopping = true;
  clearInterval(ticker);
  console.log(`${reason}: finishing the current batch, leaving the group`);
  try {
    await consumer.disconnect(); // waits for the batch in eachBatch, transaction included
    await producer.disconnect();
    console.log(`left the group: ${totalInvoiced} invoices written`);
    process.exit(exitCode);
  } catch (error) {
    console.error('shutdown failed:', error);
    process.exit(1);
  }
}
process.once('SIGTERM', () => void shutdown('SIGTERM', 0));
process.once('SIGINT', () => void shutdown('SIGINT', 0));
Enter fullscreen mode Exit fullscreen mode

What each part of it is for:

  • One transaction per batch, through eachBatch instead of eachMessage: the client hands over several events of one partition at once. A transaction costs several round trips to the broker however few events it holds, so the batch size is the main knob; the numbers are below.
  • TRANSACTIONAL_ID has to be unique among running instances and stable across restarts of the same instance. When the producer connects, it registers that id, and the broker aborts any transaction the id's previous run left open. If that previous run is somehow still alive, the broker shuts it out: its next commit fails, as a run below shows. Kafka's documentation describes what happens if the id is new after every restart, as it would be with a random UUID: an open transaction from the dead run stays open until transaction.timeout.ms expires (60 seconds, as this client sets it), and read_committed readers cannot read past it in the partitions it wrote to, because they do not yet know whether those records count. The default here, invoicer- plus the container's hostname, survives docker restart, but not a recreate: Compose gives a container a new hostname whenever its image or configuration changes. The exit described below also assumes something restarts the process, such as Kubernetes or restart: on-failure in Compose; the lab's compose.yaml has no restart policy. On Kubernetes, a StatefulSet's pod names are stable; a Deployment's are not.
  • An event that cannot be invoiced is dead-lettered inside the transaction, so the parked event and the offset past it are committed together, like the invoices.
  • On an error, the transaction is aborted and the batch thrown back, so the client seeks to its first event and the whole batch is processed again, in a new transaction.
  • If the abort fails too, the process leaves the group and exits. That happens when the producer has been shut out, has hit a fatal error, or still has a commit in flight: this client gives a commit 5 seconds, a value hardcoded in its source, and a commit that runs out of time leaves it unable to start another transaction. Nothing more can succeed in that process, and a restart with the same id finishes or aborts whatever it left open.

Killing a transactional invoicer, the way the earlier sections killed theirs, showed little. Two kills of an earlier version of this file, before it had the dead-letter topic and the exit, left no duplicates, but neither caught a transaction whose invoices had already reached the broker, so there was nothing to abort. To watch an abort on purpose instead, one transactional invoicer ran with orders.dlt missing, a free coffee (total 0) and an unreadable event went through checkout, and the topic was created 30 seconds later. Every batch holding one of the two failed to write its dead letter, was aborted, and came back:

invoicer-tx-1  | partition 0: transaction failed, aborting: KafkaJSProtocolError: Broker: Unknown topic or partition
invoicer-tx-1  | partition 1: transaction failed, aborting: Error: Local: Unknown topic
Enter fullscreen mode Exit fullscreen mode

The first two of ten abort lines, about three seconds apart, until the topic existed. The client's own error entries between them are left out.

Once orders.dlt existed, both events were parked and their partitions moved on. Then the two counts:

read_committed: 3001 paid orders, 3000 invoiced once, 0 invoiced more than once (0 extra invoices), 1 never invoiced
read_uncommitted: 3001 paid orders, 2667 invoiced once, 333 invoiced more than once (1353 extra invoices), 1 never invoiced
Enter fullscreen mode Exit fullscreen mode

The aborted transactions had written 1,353 invoices into the log. A reader that ignored transactions would have billed 333 orders more than once; a read_committed reader saw none of them. The one order never invoiced is the free coffee, now in orders.dlt; the unreadable event was never a paid order to count.

And to watch the exit, a second instance started with the same TRANSACTIONAL_ID while the first, tx-a, was working:

tx-a  | partition 2: transaction failed, aborting: KafkaJSError: EndTxn commit failed: Unknown broker error
…
tx-a  | the transaction cannot be aborted, exiting: Error: Failed to end transaction: Local: This instance has been fenced by a newer instance
…
tx-a  | cannot abort: finishing the current batch, leaving the group
…
tx-a  | left the group: 3329 invoices written
Enter fullscreen mode Exit fullscreen mode

tx-a's own lines; the client's error entries are cut where the … are. The error the client handed back for the fencing was flagged neither fatal nor retriable, which is why the file checks whether the abort works rather than trusting the flags.

tx-a exited with code 1, and the newer instance carried on. Of 4,000 paid orders, every one was invoiced exactly once for a read_committed reader; the 5 invoices from tx-a's last, aborted transaction were visible only to read_uncommitted.

The cost is throughput, and it depends almost entirely on the batch size. The same backlog of 90,000 events, one transactional invoicer catching up alone:

Batch size (js.consumer.max.batch.size) Time to process 90,000 events Transactions
32, this client's default 52 s 2,817
500, as in the file above 7 s 184

Assembled from each run's per-second lines. One run each, in the same round as the commit table above; the round made while the machine was short of memory took 200 and 17 seconds.

A transaction of 500 events cost more than one of 32: the per-second lines show about 25 transactions a second against about 63. But it cost far less than 15 times more, and that is the whole knob. With the default batch size, exactly-once took more than twice as long as the auto-commit invoicer above (52 s against 22). With 500 it was three times faster, but not because transactions are cheap: it writes a batch's invoices in one send(), while the at-least-once invoicer awaits each invoice separately so that every commit mode in the previous section runs the same code. Bigger batches also mean bigger transactions: a failure throws back up to 500 events, and a read_committed reader sees a batch's invoices only when its transaction commits.

And the guarantee covers Kafka, nothing else. If the invoicer also emailed each customer, the email would go out when the batch was processed, and again when an aborted batch was processed a second time. Anything outside the transaction, an email, an HTTP call, a row in Postgres, gets at-least-once at best and needs its own way to recognize a repeat.

On the left, a sealed glass box holds a stack of invoices and a bookmark flag tied together with one ribbon; on the right, a box like it stands open on a desk behind a closed gate, with four small robots waiting in line beside an hourglass

A failure that stops a partition

Everything so far assumed the work succeeds eventually. When eachMessage throws, this client logs the error and seeks back to the same event, which is delivered again. It never skips it. For a failure that goes away, such as a broker that restarts or a downstream service that times out, that is what you want: the partition waits, nothing is lost, and the order of its events is kept.

For an event that can never succeed, it means the partition stops for good. Ten seconds into a run of 6,000 orders, a free coffee went through checkout: one order with a total of 0, which toInvoice refuses. It landed on partition 0, owned by invoicer-3:

invoicer-3  | 14:53:44.650  partitions 0  processed 181  invoiced 62
invoicer-3  | 14:53:45.644  partitions 0  processed 173  invoiced 56  failed 1
invoicer-3  | 14:53:46.645  partitions 0  processed 0  invoiced 0  failed 14
invoicer-3  | 14:53:47.646  partitions 0  processed 0  invoiced 0  failed 17
…
invoicer-3  | 14:55:16.749  partitions 0  processed 0  invoiced 0  failed 2
invoicer-3  | 14:55:17.750  partitions 0  processed 0  invoiced 0  failed 2
invoicer-3  | 14:55:18.750  partitions 0  processed 0  invoiced 0  failed 2
Enter fullscreen mode Exit fullscreen mode

The three runs in this section were made with an earlier version of the invoicer, in which toInvoice lived in the same file and threw a plain Error, and the dead-letter version counted attempts per partition rather than per event. The free coffee takes the same path through both.

It was retried 14 to 46 times a second while checkout was still producing, and about twice a second once it stopped, for the minute and a half the run had left. Each attempt logged the error with its stack trace: 572 of them. The other two partitions carried on, and the lag at the end of the run says what it cost:

  partition 0  committed 3009  end 6069  lag 3060
  partition 1  committed 6132  end 6132  lag 0
  partition 2  committed 5802  end 5802  lag 0
Enter fullscreen mode Exit fullscreen mode
read_committed: 6001 paid orders, 4979 invoiced once, 0 invoiced more than once (0 extra invoices), 1022 never invoiced
Enter fullscreen mode Exit fullscreen mode

One free coffee left 1,021 ordinary orders behind it uninvoiced, and would have kept them there until someone deployed a fix.

The fix is to tell the two kinds of failure apart. Bad data, an event that cannot be read or cannot be invoiced, goes to a dead-letter topic, orders.dlt, where someone can inspect it, and the partition moves on. Everything else is retried, but with the partition paused for 1, 2, 4 seconds and so on, up to 30, instead of as fast as the client can fetch. Create the topic first, since this broker does not create topics on demand:

docker compose run --rm tools node src/create-topic.ts orders.dlt 1
Enter fullscreen mode Exit fullscreen mode

These are the changes to the invoicer:

// src/invoicer-dlt.ts (excerpt: the changes from invoicer.ts)
import { InvalidOrderError, INVOICES, kafka, TOPIC, toInvoice, type Invoice } from './kafka.ts';
const DEAD_LETTER = 'orders.dlt'; // create it up front: the broker does not create topics on demand

// ... in handle(), where invoicer.ts only counted the failure and threw:
  let invoice: Invoice | null = null;
  try {
    invoice = toInvoice(message.value, CLIENT_ID);
  } catch (error) {
    if (!(error instanceof InvalidOrderError)) throw error;
    // No retry can fix the data: park the event where someone can look at it, and move on.
    await producer.send({
      topic: DEAD_LETTER,
      messages: [{
        key: message.key,
        value: message.value,
        headers: { error: error.message, 'source-partition': String(partition), 'source-offset': message.offset },
      }],
    });
    deadLettered++;
  }

// ... and eachMessage, which now owns the retry:
let current: Promise<void> = Promise.resolve(); // the event being processed, if any
const failing = new Map<number, { offset: string; attempts: number }>(); // partition -> the event that keeps failing
await consumer.run({
  eachMessage: async (payload) => {
    const { topic, partition, message } = payload;
    current = handle(payload);
    try {
      await current;
      failing.delete(partition);
    } catch (error) {
      // Stop this partition, not the others, and retry the same event after 1 s, 2 s, 4 s ... at most 30 s.
      failed++;
      const previous = failing.get(partition);
      const attempt = previous?.offset === message.offset ? previous.attempts + 1 : 1;
      failing.set(partition, { offset: message.offset, attempts: attempt });
      const delayMs = Math.min(1_000 * 2 ** (attempt - 1), 30_000);
      console.error(`partition ${partition} offset ${message.offset}: attempt ${attempt} failed, retrying in ${delayMs} ms: ${String(error)}`);
      consumer.pause([{ topic, partitions: [partition] }]);
      setTimeout(() => {
        try {
          consumer.resume([{ topic, partitions: [partition] }]);
        } catch {
          // resume() throws only once the consumer is disconnecting: there is nothing left to resume.
        }
      }, delayMs);
      throw error; // the client seeks back to this event and delivers it again once the partition resumes
    }
  },
});
Enter fullscreen mode Exit fullscreen mode

Pausing and then throwing is the pattern the client's own source recommends: the throw makes it seek back to the event, and the pause keeps it from fetching that partition until the timer resumes it. The retry count belongs to the event, not the partition: once a partition gets past one failure, its next failure starts again at 1 second.

The same free coffee against this version:

invoicer-2  | 14:56:44.490  partitions 0  processed 216  invoiced 70  dead-lettered 1
Enter fullscreen mode Exit fullscreen mode
read_committed: 6001 paid orders, 6000 invoiced once, 0 invoiced more than once (0 extra invoices), 1 never invoiced
Enter fullscreen mode Exit fullscreen mode

The one order never invoiced is the free coffee, now in orders.dlt with the reason and its original position in the headers, which is what Kafka's console consumer prints first:

error:order ord-free-coffee: an invoice needs a positive total, got 0,source-partition:0,source-offset:3009 ord-free-coffee {"orderId":"ord-free-coffee","type":"paid","seq":2,"totalCents":0,"producedAt":1795791396849}
Enter fullscreen mode Exit fullscreen mode

An unreadable event goes down the same branch, since toInvoice throws the same InvalidOrderError for it; the transactional run in the previous section parked one next to a free coffee.

The backoff needed its own failure to be watched. A lab-only copy of the file failed every invoice write for 12 seconds, starting 25 seconds after the invoicers started; each partition backed off on its own:

invoicer-1  | partition 1 offset 1511: attempt 1 failed, retrying in 1000 ms: Error: simulated outage: the invoice was not written
invoicer-1  | partition 1 offset 1511: attempt 2 failed, retrying in 2000 ms: Error: simulated outage: the invoice was not written
invoicer-1  | partition 1 offset 1511: attempt 3 failed, retrying in 4000 ms: Error: simulated outage: the invoice was not written
invoicer-1  | partition 1 offset 1511: attempt 4 failed, retrying in 8000 ms: Error: simulated outage: the invoice was not written
Enter fullscreen mode Exit fullscreen mode

invoicer-1's attempts only; the other two partitions logged the same four. The client's own error entry after each attempt is left out.

The fifth attempt came after the outage and succeeded, and the count afterwards was 6,000 orders invoiced once, none twice, none missing.

One trade-off comes with the dead-letter topic. Parking an event lets the next event with the same key go ahead without it. For the invoicer that is harmless, since only paid events matter; for a consumer that needs each order's events in sequence, parking one means the order's later events must be parked too, or handled as incomplete.

Four conveyor belts of numbered tiles worked by robots; on the third, a cup marked 0 jams the machine and the tiles pile up behind it, until a curved chute carries the cup into a bin labelled invalid data and the last belt runs again

Picking a guarantee

At-least-once with auto-commit is the right default, on three conditions: you await everything the event needs inside eachMessage, the producer is idempotent, and whatever the consumer does can recognize a repeat. For the invoicer, that last condition could be a unique constraint on the order id in the billing database, or a downstream that treats a second invoice for the same order as the same invoice. Kafka cannot remove duplicates outside Kafka for you, so that part is always yours.

Commit yourself only when auto-commit cannot express what you need, and then cover every moment it covered: on a timer, in rebalance_cb when partitions are revoked, and before disconnect(). Committing after every event narrows a crash less than it seems, since this client only queues the commit, and it costs a request per event.

Use transactions when the output goes back into Kafka and duplicates there are not acceptable: running totals, aggregations, anything another service sums. Batch them, keep transactional.id stable per instance, exit when an abort fails, and make sure every reader of the output uses read_committed. They are the wrong tool when the side effect leaves Kafka; there, the usual answers are an idempotency key the other system understands, or keeping the consumer's offsets in the same database transaction as the work.

For failures, decide per kind. Data that can never be processed goes to a dead-letter topic, with enough headers to find where it came from. Everything else is retried with a backoff, on that partition only, because stopping is what keeps the other events safe.

The managed services, Confluent Cloud and Amazon MSK among them, run the same protocol, so the same rules apply there, with one condition for this code: 'group.protocol': 'consumer' needs Kafka 4.0 or later on the brokers. On an older cluster, leave it out and the client falls back to the classic protocol. Check which features your plan supports before you rely on transactions.

Key takeaways

  • Auto-commit is at-least-once for what you await in eachMessage, and it also commits when partitions are taken away. Three kills repeated 5, 145 and 250 invoices; a clean stop and a join repeated none.
  • Turning auto-commit off hands you every commit it made. Committing every 1,000 events and nothing else, a clean SIGTERM repeated 206 invoices and a join 99. This client refuses commits once disconnect() has started, so the commit has to come before it, and a count needs a timer behind it, or a quiet partition keeps its last events uncommitted for good.
  • Make every producer idempotent. With the broker frozen for 8 seconds, a producer without it wrote 4 and 6 duplicates out of 9,000 events; with it, none. This client leaves it off by default.
  • Transactions hide every aborted write from read_committed readers. Ten aborted transactions left 1,353 invoices in the log that only a read_uncommitted reader saw. With the default batch of 32 they took 52 seconds for what batches of 500 did in 7, and they cover writes to Kafka and nothing else.
  • A throw stops its partition until someone fixes it. One free coffee left 1,021 orders uninvoiced behind it, retried twice a second. Dead-letter data that can never succeed, and back off on everything else.

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

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

  invoicer-tx:
    build: .
    image: aurora-kafka-lab
    init: true
    profiles: ["tx"]
    command: ["node", "src/invoicer-tx.ts"]
    environment:
      KAFKA_BROKERS: kafka:19092
      CLIENT_ID: invoicer-tx
    depends_on:
      kafka:
        condition: service_healthy

  invoice-reader:
    build: .
    image: aurora-kafka-lab
    init: true
    profiles: ["tx"]
    command: ["node", "src/invoice-reader.ts"]
    environment:
      KAFKA_BROKERS: kafka:19092
      CLIENT_ID: invoice-reader
    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/kafka.ts
// src/kafka.ts: the broker address, the topics, and the shape of an order event and of its invoice.
import { KafkaJS } from '@confluentinc/kafka-javascript';

export const TOPIC = 'orders';
export const INVOICES = 'invoices';

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;
  }
}

// One invoice per paid order: the side effect whose duplicates and gaps this lab counts.
export type Invoice = {
  orderId: string;
  totalCents: number;
  invoicedBy: string; // the invoicer instance that wrote it
  invoicedAt: number; // epoch ms
};

// Data no retry can fix, as opposed to a failure that may go away if the event is tried again later.
export class InvalidOrderError extends Error {}

// The invoice an order event calls for: null when it needs none, InvalidOrderError when it cannot be read or billed.
export function toInvoice(value: Buffer | null, invoicedBy: string): Invoice | null {
  const event = parseOrderEvent(value);
  if (event === null) throw new InvalidOrderError(`not a readable order event: ${String(value).slice(0, 200)}`);
  if (event.type !== 'paid') return null;
  if (event.totalCents <= 0) {
    throw new InvalidOrderError(`order ${event.orderId}: an invoice needs a positive total, got ${event.totalCents}`);
  }
  return { orderId: event.orderId, totalCents: event.totalCents, invoicedBy, invoicedAt: Date.now() };
}

export function parseInvoice(value: Buffer | null): Invoice | null {
  if (value === null) return null;
  try {
    const invoice = JSON.parse(value.toString('utf8')) as Partial<Invoice>;
    const valid =
      typeof invoice.orderId === 'string' &&
      Number.isInteger(invoice.totalCents) &&
      typeof invoice.invoicedBy === 'string' &&
      typeof invoice.invoicedAt === 'number';
    return valid ? (invoice as Invoice) : 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

src/produce-orders.ts
// 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 IDEMPOTENT = process.env.IDEMPOTENT !== 'false'; // IDEMPOTENT=false switches duplicate detection off, on purpose
// How long the client waits for the broker's answer before it gives up on a request and retries it.
// Unset keeps this client's default, 30 s.
const SOCKET_TIMEOUT_MS = process.env.SOCKET_TIMEOUT_MS ? Number(process.env.SOCKET_TIMEOUT_MS) : undefined;

const producer = kafka.producer({
  ...(SOCKET_TIMEOUT_MS === undefined ? {} : { 'socket.timeout.ms': SOCKET_TIMEOUT_MS }),
  kafkaJS: { idempotent: IDEMPOTENT },
});
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).
    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

src/count-invoices.ts
// src/count-invoices.ts: reads every paid order and every invoice from the beginning and compares them.
// READ_UNCOMMITTED=true also reads invoices that belong to aborted transactions. A read_committed count
// stops at an open transaction, so it reports only what has been committed when it runs.
import { randomUUID } from 'node:crypto';
import { INVOICES, kafka, parseInvoice, parseOrderEvent, TOPIC } from './kafka.ts';

const READ_UNCOMMITTED = process.env.READ_UNCOMMITTED === 'true';
const IDLE_MS = 3_000; // stop once nothing new has arrived for this long

const paid = new Set<string>();
const invoices = new Map<string, number>(); // order id -> invoices seen for it

const consumer = kafka.consumer({
  kafkaJS: {
    groupId: `count-invoices-${randomUUID()}`, // a fresh group: always from offset 0, never commits
    fromBeginning: true,
    autoCommit: false,
    allowAutoTopicCreation: false,
    readUncommitted: READ_UNCOMMITTED,
  },
});
await consumer.connect();
await consumer.subscribe({ topics: [TOPIC, INVOICES] });

let lastMessageAt = 0; // the idle clock starts at the first message, not before the group has joined
await consumer.run({
  eachMessage: async ({ topic, message }) => {
    lastMessageAt = Date.now();
    if (topic === TOPIC) {
      const event = parseOrderEvent(message.value);
      if (event?.type === 'paid') paid.add(event.orderId);
    } else {
      const invoice = parseInvoice(message.value);
      if (invoice !== null) invoices.set(invoice.orderId, (invoices.get(invoice.orderId) ?? 0) + 1);
    }
  },
});

while (lastMessageAt === 0 || Date.now() - lastMessageAt < IDLE_MS) {
  await new Promise((resolve) => setTimeout(resolve, 250));
}
await consumer.disconnect();

let once = 0;
let duplicated = 0;
let extra = 0;
let missing = 0;
for (const orderId of paid) {
  const count = invoices.get(orderId) ?? 0;
  if (count === 0) missing++;
  else if (count === 1) once++;
  else {
    duplicated++;
    extra += count - 1;
  }
}
const orphans = [...invoices.keys()].filter((orderId) => !paid.has(orderId)).length;
console.log(
  `${READ_UNCOMMITTED ? 'read_uncommitted' : 'read_committed'}: ${paid.size} paid orders, ` +
  `${once} invoiced once, ${duplicated} invoiced more than once (${extra} extra invoices), ` +
  `${missing} never invoiced` + (orphans > 0 ? `, ${orphans} invoices for unknown orders` : ''),
);
Enter fullscreen mode Exit fullscreen mode

src/invoice-reader.ts
// src/invoice-reader.ts: a downstream service that reads invoices. Prints one line per second.
// READ_UNCOMMITTED=true also reads invoices from transactions that are still open or were aborted.
import { INVOICES, kafka, parseInvoice } from './kafka.ts';

const READ_UNCOMMITTED = process.env.READ_UNCOMMITTED === 'true';

const consumer = kafka.consumer({
  kafkaJS: {
    groupId: process.env.GROUP_ID ?? 'invoice-reader',
    fromBeginning: true,
    allowAutoTopicCreation: false,
    readUncommitted: READ_UNCOMMITTED,
  },
  'group.protocol': 'consumer',
});

let received = 0;
let maxDelayMs = 0;
let total = 0;

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

const ticker = setInterval(() => {
  console.log(`${new Date().toISOString().slice(11, 23)}  invoices ${received}  max delay ${maxDelayMs} ms`);
  received = 0;
  maxDelayMs = 0;
}, 1_000);

await consumer.run({
  eachMessage: async ({ message }) => {
    const invoice = parseInvoice(message.value);
    if (invoice === null) return;
    received++;
    total++;
    maxDelayMs = Math.max(maxDelayMs, Date.now() - invoice.invoicedAt); // how long since it was written
  },
});

let stopping = false;
async function shutdown(): Promise<void> {
  if (stopping) return;
  stopping = true;
  clearInterval(ticker);
  try {
    await consumer.disconnect();
    console.log(`left the group: ${total} invoices read`);
    process.exit(0);
  } catch (error) {
    console.error('disconnect failed:', error);
    process.exit(1);
  }
}
process.once('SIGTERM', () => void shutdown());
process.once('SIGINT', () => void shutdown());
Enter fullscreen mode Exit fullscreen mode

src/create-topic.ts
// src/create-topic.ts: creates a topic with a fixed number of partitions, e.g. `node src/create-topic.ts orders 3`.
import { kafka } from './kafka.ts';

const topic = process.argv[2];
if (topic === undefined || topic === '') throw new Error('usage: node src/create-topic.ts <topic> [partitions] [replication factor]');
const partitions = Number(process.argv[3] ?? 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[4] ?? 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, 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

Top comments (0)