Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(logs): fail the batch instead of DLQing on a dependency outage (#95200)

Frank Hamandb0fece033c69
diff --git a/nodejs/src/common/kafka/error-handling.test.ts b/nodejs/src/common/kafka/error-handling.test.ts
new file mode 100644
index 000000000000..791f3a0d35be
--- /dev/null
+++ b/nodejs/src/common/kafka/error-handling.test.ts
@@ -0,0 +1,36 @@
+import { DependencyUnavailableError } from '../utils/db/error'
+import { retryOnDependencyUnavailableError } from './error-handling'
+
+describe('retryOnDependencyUnavailableError', () => {
+ const dependencyError = (): DependencyUnavailableError =>
+ new DependencyUnavailableError('down', 'Postgres', new Error('down'))
+
+ it('returns the result once a retry succeeds', async () => {
+ const fn = jest.fn().mockRejectedValueOnce(dependencyError()).mockResolvedValue('ok')
+
+ await expect(retryOnDependencyUnavailableError(fn, { retryCount: 3, initialRetryDelayMs: 1 })).resolves.toBe(
+ 'ok'
+ )
+ expect(fn).toHaveBeenCalledTimes(2)
+ })
+
+ it('rethrows the dependency error after retryCount attempts', async () => {
+ const fn = jest.fn().mockRejectedValue(dependencyError())
+
+ // Guards the limit against a hardcoded attempt count: a retryCount below the hardcoded
+ // value used to fall out of the loop with "Should not get here".
+ await expect(
+ retryOnDependencyUnavailableError(fn, { retryCount: 2, initialRetryDelayMs: 1 })
+ ).rejects.toBeInstanceOf(DependencyUnavailableError)
+ expect(fn).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not retry other errors', async () => {
+ const fn = jest.fn().mockRejectedValue(new Error('bad payload'))
+
+ await expect(retryOnDependencyUnavailableError(fn, { retryCount: 3, initialRetryDelayMs: 1 })).rejects.toThrow(
+ 'bad payload'
+ )
+ expect(fn).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/nodejs/src/common/kafka/error-handling.ts b/nodejs/src/common/kafka/error-handling.ts
index d5a2aa5e90d5..ad7a22036aa3 100644
--- a/nodejs/src/common/kafka/error-handling.ts
+++ b/nodejs/src/common/kafka/error-handling.ts
@@ -26,7 +26,7 @@ export const retryOnDependencyUnavailableError = async <T>(
return await fn()
} catch (error) {
if (error instanceof DependencyUnavailableError) {
- if (currentRetryCount === 4) {
+ if (currentRetryCount === retryCount - 1) {
logger.error('🔁', 'main_loop_error_retry_limit', {
error,
currentRetryCount,
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
index 67fe70cb5193..f0c0f63d64ba 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -17,6 +17,7 @@ import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
+import { DependencyUnavailableError } from '~/common/utils/db/error'
import { closeHub, createHub } from '~/common/utils/db/hub'
import { PostgresUse } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
@@ -232,6 +233,7 @@ describe('LogsIngestionConsumer', () => {
),
}),
usageBatch: new UsageRecordBatch(null, { unit: 'bytes', isTeamEnabled: () => false }),
+ dependencyRetry: { retryCount: 2, initialRetryDelayMs: 1 },
...depsPartial,
},
overrides
@@ -569,29 +571,6 @@ describe('LogsIngestionConsumer', () => {
})
describe('error handling', () => {
- it('should handle producer errors gracefully', async () => {
- const logData = createLogMessage()
- const messages = await createKafkaMessages([logData], {
- token: team.api_token,
- })
-
- // Mock producer's batched-write path to throw — this is what
- // SingleIngestionOutput.queueMessages drives under the hood.
- const originalQueueMessages = mockProducer.queueMessages
- const queueSpy = jest.fn().mockRejectedValue(new Error('Producer error'))
- mockProducer.queueMessages = queueSpy
-
- try {
- // Producer errors are caught and logged, not thrown
- await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
-
- // Verify the producer was called and would have failed
- expect(queueSpy).toHaveBeenCalled()
- } finally {
- mockProducer.queueMessages = originalQueueMessages
- }
- })
-
it('should send failed messages to DLQ', async () => {
const logData = createLogMessage()
const messages = await createKafkaMessages([logData], {
@@ -643,6 +622,64 @@ describe('LogsIngestionConsumer', () => {
}
})
+ it('should retry a dependency blip in place and produce the message', async () => {
+ const logData = createLogMessage()
+ const messages = await createKafkaMessages([logData], {
+ token: team.api_token,
+ })
+
+ const originalQueueMessages = mockProducer.queueMessages
+ const passthrough = originalQueueMessages.bind(mockProducer)
+ let logsProduceAttempts = 0
+ mockProducer.queueMessages = jest.fn().mockImplementation((topicMessages) => {
+ const t = Array.isArray(topicMessages) ? topicMessages[0]?.topic : topicMessages.topic
+ if (t === KAFKA_LOGS_CLICKHOUSE && logsProduceAttempts++ === 0) {
+ throw new DependencyUnavailableError('broker down', 'Kafka', new Error('broker down'))
+ }
+ return passthrough(topicMessages)
+ })
+
+ try {
+ // A blip that clears inside the backoff must not fail the batch: a replay would
+ // produce every other message of the batch a second time.
+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))
+
+ const produced = getProducedKafkaMessages()
+ expect(produced.filter((m) => m.topic === KAFKA_LOGS_CLICKHOUSE)).toHaveLength(1)
+ expect(produced.filter((m) => m.topic === KAFKA_LOGS_INGESTION_DLQ)).toHaveLength(0)
+ } finally {
+ mockProducer.queueMessages = originalQueueMessages
+ }
+ })
+
+ it('should fail the batch instead of DLQing when a dependency is unavailable', async () => {
+ const logData = createLogMessage()
+ const messages = await createKafkaMessages([logData], {
+ token: team.api_token,
+ })
+
+ const originalQueueMessages = mockProducer.queueMessages
+ const passthrough = originalQueueMessages.bind(mockProducer)
+ mockProducer.queueMessages = jest.fn().mockImplementation((topicMessages) => {
+ const t = Array.isArray(topicMessages) ? topicMessages[0]?.topic : topicMessages.topic
+ if (t === KAFKA_LOGS_CLICKHOUSE) {
+ throw new DependencyUnavailableError('broker down', 'Kafka', new Error('broker down'))
+ }
+ return passthrough(topicMessages)
+ })
+
+ try {
+ // The message is good data that succeeds on redelivery. Quarantining it would
+ // move it out of the source topic for an outage that was not its fault.
+ await expect(waitForBackgroundTasks(consumer.processKafkaBatch(messages))).rejects.toThrow(
+ 'broker down'
+ )
+ expect(getProducedKafkaMessages().filter((m) => m.topic === KAFKA_LOGS_INGESTION_DLQ)).toHaveLength(0)
+ } finally {
+ mockProducer.queueMessages = originalQueueMessages
+ }
+ })
+
it('should send a message with an unparseable size header to DLQ instead of ingesting it', async () => {
const logData = createLogMessage()
const messages = await createKafkaMessages([logData], {
@@ -662,20 +699,27 @@ describe('LogsIngestionConsumer', () => {
expect(dlq[0]?.headers?.team_id).toEqual(team.id.toString())
})
- it('should fail the batch when the message cannot be written to the DLQ', async () => {
+ it.each([
+ ['the message fails to parse', { bytes_uncompressed: 'not-a-number' }],
+ ['the message fails to process', {}],
+ ])('should fail the batch when %s and cannot be written to the DLQ', async (_, headers) => {
const logData = createLogMessage()
const messages = await createKafkaMessages([logData], {
token: team.api_token,
- bytes_uncompressed: 'not-a-number',
+ ...headers,
})
+ // Every produce fails: the logs topic write fails the message, and the DLQ write that
+ // follows fails too.
const originalQueueMessages = mockProducer.queueMessages
mockProducer.queueMessages = jest.fn().mockRejectedValue(new Error('DLQ unavailable'))
try {
// Resolving here would commit the source offset with no copy anywhere, so the
// only record of the payload would be gone.
- await expect(consumer.processKafkaBatch(messages)).rejects.toThrow('DLQ unavailable')
+ await expect(waitForBackgroundTasks(consumer.processKafkaBatch(messages))).rejects.toThrow(
+ 'DLQ unavailable'
+ )
} finally {
mockProducer.queueMessages = originalQueueMessages
}
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 257701b1f1f8..f571213a4f62 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -4,6 +4,7 @@ import pLimit from 'p-limit'
import { Counter, Histogram } from 'prom-client'
import { KafkaConsumerInterface, createKafkaConsumer, parseKafkaHeaders } from '~/common/kafka/consumer'
+import { retryOnDependencyUnavailableError } from '~/common/kafka/error-handling'
import { recordPiiReplacements } from '~/common/metrics/otel-metrics'
import { AppMetricsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
@@ -12,6 +13,7 @@ import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'
import { QuotaLimiting, QuotaResource } from '~/common/services/quota-limiting.service'
import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'
import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'
+import { DependencyUnavailableError } from '~/common/utils/db/error'
import { isDevEnv } from '~/common/utils/env-utils'
import { logger } from '~/common/utils/logger'
import { TeamManager } from '~/common/utils/team-manager'
@@ -73,6 +75,12 @@ export interface LogsIngestionConsumerDeps {
*/
outputs: IngestionOutputs<LogsOutput | LogsDlqOutput | AppMetricsOutput>
usageBatch: UsageRecordBatch
+ /**
+ * Backoff for a `DependencyUnavailableError` from the team lookup or a Kafka produce. Defaults
+ * to the `retryOnDependencyUnavailableError` policy (5 tries, 1 s doubling to 16 s). Tests
+ * shorten it.
+ */
+ dependencyRetry?: { retryCount: number; initialRetryDelayMs: number }
}
/** Ingestion default when `logs_settings.retention_days` is unset; must be in `TeamSerializer.VALID_RETENTION_DAYS`. */
@@ -877,12 +885,15 @@ export class LogsIngestionConsumer {
{ token: string; rules: CompiledMetricRule[]; tallies: BatchTallies }
>()
const limit = pLimit(MAX_CONCURRENT_MESSAGE_PROCESSES)
+ let quarantined = 0
const results = await Promise.allSettled(
messages.map((message) =>
limit(async () => {
try {
// Fetch team to get logs_settings
- const team = await this.deps.teamManager.getTeam(message.teamId)
+ const team = await this.retryOnDependencyUnavailable(() =>
+ this.deps.teamManager.getTeam(message.teamId)
+ )
const logsSettings = team?.logs_settings || {}
// Extract settings with defaults
@@ -1010,43 +1021,64 @@ export class LogsIngestionConsumer {
this.queueBytesDroppedByRule(message.teamId, bytesDroppedByRuleId)
// Await so a rejection here lands in the catch and routes to the DLQ.
- await this.deps.outputs.queueMessages(LOGS_OUTPUT, [
- {
- value: processedValue,
- key: null,
- headers: {
- ...parseKafkaHeaders(message.message.headers),
- token: message.token,
- team_id: message.teamId.toString(),
- 'json-parse': jsonParse.toString(),
- 'retention-days': retentionDays.toString(),
- ...(bytesUncompressedHeaderOverride !== undefined
- ? { bytes_uncompressed: bytesUncompressedHeaderOverride.toString() }
- : {}),
- ...(bytesCompressedHeaderOverride !== undefined
- ? { bytes_compressed: bytesCompressedHeaderOverride.toString() }
- : {}),
- ...(recordCountHeaderOverride !== undefined
- ? { record_count: recordCountHeaderOverride.toString() }
- : {}),
+ await this.retryOnDependencyUnavailable(() =>
+ this.deps.outputs.queueMessages(LOGS_OUTPUT, [
+ {
+ value: processedValue,
+ key: null,
+ headers: {
+ ...parseKafkaHeaders(message.message.headers),
+ token: message.token,
+ team_id: message.teamId.toString(),
+ 'json-parse': jsonParse.toString(),
+ 'retention-days': retentionDays.toString(),
+ ...(bytesUncompressedHeaderOverride !== undefined
+ ? { bytes_uncompressed: bytesUncompressedHeaderOverride.toString() }
+ : {}),
+ ...(bytesCompressedHeaderOverride !== undefined
+ ? { bytes_compressed: bytesCompressedHeaderOverride.toString() }
+ : {}),
+ ...(recordCountHeaderOverride !== undefined
+ ? { record_count: recordCountHeaderOverride.toString() }
+ : {}),
+ },
},
- },
- ])
+ ])
+ )
} catch (error) {
+ // A dependency outage (Postgres, Redis, Kafka) is infrastructure-scoped. The
+ // message itself is fine and processes once the dependency is back, so
+ // quarantining it would move good data into the DLQ. The retries above
+ // already absorbed a blip; a longer outage leaves the message on the source
+ // topic and fails the batch below instead.
+ if (error instanceof DependencyUnavailableError) {
+ throw error
+ }
+ // Quarantine succeeded: the DLQ copy is the record of this failure, so the
+ // message resolves and the batch can commit past it. A failed DLQ write
+ // rejects here instead, so the batch keeps the only copy on the source topic.
await this.produceToDlq(message, error)
- throw error
+ quarantined += 1
}
})
)
)
- const failures = results.filter((r) => r.status === 'rejected')
- if (failures.length > 0) {
+ // Every rejection means this batch must not commit: a dependency outage, or a DLQ write
+ // that failed. `Promise.allSettled` swallows rejections, so rethrow before the tallies and
+ // usage metrics are emitted. The rejected background task stops the offset commit and the
+ // consumer replays the batch from the last good commit, which would count them twice.
+ const failures = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')
+ if (failures.length > 0 || quarantined > 0) {
logger.error('Failed to process some log messages', {
+ quarantinedCount: quarantined,
failureCount: failures.length,
totalCount: messages.length,
})
}
+ if (failures.length > 0) {
+ throw failures[0].reason
+ }
await this.emitMetricRuleTallies(metricTalliesByTeam)
}
@@ -1055,6 +1087,15 @@ export class LogsIngestionConsumer {
await this.produceRawToDlq(message.message, error, { token: message.token, teamId: message.teamId })
}
+ /**
+ * Absorb a dependency blip in place. A batch that fails after some of its messages were
+ * produced is replayed in full, and the logs table has no dedupe, so every retry here is a
+ * duplicate avoided. Only an outage that outlasts the backoff reaches the caller.
+ */
+ private retryOnDependencyUnavailable<T>(fn: () => Promise<T>): Promise<T> {
+ return retryOnDependencyUnavailableError(fn, this.deps.dependencyRetry)
+ }
+
/**
* Quarantine a raw Kafka message. Takes the message rather than a `LogsIngestionMessage` so
* failures from before the team is resolved can reach the DLQ too — those used to be counted
@@ -1073,25 +1114,27 @@ export class LogsIngestionConsumer {
recordLogMessageDlq(errorName, teamIdLabel)
try {
- await this.deps.outputs.queueMessages(LOGS_DLQ_OUTPUT, [
- {
- value: message.value,
- key: null,
- headers: {
- ...parseKafkaHeaders(message.headers),
- ...(context.token !== undefined ? { token: context.token } : {}),
- team_id: teamIdLabel,
- error_message: errorMessage,
- error_name: errorName,
- failed_at: new Date().toISOString(),
- // Where the message came from, so a quarantined record can be read back
- // from the source partition and replayed against the consumer.
- source_topic: message.topic,
- source_partition: message.partition.toString(),
- source_offset: message.offset.toString(),
+ await this.retryOnDependencyUnavailable(() =>
+ this.deps.outputs.queueMessages(LOGS_DLQ_OUTPUT, [
+ {
+ value: message.value,
+ key: null,
+ headers: {
+ ...parseKafkaHeaders(message.headers),
+ ...(context.token !== undefined ? { token: context.token } : {}),
+ team_id: teamIdLabel,
+ error_message: errorMessage,
+ error_name: errorName,
+ failed_at: new Date().toISOString(),
+ // Where the message came from, so a quarantined record can be read back
+ // from the source partition and replayed against the consumer.
+ source_topic: message.topic,
+ source_partition: message.partition.toString(),
+ source_offset: message.offset.toString(),
+ },
},
- },
- ])
+ ])
+ )
} catch (dlqError) {
logger.error('Failed to produce message to DLQ', {
error: dlqError,