OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(M16-002): Make the Kafka producer's throughput knobs configurable and add batching behind a default-off flag, so options 2 and 4 can be MEASURED without changing today's behaviour
ralph4b2621c1343f
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.tsindex fe7217dbe..2a884e80c 100644--- a/apps/api/src/config/env.ts+++ b/apps/api/src/config/env.ts@@ -29,6 +29,11 @@import type { CoreConfig } from '@openpanel/core';import { queues } from '@openpanel/core';+// The producer's throughput knobs are shaped by the module that applies them+// (ADR-022 R8: a module's `*.constants.ts` is the file an app may import), so+// a renamed field fails to compile on both sides instead of going quietly+// unread. See packages/core/src/modules/ingest/src/producer-tuning.ts.+import type { KafkaProducerTuning } from '@openpanel/core/modules/ingest/ingest.constants';import { z } from 'zod';export const ROLE_VALUES = ['api', 'worker', 'all'] as const;@@ -60,6 +65,12 @@ const DEFAULT_KAFKA_CONNECTION_TIMEOUT_MS = 2000;const DEFAULT_KAFKA_PRODUCER_RETRIES = 2;const DEFAULT_KAFKA_PRODUCER_INITIAL_RETRY_MS = 100;const DEFAULT_KAFKA_PRODUCER_MAX_RETRY_MS = 1000;+/** One produce round-trip at a time — today's behaviour (M16-002 option 4). */+const DEFAULT_KAFKA_PRODUCER_MAX_IN_FLIGHT = 1;+/** Messages per `send()`. 1 = batching off (M16-002 option 2). */+const DEFAULT_KAFKA_PRODUCER_BATCH_SIZE = 1;+/** A partial batch's maximum wait. Inert while the batch size is 1. */+const DEFAULT_KAFKA_PRODUCER_BATCH_LINGER_MS = 5;const DEFAULT_KAFKA_HANDLER_MAX_ATTEMPTS = 3;const DEFAULT_KAFKA_HANDLER_RETRY_INITIAL_MS = 100;const DEFAULT_KAFKA_HANDLER_RETRY_MAX_MS = 1000;@@ -417,6 +428,15 @@ const rawSchema = z.object({KAFKA_PRODUCER_MAX_RETRY_MS: positiveIntWithDefault(DEFAULT_KAFKA_PRODUCER_MAX_RETRY_MS),+ KAFKA_PRODUCER_MAX_IN_FLIGHT: positiveIntWithDefault(+ DEFAULT_KAFKA_PRODUCER_MAX_IN_FLIGHT+ ),+ KAFKA_PRODUCER_BATCH_SIZE: positiveIntWithDefault(+ DEFAULT_KAFKA_PRODUCER_BATCH_SIZE+ ),+ KAFKA_PRODUCER_BATCH_LINGER_MS: positiveIntWithDefault(+ DEFAULT_KAFKA_PRODUCER_BATCH_LINGER_MS+ ),KAFKA_HANDLER_MAX_ATTEMPTS: positiveIntWithDefault(DEFAULT_KAFKA_HANDLER_MAX_ATTEMPTS),@@ -584,6 +604,46 @@ function deriveDashboardUrl(raw: RawEnv): string {return raw.DASHBOARD_URL ?? '';}+/**+ * The Kafka transport's knobs, plus the three producer tuning knobs the ingest+ * module reads off the same object (`KafkaProducerTuning`). They are its+ * fields rather than `KafkaConfig`'s only because+ * `packages/core/src/config.ts` is outside M16-002's scope; the follow-up+ * moves them onto `KafkaConfig` and this return type becomes plain+ * `CoreConfig['kafka']`.+ */+function deriveKafkaConfig(+ raw: RawEnv+): CoreConfig['kafka'] & KafkaProducerTuning {+ return {+ clientId: raw.KAFKA_CLIENT_ID,+ brokers: raw.KAFKA_BROKERS,+ eventsTopic: raw.KAFKA_EVENTS_TOPIC,+ // Same broker as the events topic, so a poison message is retained and+ // countable instead of dropped (ADR-004 delivery semantics).+ eventsDlqTopic:+ raw.KAFKA_EVENTS_DLQ_TOPIC ?? `${raw.KAFKA_EVENTS_TOPIC}-dlq`,+ consumerGroup: raw.KAFKA_CONSUMER_GROUP,+ partitionsConcurrent: raw.KAFKA_PARTITIONS_CONCURRENT,+ minMessages: raw.KAFKA_MIN_MESSAGES,+ maxWaitMs: raw.KAFKA_MAX_WAIT_MS,+ maxMessagesPerPartition: raw.KAFKA_MAX_MESSAGES_PER_PARTITION,+ sessionTimeoutMs: raw.KAFKA_SESSION_TIMEOUT_MS,+ heartbeatIntervalMs: raw.KAFKA_HEARTBEAT_INTERVAL_MS,+ requestTimeoutMs: raw.KAFKA_REQUEST_TIMEOUT_MS,+ connectionTimeoutMs: raw.KAFKA_CONNECTION_TIMEOUT_MS,+ producerRetries: raw.KAFKA_PRODUCER_RETRIES,+ producerInitialRetryMs: raw.KAFKA_PRODUCER_INITIAL_RETRY_MS,+ producerMaxRetryMs: raw.KAFKA_PRODUCER_MAX_RETRY_MS,+ producerMaxInFlight: raw.KAFKA_PRODUCER_MAX_IN_FLIGHT,+ producerBatchSize: raw.KAFKA_PRODUCER_BATCH_SIZE,+ producerBatchLingerMs: raw.KAFKA_PRODUCER_BATCH_LINGER_MS,+ handlerMaxAttempts: raw.KAFKA_HANDLER_MAX_ATTEMPTS,+ handlerRetryInitialMs: raw.KAFKA_HANDLER_RETRY_INITIAL_MS,+ handlerRetryMaxMs: raw.KAFKA_HANDLER_RETRY_MAX_MS,+ };+}+function deriveCoreConfig(raw: RawEnv): CoreConfig {const isProduction = raw.NODE_ENV === PRODUCTION;const exporter =@@ -659,30 +719,7 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {saveDiscountId: raw.POLAR_SAVE_DISCOUNT_ID,webhookSecret: raw.POLAR_WEBHOOK_SECRET,},- kafka: {- clientId: raw.KAFKA_CLIENT_ID,- brokers: raw.KAFKA_BROKERS,- eventsTopic: raw.KAFKA_EVENTS_TOPIC,- // Same broker as the events topic, so a poison message is retained and- // countable instead of dropped (ADR-004 delivery semantics).- eventsDlqTopic:- raw.KAFKA_EVENTS_DLQ_TOPIC ?? `${raw.KAFKA_EVENTS_TOPIC}-dlq`,- consumerGroup: raw.KAFKA_CONSUMER_GROUP,- partitionsConcurrent: raw.KAFKA_PARTITIONS_CONCURRENT,- minMessages: raw.KAFKA_MIN_MESSAGES,- maxWaitMs: raw.KAFKA_MAX_WAIT_MS,- maxMessagesPerPartition: raw.KAFKA_MAX_MESSAGES_PER_PARTITION,- sessionTimeoutMs: raw.KAFKA_SESSION_TIMEOUT_MS,- heartbeatIntervalMs: raw.KAFKA_HEARTBEAT_INTERVAL_MS,- requestTimeoutMs: raw.KAFKA_REQUEST_TIMEOUT_MS,- connectionTimeoutMs: raw.KAFKA_CONNECTION_TIMEOUT_MS,- producerRetries: raw.KAFKA_PRODUCER_RETRIES,- producerInitialRetryMs: raw.KAFKA_PRODUCER_INITIAL_RETRY_MS,- producerMaxRetryMs: raw.KAFKA_PRODUCER_MAX_RETRY_MS,- handlerMaxAttempts: raw.KAFKA_HANDLER_MAX_ATTEMPTS,- handlerRetryInitialMs: raw.KAFKA_HANDLER_RETRY_INITIAL_MS,- handlerRetryMaxMs: raw.KAFKA_HANDLER_RETRY_MAX_MS,- },+ kafka: deriveKafkaConfig(raw),buffers: {asyncInserts: raw.BUFFER_ASYNC_INSERTS,chInsertConcurrency: raw.BUFFER_CH_INSERT_CONCURRENCY,diff --git a/docs/KAFKA_PRODUCER_OPTIONS.md b/docs/KAFKA_PRODUCER_OPTIONS.mdnew file mode 100644index 000000000..7f29bcf6a--- /dev/null+++ b/docs/KAFKA_PRODUCER_OPTIONS.md@@ -0,0 +1,217 @@+# The Kafka producer's throughput knobs — what to measure, and how++M16-002. This document exists so the operator's four-configuration measurement+run, and the ADR Carl writes from it (ADR-004's producer-redesign question),+are built on precise statements about which knob produces which behaviour.++**Nothing here is switched on.** Every default reproduces the behaviour+measured in `verification/benchmarks/05-v2-saturation.md`: one produce+round-trip at a time, one message per `send()`, awaited in the request path.++## The bottleneck being measured++`05-v2-saturation.md` (operator run, 2026-09-12, 4-core box): V2 `/track`+plateaus at **~780–806 events/s** with ~85 % of the CPU unused, while P50+latency doubles with every doubling of concurrency (29 → 456 ms from+concurrency 25 → 400). The cause is in+`packages/core/src/modules/ingest/src/kafka.ts`: one shared producer with+`maxInFlightRequests: 1`, and one awaited `send()` carrying a **single**+message per request. ~800/s is ~1.25 ms per local ack, serialised.++Four options were named. This task makes **2** and **4** measurable:++| # | Option | Status |+|---|---|---|+| 1 | More api processes | Already the cloud deployment's scaling story (Carl). A live fallback, not a candidate — nothing below has to reach 5,000 ev/s in one process. |+| 2 | **Batch: one `send()`, many messages** | Built, default **off** — `KAFKA_PRODUCER_BATCH_SIZE` / `KAFKA_PRODUCER_BATCH_LINGER_MS`. |+| 3 | Don't await the broker; buffer and flush async | **Deliberately not built.** It changes what a 200 response promises — a durability decision for Carl, not a performance tweak. |+| 4 | **Raise `maxInFlightRequests`** | Built, default **1** (unchanged) — `KAFKA_PRODUCER_MAX_IN_FLIGHT`. |++## The knobs++All three are read by the config loader, `apps/api/src/config/env.ts` (the sole+`process.env` reader, ADR-022 R7), and resolved in+`packages/core/src/modules/ingest/src/producer-tuning.ts`.++| Env var | Default | What it does |+|---|---|---|+| `KAFKA_PRODUCER_MAX_IN_FLIGHT` | `1` | kafkajs `maxInFlightRequests`: how many produce requests may be outstanding on the producer's connection at once. `1` is today's value and serialises every produce. Raising it lets requests overlap — read the retry coupling below before you do. |+| `KAFKA_PRODUCER_BATCH_SIZE` | `1` | Messages accumulated into ONE `send()`. `1` means batching is off and the code path is byte-for-byte today's: one message, one awaited send. `>= 2` turns the accumulator on. |+| `KAFKA_PRODUCER_BATCH_LINGER_MS` | `5` | How long a partially filled batch may wait for company before it is sent anyway. **Inert while the batch size is 1.** |++Positive integers only; a blank or malformed value fails boot, like every other+`KAFKA_*` knob. The resolved values are logged once, on the+`kafka producer connected` line, so a measurement run can be tied to the+configuration that produced it:++```json+{"topic":"events","maxInFlight":5,"batchSize":25,"batchLingerMs":10,"batching":true,"msg":"kafka producer connected"}+```++### What batching does and does not change++Batching only touches the **events topic** (`produceIncomingEvent`). The+dead-letter path produces one poison record at a time and has no round-trip to+amortise, so it keeps the direct path.++The accumulator (`src/producer-batcher.ts`) holds two guarantees, each with a+test in `src/producer-batcher.test.ts`:++1. **Per-key ordering survives.** Messages leave in the order they were+ enqueued — within a batch because the array preserves that order (kafkajs+ partitions per message by key, and same-key messages in one `send()` land in+ one partition batch in array order), and across batches because the+ accumulator keeps exactly **one send outstanding at a time**. That second+ half is why ordering does not depend on `maxInFlightRequests` staying at 1.+2. **A caller's promise settles on its own batch.** A failed `send()` rejects+ exactly the callers whose messages were in it, and nobody else; the next+ batch is still sent. A batch that fails fatally+ (`OUT_OF_ORDER_SEQUENCE_NUMBER` and friends) runs the same+ `resetProducer` recovery a lone message did — the batched and unbatched+ paths are the same `sendMessages` call.++A partially filled batch is flushed inside the linger window, so a low-traffic+instance never strands an event; `disconnectKafka` flushes what is still+accumulating before the producer closes, so a shutdown inside the linger window+cannot strand one either.++What batching does **not** change: idempotency stays on, `maxInFlightRequests`+is untouched by it, the topic, key and envelope are identical, and `/track`+still answers only after the broker has acknowledged the caller's message.++### The retry coupling — why option 4 must not be measured alone++kafkajs 2.2.4 defaults an idempotent producer to+`retries: Number.MAX_SAFE_INTEGER`, and logs+`Limiting retries for the idempotent producer may invalidate EoS guarantees`+when you lower it (`kafkajs/src/producer/index.js:43-55`). This codebase+lowers it: `KAFKA_PRODUCER_RETRIES`, `DEFAULT_KAFKA_PRODUCER_RETRIES = 2`.++So today's `maxInFlightRequests: 1` is plausibly **compensating for a retry+setting that already weakened idempotency**, and the in-code comment+("1 (not 5) to avoid in-flight reordering … reordered batches trip+`OUT_OF_ORDER_SEQUENCE_NUMBER` and stick the producer per-partition") is+consistent with that reading.++**Consequence for the measurement: vary `KAFKA_PRODUCER_RETRIES` together with+`KAFKA_PRODUCER_MAX_IN_FLIGHT`.** A configuration-4 run at `retries=2` is a+different durability posture from one at kafkajs's own default, and a+throughput number from either is not transferable to the other. M16-002 did+**not** change the retry default; that is part of the decision, not part of+making it measurable.++Note that option 2 sidesteps this entirely: batching amortises the round-trip+while leaving `maxInFlightRequests`, idempotency and ordering exactly as they+are. That is why it is the likelier candidate for adoption.++## Reproducing the four configurations++The harness is `apps/api/e2e/saturation-sweep.ts` (M16-001); its knobs are+documented in `docs/BENCHMARK_HARNESS.md`. The producer knobs belong to the+**api process**, not to the harness, so they are set when the stack is booted+and the stack is restarted between configurations.++```bash+# 1. BASELINE — today's behaviour. No producer env at all.+cd apps/api && API_PORT=3333 bun run dev++# 2. HIGHER IN-FLIGHT (option 4)+cd apps/api && API_PORT=3333 KAFKA_PRODUCER_MAX_IN_FLIGHT=5 bun run dev++# 3. BATCHING (option 2)+cd apps/api && API_PORT=3333 \+ KAFKA_PRODUCER_BATCH_SIZE=25 KAFKA_PRODUCER_BATCH_LINGER_MS=10 \+ bun run dev++# 4. BOTH+cd apps/api && API_PORT=3333 \+ KAFKA_PRODUCER_MAX_IN_FLIGHT=5 \+ KAFKA_PRODUCER_BATCH_SIZE=25 KAFKA_PRODUCER_BATCH_LINGER_MS=10 \+ bun run dev+```++and against each stack, the same sweep `05-v2-saturation.md` ran:++```bash+cd apps/api+E2E_WORKER_URL=http://localhost:3333 \+ SWEEP_LADDER=25,50,100,200,400,800 \+ E2E_SESSIONS=2000 E2E_EVENTS_PER_SESSION=3 \+ bun run e2e:saturation+```++Confirm each run's configuration from the api's own+`kafka producer connected` log line before recording its numbers — the knobs+are read at boot, and a stale stack silently measures the previous+configuration.++Two things worth holding constant, from `05-v2-saturation.md`: split the roles+(`ROLE=api` and `ROLE=worker` as two processes) or the api and worker+CPU/RSS rows are the same pid, and keep the auth path fixed —+`SWEEP_AUTH_MODE=secret` is the harness default and the pessimistic, real+server-side-SDK path.++Batch size and linger deserve a small ladder of their own inside+configuration 3 (e.g. size 10/25/100 at linger 5/10/25): the batch size is+bounded in practice by how many requests are actually in flight at the offered+concurrency, and a batch size far above that only ever fills by linger timeout.++## Proof runs performed by this task (not the measurement)++Run by the agent on 2026-09-12 on the same 4-core box, against a+purpose-booted `ROLE=api` api on `API_PORT=3399` producing into the running+dev stack's consumer. These prove the flags take effect and that nothing+regresses. **They are far too small to support a throughput conclusion** —+150 sessions × 3 events = 450 requests per run, and the two baseline runs+differ from each other by 50 %.++| configuration | `session-stress` emit window | P50 | P95 | checks |+|---|---|---|---|---|+| default (`maxInFlight=1`, batching off), run 1 | 0.9 s | 91.7 ms | 142.9 ms | 13/13 |+| default, run 2 | 0.6 s | 67.0 ms | 79.9 ms | 13/13 |+| `MAX_IN_FLIGHT=5 BATCH_SIZE=25 LINGER_MS=10`, run 1 | 0.5 s | 48.4 ms | 77.3 ms | 13/13 |+| same, run 2 | 0.5 s | 45.7 ms | 95.2 ms | 13/13 |++Every run reconciled its ClickHouse event counts exactly+(`session_start == sessions`, `session_end == sessions`, total events ==+`sessions × (events + start + end)`), with Kafka peak lag 1 and no queue or+buffer left off zero. The session e2e passed 29/29 against both+configurations — and because that suite sends single events with nothing else+in flight, its passing under `BATCH_SIZE=25` is also the end-to-end proof that+the linger flush works: every one of those events left as a partial batch.++## What is still unknown++- **Whether either option moves the plateau at all.** Nothing here has been+ measured at saturation. The ~800 ev/s ceiling is attributed to the+ serialised produce path by elimination (idle CPU, clean event loop, consumer+ lag ≈ 0), not by an experiment that removed the serialisation.+- **Whether the produce path is the only serialising dependency.**+ `05-v2-saturation.md` names two other candidates it did not exonerate: the+ Redis session-state operations and the event buffer. If the plateau holds+ with batching on, the next suspect is one of those, not a bigger batch.+- **The right batch size and linger for production**, and whether a linger of+ a few ms is acceptable in the request path at all — it is latency added to+ every `/track` that is not in a full batch.+- **The durability posture.** Both the retry coupling above and option 3 are+ Carl's to decide; this task deliberately leaves both alone.+- **Ordering under `maxInFlightRequests > 1` without batching** is exactly the+ risk the existing in-code comment describes, and it is unmeasured: a+ configuration-2 run that never hits a broker hiccup proves nothing about+ what happens when one occurs.++## One structural note for whoever lands the follow-up++The three fields ride on `config.kafka`, but they are declared as the optional+members of `KafkaProducerTuning` in+`packages/core/src/modules/ingest/ingest.constants.ts` rather than on+`KafkaConfig` in `packages/core/src/config.ts` — that file is outside+M16-002's declared scope. The loader always sets all three; the fallbacks in+`src/producer-tuning.ts` only apply to a `CoreConfig` built by a test fixture,+and they reproduce today's behaviour. The follow-up is one edit: move the+three fields onto `KafkaConfig` as required numbers, add them to+`packages/core/test/config-fixture.ts`, delete `KafkaProducerTuning` and the+fallbacks, and drop the intersection from `deriveKafkaConfig`'s return type.++The three env vars are also missing from `.env.example`, for the same reason —+it is not in this task's scope.diff --git a/packages/core/src/modules/ingest/ingest.constants.ts b/packages/core/src/modules/ingest/ingest.constants.tsindex 2a50fd571..8f4970c43 100644--- a/packages/core/src/modules/ingest/ingest.constants.ts+++ b/packages/core/src/modules/ingest/ingest.constants.ts@@ -396,3 +396,24 @@ export interface DeprecatedDecrementProfilePayload {property: string;value: number;}++// ----- The Kafka producer's throughput knobs (M16-002) -----+//+// `apps/api/src/config/env.ts` is the only reader of `process.env` (ADR-022+// R7), and `<name>.constants.ts` is the one file of this module it may import+// (R8) — so the shape of the three knobs it sets lives here, and both sides+// break at compile time if a field is renamed. `src/producer-tuning.ts`+// resolves them; `src/kafka.ts` applies them.+//+// They are optional because they ride on `config.kafka`, whose `KafkaConfig`+// interface (`packages/core/src/config.ts`) is outside M16-002's scope and so+// cannot declare them. See the header of `src/producer-tuning.ts`.++export interface KafkaProducerTuning {+ /** kafkajs `maxInFlightRequests`. Default 1: one round-trip at a time. */+ producerMaxInFlight?: number;+ /** Messages per `send()`. Default 1: batching off. */+ producerBatchSize?: number;+ /** A partial batch's maximum wait, in ms. Inert while batching is off. */+ producerBatchLingerMs?: number;+}diff --git a/packages/core/src/modules/ingest/src/kafka.ts b/packages/core/src/modules/ingest/src/kafka.tsindex 6423aacee..cdb9745a3 100644--- a/packages/core/src/modules/ingest/src/kafka.ts+++ b/packages/core/src/modules/ingest/src/kafka.ts@@ -25,6 +25,15 @@ import { createLogger, type ILogger } from '../../../pino-logger';// message shape it hands to this producer, and both files are now siblings.import type { DeadLetterMessage } from './consumer';import type { IncomingEventPayload } from './incoming-event';+import {+ createProducerBatcher,+ type ProducerBatcher,+} from './producer-batcher';+import { sendWithFatalRecovery } from './producer-errors';+import {+ type ResolvedProducerTuning,+ resolveProducerTuning,+} from './producer-tuning';export type { Admin, EachBatchPayload, KafkaMessage } from 'kafkajs';@@ -76,12 +85,16 @@ const getProducer = async (config: CoreConfig): Promise<Producer> => {}if (!producerConnectPromise) {const client = getKafka(config);+ const tuning = resolveProducerTuning(config.kafka);const p = client.producer({idempotent: true,- // 1 (not 5) to avoid in-flight reordering after a transient broker hiccup:- // with idempotency on and low retries, reordered batches trip- // OUT_OF_ORDER_SEQUENCE_NUMBER and stick the producer per-partition.- maxInFlightRequests: 1,+ // Default 1 (not 5) to avoid in-flight reordering after a transient+ // broker hiccup: with idempotency on and low retries, reordered batches+ // trip OUT_OF_ORDER_SEQUENCE_NUMBER and stick the producer per-partition.+ // KAFKA_PRODUCER_MAX_IN_FLIGHT raises it for a measurement run — read+ // docs/KAFKA_PRODUCER_OPTIONS.md first: it is coupled to the retry+ // policy, which is why the two are measured together and not alone.+ maxInFlightRequests: tuning.maxInFlight,allowAutoTopicCreation: true,retry: {retries: config.kafka.producerRetries,@@ -98,6 +111,12 @@ const getProducer = async (config: CoreConfig): Promise<Producer> => {{brokers: config.kafka.brokers,topic: config.kafka.eventsTopic,+ // The throughput knobs, logged once, so a measurement run can be+ // tied to the configuration that produced it.+ maxInFlight: tuning.maxInFlight,+ batchSize: tuning.batchSize,+ batchLingerMs: tuning.lingerMs,+ batching: tuning.batchingEnabled,},'kafka producer connected');@@ -111,33 +130,6 @@ const getProducer = async (config: CoreConfig): Promise<Producer> => {return producerConnectPromise;};-// Kafka error codes that mean the producer's PID/sequence state is-// permanently out of sync with the broker for some partition — only a-// fresh PID (new producer instance) can recover.-// 45 OUT_OF_ORDER_SEQUENCE_NUMBER-// 46 DUPLICATE_SEQUENCE_NUMBER-// 47 INVALID_PRODUCER_EPOCH-// 65 UNKNOWN_PRODUCER_ID-const FATAL_PRODUCER_ERROR_CODES = new Set<number>([45, 46, 47, 65]);--const isFatalProducerError = (err: unknown): boolean => {- if (!err || typeof err !== 'object') {- return false;- }- const name = (err as { name?: string }).name;- // Retries-exceeded leaves the idempotent producer's sequence state- // suspect (broker may have persisted a batch we gave up on), so treat- // it as fatal-for-this-producer too.- if (name === 'KafkaJSNumberOfRetriesExceeded') {- return true;- }- if (name === 'KafkaJSProtocolError') {- const code = (err as { code?: number }).code;- return typeof code === 'number' && FATAL_PRODUCER_ERROR_CODES.has(code);- }- return false;-};-const resetProducer = (config: CoreConfig, broken: Producer): void => {if (producer !== broken) {return;@@ -158,39 +150,68 @@ interface OutgoingMessage {headers?: IHeaders;}-const send = async (+// One send, one or many messages. The batching path (below) and the+// unbatched path are the same call, so a batch that fails resets the producer+// exactly like a lone message did.+const sendMessages = (config: CoreConfig,topic: string,- message: OutgoingMessage-): Promise<void> => {- const p = await getProducer(config);- try {- await p.send({- topic,- timeout: config.kafka.requestTimeoutMs,- messages: [message],- });- } catch (err) {- if (isFatalProducerError(err)) {- kafkaLogger(config).warn(- { err },- 'kafka producer in fatal state; resetting for next call'- );- resetProducer(config, p);- }- throw err;- }+ messages: OutgoingMessage[]+): Promise<void> =>+ getProducer(config).then((p) =>+ sendWithFatalRecovery(+ async () => {+ await p.send({+ topic,+ timeout: config.kafka.requestTimeoutMs,+ messages,+ });+ },+ (err) => {+ kafkaLogger(config).warn(+ { err },+ 'kafka producer in fatal state; resetting for next call'+ );+ resetProducer(config, p);+ }+ )+ );++// Built on the first batched produce, from the tuning the config carries.+// Only the events topic batches: the dead-letter path is low volume and its+// messages are produced one poison record at a time, so it has no round-trip+// to amortise.+let eventsBatcher: ProducerBatcher<OutgoingMessage> | null = null;++const getEventsBatcher = (+ config: CoreConfig,+ tuning: ResolvedProducerTuning+): ProducerBatcher<OutgoingMessage> => {+ eventsBatcher ??= createProducerBatcher<OutgoingMessage>({+ batchSize: tuning.batchSize,+ lingerMs: tuning.lingerMs,+ send: (messages) =>+ sendMessages(config, config.kafka.eventsTopic, messages),+ });+ return eventsBatcher;};export const produceIncomingEvent = async (config: CoreConfig,payload: IncomingEventPayload,partitionKey: string-): Promise<void> =>- send(config, config.kafka.eventsTopic, {+): Promise<void> => {+ const message: OutgoingMessage = {key: Buffer.from(partitionKey),value: Buffer.from(JSON.stringify(payload)),- });+ };+ const tuning = resolveProducerTuning(config.kafka);+ if (!tuning.batchingEnabled) {+ await sendMessages(config, config.kafka.eventsTopic, [message]);+ return;+ }+ await getEventsBatcher(config, tuning).enqueue(message);+};// Why the reason/error/coordinates travel as headers and not in the value: the// value stays the producer's original bytes, so a DLQ message can be replayed@@ -199,19 +220,21 @@ export const produceDeadLetterEvent = async (config: CoreConfig,message: DeadLetterMessage): Promise<void> =>- send(config, config.kafka.eventsDlqTopic, {- key: message.key,- value: message.value,- headers: {- ...message.headers,- 'dlq-source-topic': message.topic,- 'dlq-source-partition': String(message.partition),- 'dlq-source-offset': message.offset,- 'dlq-reason': message.reason,- 'dlq-error': message.error,- 'dlq-at': new Date().toISOString(),+ sendMessages(config, config.kafka.eventsDlqTopic, [+ {+ key: message.key,+ value: message.value,+ headers: {+ ...message.headers,+ 'dlq-source-topic': message.topic,+ 'dlq-source-partition': String(message.partition),+ 'dlq-source-offset': message.offset,+ 'dlq-reason': message.reason,+ 'dlq-error': message.error,+ 'dlq-at': new Date().toISOString(),+ },},- });+ ]);const consumers = new Set<Consumer>();@@ -302,6 +325,15 @@ export const sampleConsumerGroupLag = async (};export const disconnectKafka = async (config: CoreConfig): Promise<void> => {+ // Whatever is still accumulating goes out before the producer closes, so a+ // shutdown inside the linger window cannot strand an accepted event.+ if (eventsBatcher) {+ const batcher = eventsBatcher;+ eventsBatcher = null;+ await batcher.flush().catch((err) => {+ kafkaLogger(config).error({ err }, 'kafka producer batch flush failed');+ });+ }const tasks: Promise<unknown>[] = [];for (const c of consumers) {tasks.push(diff --git a/packages/core/src/modules/ingest/src/producer-batcher.test.ts b/packages/core/src/modules/ingest/src/producer-batcher.test.tsnew file mode 100644index 000000000..58b61e65f--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-batcher.test.ts@@ -0,0 +1,213 @@+/**+ * The batching accumulator's correctness contract (M16-002 deliverable 2b).+ * Batching exists to amortise the produce round-trip, and it is only adoptable+ * if it changes nothing a caller can observe:+ *+ * (i) per-key ordering survives — same-key messages leave in produce+ * order, inside one `send()` and across consecutive sends;+ * (ii) a caller's promise settles on its OWN batch, so a failed send+ * rejects exactly the callers whose messages were in it;+ * (iii) a partially filled batch still goes out inside the linger window;+ * (iv) a failed batch still runs the fatal-producer recovery path.+ *+ * No broker: `send` is injected, which is the same seam `kafka.ts` fills with+ * the real producer call.+ */++import { describe, expect, mock, test } from 'bun:test';+import { createProducerBatcher } from './producer-batcher';+import { sendWithFatalRecovery } from './producer-errors';++const LINGER_MS = 5;+const LINGER_GRACE_MS = 40;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/** A `send` whose completion the test controls, recording what it was given. */+const controllableSend = () => {+ const batches: string[][] = [];+ const settlers: {+ resolve: () => void;+ reject: (err: unknown) => void;+ }[] = [];+ const send = (messages: string[]) => {+ batches.push([...messages]);+ return new Promise<void>((resolve, reject) => {+ settlers.push({ resolve, reject });+ });+ };+ return { batches, settlers, send };+};++/** Swallows a rejection so an unhandled rejection cannot fail the suite. */+const settled = (promise: Promise<void>) =>+ promise.then(+ () => 'resolved' as const,+ (err) => ({ rejected: err })+ );++describe('createProducerBatcher', () => {+ test('sends one batch of many messages once the batch size is reached', async () => {+ const { batches, settlers, send } = controllableSend();+ const batcher = createProducerBatcher<string>({+ batchSize: 3,+ lingerMs: LINGER_MS,+ send,+ });++ const first = settled(batcher.enqueue('a'));+ const second = settled(batcher.enqueue('b'));+ const third = settled(batcher.enqueue('c'));+ await sleep(0);++ expect(batches).toEqual([['a', 'b', 'c']]);+ settlers[0]?.resolve();+ expect(await Promise.all([first, second, third])).toEqual([+ 'resolved',+ 'resolved',+ 'resolved',+ ]);+ });++ test('(i) keeps enqueue order inside a batch and across batches', async () => {+ const { batches, settlers, send } = controllableSend();+ const batcher = createProducerBatcher<string>({+ batchSize: 2,+ lingerMs: LINGER_MS,+ send,+ });++ const produced = ['k1', 'k2', 'k3', 'k4'];+ const promises = produced.map((message) =>+ settled(batcher.enqueue(message))+ );+ await sleep(0);++ // Exactly one send is outstanding: the second batch waits for the first,+ // which is what keeps same-key messages in order across sends regardless+ // of `maxInFlightRequests`.+ expect(batches).toEqual([['k1', 'k2']]);+ settlers[0]?.resolve();+ await sleep(0);+ expect(batches).toEqual([+ ['k1', 'k2'],+ ['k3', 'k4'],+ ]);+ settlers[1]?.resolve();+ await Promise.all(promises);+ expect(batches.flat()).toEqual(produced);+ });++ test('(ii) a failed batch rejects its own callers and nobody else', async () => {+ const { batches, settlers, send } = controllableSend();+ const batcher = createProducerBatcher<string>({+ batchSize: 2,+ lingerMs: LINGER_MS,+ send,+ });++ const failing = [+ settled(batcher.enqueue('a')),+ settled(batcher.enqueue('b')),+ ];+ await sleep(0);+ const surviving = [+ settled(batcher.enqueue('c')),+ settled(batcher.enqueue('d')),+ ];++ const boom = new Error('broker refused the batch');+ settlers[0]?.reject(boom);+ expect(await Promise.all(failing)).toEqual([+ { rejected: boom },+ { rejected: boom },+ ]);++ await sleep(0);+ expect(batches[1]).toEqual(['c', 'd']);+ settlers[1]?.resolve();+ expect(await Promise.all(surviving)).toEqual(['resolved', 'resolved']);+ });++ test('(iii) flushes a partial batch within the linger window', async () => {+ const send = mock((_messages: string[]) => Promise.resolve());+ const batcher = createProducerBatcher<string>({+ batchSize: 100,+ lingerMs: LINGER_MS,+ send,+ });++ const pending = batcher.enqueue('lonely');+ expect(batcher.pendingCount()).toBe(1);+ expect(send).not.toHaveBeenCalled();++ await Promise.race([pending, sleep(LINGER_GRACE_MS)]);++ expect(send).toHaveBeenCalledTimes(1);+ expect(send.mock.calls[0]?.[0]).toEqual(['lonely']);+ await pending;+ expect(batcher.pendingCount()).toBe(0);+ });++ test('(iii) the linger timer of a size-closed batch cannot close its successor', async () => {+ const send = mock((_messages: string[]) => Promise.resolve());+ const batcher = createProducerBatcher<string>({+ batchSize: 2,+ lingerMs: LINGER_MS,+ send,+ });++ await Promise.all([batcher.enqueue('a'), batcher.enqueue('b')]);+ const late = batcher.enqueue('c');+ await sleep(LINGER_GRACE_MS);+ await late;++ expect(send.mock.calls.map((call) => call[0])).toEqual([['a', 'b'], ['c']]);+ });++ test('(iv) a failed batch still runs the fatal-producer recovery', async () => {+ const onFatal = mock((_err: unknown) => undefined);+ const fatal = Object.assign(new Error('out of order'), {+ name: 'KafkaJSProtocolError',+ code: 45,+ });+ const batcher = createProducerBatcher<string>({+ batchSize: 2,+ lingerMs: LINGER_MS,+ send: () => sendWithFatalRecovery(() => Promise.reject(fatal), onFatal),+ });++ const results = await Promise.all([+ settled(batcher.enqueue('a')),+ settled(batcher.enqueue('b')),+ ]);++ expect(results).toEqual([{ rejected: fatal }, { rejected: fatal }]);+ expect(onFatal).toHaveBeenCalledTimes(1);+ expect(onFatal.mock.calls[0]?.[0]).toBe(fatal);+ });++ test('flush sends what is still accumulating and waits for it', async () => {+ const { batches, settlers, send } = controllableSend();+ const batcher = createProducerBatcher<string>({+ batchSize: 100,+ lingerMs: 60_000,+ send,+ });++ const pending = settled(batcher.enqueue('a'));+ let flushed = false;+ const flushing = batcher.flush().then(() => {+ flushed = true;+ });++ await sleep(0);+ expect(batches).toEqual([['a']]);+ expect(flushed).toBe(false);++ settlers[0]?.resolve();+ await flushing;+ expect(flushed).toBe(true);+ expect(await pending).toBe('resolved');+ });+});diff --git a/packages/core/src/modules/ingest/src/producer-batcher.ts b/packages/core/src/modules/ingest/src/producer-batcher.tsnew file mode 100644index 000000000..5ef2ae1b8--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-batcher.ts@@ -0,0 +1,119 @@+// Option 2 of the produce-path options (M16-002): amortise the produce+// round-trip by accumulating messages and sending them as ONE `send()`+// carrying MANY messages, instead of one awaited `send()` per /track request.+//+// It is OFF unless the config loader says otherwise — see `producer-tuning.ts`.+//+// Two invariants the tests hold this file to:+//+// 1. ORDER. Messages leave in the order they were enqueued: within a batch+// because the array keeps that order (kafkajs partitions per message by+// key, and same-key messages in one `send()` land in one partition batch+// in array order), and across batches because this file keeps exactly+// ONE send outstanding at a time. That second half is why the guarantee+// does not depend on `maxInFlightRequests` staying at 1.+// 2. SETTLEMENT. A caller's promise settles on ITS OWN batch's result. A+// failed send rejects exactly the callers whose messages were in it, and+// no others.++interface BatchWaiter {+ resolve: () => void;+ reject: (err: unknown) => void;+}++interface OpenBatch<TMessage> {+ messages: TMessage[];+ waiters: BatchWaiter[];+ lingerTimer: ReturnType<typeof setTimeout> | null;+}++export interface ProducerBatcherOptions<TMessage> {+ /** Messages per `send()`. A batch closes as soon as it reaches this many. */+ batchSize: number;+ /** How long a partially filled batch may wait for company, in ms. */+ lingerMs: number;+ /** Sends one closed batch. Rejecting rejects that batch's callers only. */+ send: (messages: TMessage[]) => Promise<void>;+}++export interface ProducerBatcher<TMessage> {+ /** Resolves when THIS message's batch has been acknowledged. */+ enqueue: (message: TMessage) => Promise<void>;+ /** Closes the open batch and waits for everything already sent. */+ flush: () => Promise<void>;+ /** Messages accumulated but not yet sent. */+ pendingCount: () => number;+}++export const createProducerBatcher = <TMessage>(+ options: ProducerBatcherOptions<TMessage>+): ProducerBatcher<TMessage> => {+ let openBatch: OpenBatch<TMessage> | null = null;+ // The tail of the send chain. It never rejects: `deliver` settles the+ // waiters and returns, so one failed batch cannot break the chain for the+ // batches queued behind it.+ let sendChain: Promise<void> = Promise.resolve();++ const deliver = async (batch: OpenBatch<TMessage>): Promise<void> => {+ try {+ await options.send(batch.messages);+ for (const waiter of batch.waiters) {+ waiter.resolve();+ }+ } catch (err) {+ for (const waiter of batch.waiters) {+ waiter.reject(err);+ }+ }+ };++ const closeOpenBatch = (): void => {+ if (!openBatch) {+ return;+ }+ const batch = openBatch;+ openBatch = null;+ if (batch.lingerTimer) {+ clearTimeout(batch.lingerTimer);+ }+ sendChain = sendChain.then(() => deliver(batch));+ };++ const startLinger = (batch: OpenBatch<TMessage>): void => {+ batch.lingerTimer = setTimeout(() => {+ // Only the batch that armed the timer may be closed by it; a size-+ // triggered close has already replaced `openBatch` by then.+ if (openBatch === batch) {+ closeOpenBatch();+ }+ }, options.lingerMs);+ };++ const enqueue = (message: TMessage): Promise<void> =>+ new Promise<void>((resolve, reject) => {+ const batch: OpenBatch<TMessage> = openBatch ?? {+ messages: [],+ waiters: [],+ lingerTimer: null,+ };+ openBatch = batch;+ batch.messages.push(message);+ batch.waiters.push({ resolve, reject });+ if (batch.messages.length >= options.batchSize) {+ closeOpenBatch();+ return;+ }+ if (!batch.lingerTimer) {+ startLinger(batch);+ }+ });++ return {+ enqueue,+ flush: async () => {+ closeOpenBatch();+ await sendChain;+ },+ pendingCount: () => openBatch?.messages.length ?? 0,+ };+};diff --git a/packages/core/src/modules/ingest/src/producer-errors.test.ts b/packages/core/src/modules/ingest/src/producer-errors.test.tsnew file mode 100644index 000000000..d73680467--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-errors.test.ts@@ -0,0 +1,69 @@+/**+ * The producer's fatal-error classification, split out of `kafka.ts` with+ * M16-002's batching. Only these failures invalidate the idempotent+ * producer's PID/sequence state; everything else must be retried against the+ * SAME producer rather than silently rebuilding it.+ */++import { describe, expect, mock, test } from 'bun:test';+import { isFatalProducerError, sendWithFatalRecovery } from './producer-errors';++const protocolError = (code: number) =>+ Object.assign(new Error(`protocol ${code}`), {+ name: 'KafkaJSProtocolError',+ code,+ });++describe('isFatalProducerError', () => {+ test.each([45, 46, 47, 65])('protocol error %i is fatal', (code) => {+ expect(isFatalProducerError(protocolError(code))).toBe(true);+ });++ test('retries-exceeded is fatal for this producer', () => {+ expect(+ isFatalProducerError(+ Object.assign(new Error('gave up'), {+ name: 'KafkaJSNumberOfRetriesExceeded',+ })+ )+ ).toBe(true);+ });++ test.each([1, 7, 44])('protocol error %i is not fatal', (code) => {+ expect(isFatalProducerError(protocolError(code))).toBe(false);+ });++ test.each([+ ['a plain error', new Error('connection reset')],+ ['a string', 'nope'],+ ['null', null],+ ])('%s is not fatal', (_label, err) => {+ expect(isFatalProducerError(err)).toBe(false);+ });+});++describe('sendWithFatalRecovery', () => {+ test('leaves a successful produce untouched', async () => {+ const onFatal = mock(() => undefined);+ await sendWithFatalRecovery(() => Promise.resolve(), onFatal);+ expect(onFatal).not.toHaveBeenCalled();+ });++ test('rethrows a non-fatal failure without recovering', async () => {+ const onFatal = mock(() => undefined);+ const err = new Error('transient');+ await expect(+ sendWithFatalRecovery(() => Promise.reject(err), onFatal)+ ).rejects.toBe(err);+ expect(onFatal).not.toHaveBeenCalled();+ });++ test('recovers and still rethrows a fatal failure', async () => {+ const onFatal = mock((_err: unknown) => undefined);+ const err = protocolError(65);+ await expect(+ sendWithFatalRecovery(() => Promise.reject(err), onFatal)+ ).rejects.toBe(err);+ expect(onFatal).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/core/src/modules/ingest/src/producer-errors.ts b/packages/core/src/modules/ingest/src/producer-errors.tsnew file mode 100644index 000000000..5c1110a2b--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-errors.ts@@ -0,0 +1,51 @@+// The producer's error classification, split out of `kafka.ts` (M16-002) so+// the batching path can be tested against the same code the single-message+// path uses: a batch that fails must reset the producer exactly like a lone+// message did, and that is only provable if the recovery wrapper is reachable+// without a broker.++// Kafka error codes that mean the producer's PID/sequence state is+// permanently out of sync with the broker for some partition — only a+// fresh PID (new producer instance) can recover.+// 45 OUT_OF_ORDER_SEQUENCE_NUMBER+// 46 DUPLICATE_SEQUENCE_NUMBER+// 47 INVALID_PRODUCER_EPOCH+// 65 UNKNOWN_PRODUCER_ID+const FATAL_PRODUCER_ERROR_CODES = new Set<number>([45, 46, 47, 65]);++export const isFatalProducerError = (err: unknown): boolean => {+ if (!err || typeof err !== 'object') {+ return false;+ }+ const name = (err as { name?: string }).name;+ // Retries-exceeded leaves the idempotent producer's sequence state+ // suspect (broker may have persisted a batch we gave up on), so treat+ // it as fatal-for-this-producer too.+ if (name === 'KafkaJSNumberOfRetriesExceeded') {+ return true;+ }+ if (name === 'KafkaJSProtocolError') {+ const code = (err as { code?: number }).code;+ return typeof code === 'number' && FATAL_PRODUCER_ERROR_CODES.has(code);+ }+ return false;+};++/**+ * Runs a produce call and hands a fatal producer failure to `onFatal` before+ * rethrowing. The error always propagates — `onFatal` is the recovery side+ * effect (drop and rebuild the producer), never a swallow.+ */+export const sendWithFatalRecovery = async (+ produce: () => Promise<void>,+ onFatal: (err: unknown) => void+): Promise<void> => {+ try {+ await produce();+ } catch (err) {+ if (isFatalProducerError(err)) {+ onFatal(err);+ }+ throw err;+ }+};diff --git a/packages/core/src/modules/ingest/src/producer-tuning.test.ts b/packages/core/src/modules/ingest/src/producer-tuning.test.tsnew file mode 100644index 000000000..2a4a027dd--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-tuning.test.ts@@ -0,0 +1,73 @@+/**+ * M16-002's non-negotiable: every default reproduces today's behaviour — one+ * produce round-trip at a time, one message per `send()`. A config that says+ * nothing about the knobs must therefore resolve to exactly that.+ */++import { describe, expect, test } from 'bun:test';+import {+ resolveProducerTuning,+ type TunedKafkaConfig,+} from './producer-tuning';++const kafkaConfig = (+ tuning: Partial<TunedKafkaConfig> = {}+): TunedKafkaConfig =>+ ({+ clientId: 'openpanel',+ brokers: [],+ eventsTopic: 'events',+ eventsDlqTopic: 'events-dlq',+ consumerGroup: 'openpanel-events',+ partitionsConcurrent: 8,+ minMessages: 1,+ maxWaitMs: 500,+ maxMessagesPerPartition: 256,+ sessionTimeoutMs: 30_000,+ heartbeatIntervalMs: 3000,+ requestTimeoutMs: 5000,+ connectionTimeoutMs: 2000,+ producerRetries: 2,+ producerInitialRetryMs: 100,+ producerMaxRetryMs: 1000,+ handlerMaxAttempts: 3,+ handlerRetryInitialMs: 100,+ handlerRetryMaxMs: 1000,+ ...tuning,+ }) satisfies TunedKafkaConfig;++describe('resolveProducerTuning', () => {+ test('an unconfigured config reproduces the pre-M16-002 behaviour', () => {+ const tuning = resolveProducerTuning(kafkaConfig());+ expect(tuning.maxInFlight).toBe(1);+ expect(tuning.batchSize).toBe(1);+ expect(tuning.batchingEnabled).toBe(false);+ });++ test('the loader-supplied defaults also leave batching off', () => {+ const tuning = resolveProducerTuning(+ kafkaConfig({+ producerMaxInFlight: 1,+ producerBatchSize: 1,+ producerBatchLingerMs: 5,+ })+ );+ expect(tuning.maxInFlight).toBe(1);+ expect(tuning.batchingEnabled).toBe(false);+ });++ test('a batch size of two or more turns batching on', () => {+ const tuning = resolveProducerTuning(+ kafkaConfig({ producerBatchSize: 50, producerBatchLingerMs: 10 })+ );+ expect(tuning.batchSize).toBe(50);+ expect(tuning.lingerMs).toBe(10);+ expect(tuning.batchingEnabled).toBe(true);+ });++ test('the in-flight knob passes through to kafkajs untouched', () => {+ expect(+ resolveProducerTuning(kafkaConfig({ producerMaxInFlight: 5 })).maxInFlight+ ).toBe(5);+ });+});diff --git a/packages/core/src/modules/ingest/src/producer-tuning.ts b/packages/core/src/modules/ingest/src/producer-tuning.tsnew file mode 100644index 000000000..eba0d4069--- /dev/null+++ b/packages/core/src/modules/ingest/src/producer-tuning.ts@@ -0,0 +1,50 @@+// The Kafka producer's throughput knobs (M16-002), resolved in one place.+//+// WHERE THESE FIELDS ARE DECLARED, AND WHY IT IS NOT `KafkaConfig`:+// the config loader (`apps/api/src/config/env.ts`) sets them and they ride on+// `config.kafka`, but they are declared as the optional members of+// `KafkaProducerTuning` in this module's `ingest.constants.ts` — the one file+// of this module an app may import (ADR-022 R8) — rather than on `KafkaConfig`+// in `packages/core/src/config.ts`, which is outside M16-002's declared scope.+// Follow-up, one edit: move the three fields onto `KafkaConfig` as required+// numbers, drop `KafkaProducerTuning`, and delete the fallbacks below.+//+// The fallbacks are NOT a second production default: the loader always sets+// all three, so they only apply to a `CoreConfig` built by a test fixture.+// They reproduce today's behaviour exactly — one produce round-trip at a+// time, batching off.++import type { KafkaConfig } from '../../../config';+import type { KafkaProducerTuning } from '../ingest.constants';++/** kafkajs `maxInFlightRequests`: one produce round-trip at a time. */+const FALLBACK_MAX_IN_FLIGHT = 1;+/** Messages per `send()`. 1 = batching off — one message per send, as today. */+const FALLBACK_BATCH_SIZE = 1;+/** A partial batch's maximum wait. Inert while batching is off. */+const FALLBACK_BATCH_LINGER_MS = 5;++/** The smallest batch size that batches anything. */+const BATCHING_MIN_SIZE = 2;++export type TunedKafkaConfig = KafkaConfig & KafkaProducerTuning;++export interface ResolvedProducerTuning {+ maxInFlight: number;+ batchSize: number;+ lingerMs: number;+ /** False keeps the pre-M16-002 path: one message per awaited `send()`. */+ batchingEnabled: boolean;+}++export const resolveProducerTuning = (+ kafka: TunedKafkaConfig+): ResolvedProducerTuning => {+ const batchSize = kafka.producerBatchSize ?? FALLBACK_BATCH_SIZE;+ return {+ maxInFlight: kafka.producerMaxInFlight ?? FALLBACK_MAX_IN_FLIGHT,+ batchSize,+ lingerMs: kafka.producerBatchLingerMs ?? FALLBACK_BATCH_LINGER_MS,+ batchingEnabled: batchSize >= BATCHING_MIN_SIZE,+ };+};