Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

perf(ingest): drop the per-event duplicate marker

Carl-Gerhard Lindesvärdaaf02b1b0ab2
diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts
index 5f4c54293..8e8eb2e3c 100644
--- a/apps/api/src/config/env.ts
+++ b/apps/api/src/config/env.ts
@@ -65,18 +65,6 @@ const DEFAULT_KAFKA_HANDLER_RETRY_INITIAL_MS = 100;
const DEFAULT_KAFKA_HANDLER_RETRY_MAX_MS = 1000;
const DEFAULT_KAFKA_SASL_MECHANISM: KafkaSaslMechanism = 'scram-sha-512';
-/**
- * How long a duplicate marker outlives its event — it only needs to outlive
- * the replay window, not the data. Two minutes gives comfortable margin over
- * observed redelivery windows (a consumer-eviction rejoin lands in seconds; a
- * lost-ACK replay lands ~30s out) and covers a process restart resuming from
- * its last committed offset.
- *
- * It also sets the live key count (`events/s x TTL`), so raising it is a
- * direct Redis-memory cost, not a free knob.
- */
-const DEFAULT_INGEST_DUPLICATE_MARKER_TTL_MS = 120_000;
-
/** The Kafka events consumer's token. The old `events_kafka` spelling gets its own error (`RENAMED_QUEUE_TOKENS`), not an alias. */
export const KAFKA_QUEUE_TOKEN = 'events';
@@ -495,10 +483,6 @@ const rawSchema = z.object({
DEFAULT_INGEST_DEAD_LETTER_MAX_ENTRIES
),
- INGEST_DUPLICATE_MARKER_TTL_MS: positiveIntWithDefault(
- DEFAULT_INGEST_DUPLICATE_MARKER_TTL_MS
- ),
-
BUFFER_ASYNC_INSERTS: definedIsTrueSchema,
BUFFER_CH_INSERT_CONCURRENCY: optionalPositiveInt,
BOT_BUFFER_BATCH_SIZE: optionalPositiveInt,
@@ -933,7 +917,6 @@ export interface Config {
/** Sits here, not in `core.kafka`: `apps/api` picks the dead-letter sink and core only gets the `sendToDeadLetter` seam. */
INGEST_DEAD_LETTER_MAX_ENTRIES: number;
/** Sits here, not in `core.kafka`: the marker is keyed on the event, not a Kafka coordinate. */
- INGEST_DUPLICATE_MARKER_TTL_MS: number;
/** The CORS delegator's origin allowlist, order-sensitive. */
dashboardOrigins: string[];
/** `ENABLE_VERBOSE_LOGGING`, already split. */
@@ -978,7 +961,6 @@ const envSchema = rawSchema
SHUTDOWN_FORCE_EXIT_MS: raw.SHUTDOWN_FORCE_EXIT_MS,
REDIS_CACHE_COMMAND_TIMEOUT_MS: raw.REDIS_CACHE_COMMAND_TIMEOUT_MS,
INGEST_DEAD_LETTER_MAX_ENTRIES: raw.INGEST_DEAD_LETTER_MAX_ENTRIES,
- INGEST_DUPLICATE_MARKER_TTL_MS: raw.INGEST_DUPLICATE_MARKER_TTL_MS,
dashboardOrigins: [
dashboardUrl,
...splitTokens(raw.API_CORS_ORIGINS),
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index 8402e106d..1e2c922c0 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -63,7 +63,6 @@ import { db, Prisma } from '@openpanel/db/src/prisma-client';
import {
configureRedisCache,
createDeadLetterRecorder,
- createDuplicateEventMarker,
getRedisCache,
getRedisPub,
getRedisQueue,
@@ -238,14 +237,6 @@ async function startIngestConsumer(
// here, once: the notification dispatch has no Ctx slot in its signature.
handleEvent: createIncomingEventHandler(deps, {
checkNotificationRulesForEvent,
- // MARKS a redelivery, never drops one — the event is inserted either
- // way. The CACHE client, again, and for the same reason: a handler
- // that blocks on Redis risks evicting the consumer past its session
- // timeout, and an eviction is what causes duplicate rows.
- markDuplicateEvent: createDuplicateEventMarker({
- client: deps.redis,
- ttlMs: config.INGEST_DUPLICATE_MARKER_TTL_MS,
- }),
}),
// A capped Redis list, and the event is DROPPED whether or not the record lands: a Kafka DLQ topic nothing creates
// held the offset back in a redelivery loop. The CACHE client, not the queue client: only that one fails fast, and
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
index 666f75bb1..028d1b7e4 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.test.ts
@@ -7,7 +7,6 @@
// mapping are still pinned here, not re-implemented by the test.
import { beforeEach, describe, expect, mock, test } from 'bun:test';
-import { createDuplicateEventMarker } from '@openpanel/redis';
import { formatClickhouseDate } from '../../event/src/dates';
import type { IClickhouseSession } from '../../session/session.service';
import {
@@ -154,10 +153,6 @@ function makeDeps() {
const enqueueSessionEnd = mock<IncomingEventDeps['enqueueSessionEnd']>(
async () => undefined
);
- const markDuplicate = mock<IncomingEventDeps['markDuplicate']>(
- async () => false
- );
- const duplicateMarked = mock(() => undefined);
const deps: IncomingEventDeps = {
logger: noopLogger,
sessions: { getExistingSession, ingest },
@@ -168,11 +163,9 @@ function makeDeps() {
markFirstEvent: mock(async () => undefined),
},
enqueueSessionEnd,
- markDuplicate,
metrics: {
sessionStarted: mock(() => undefined),
sessionEndEnqueued: mock(() => undefined),
- duplicateMarked,
},
};
return {
@@ -181,8 +174,6 @@ function makeDeps() {
getExistingSession,
ingest,
enqueueSessionEnd,
- markDuplicate,
- duplicateMarked,
};
}
@@ -465,165 +456,3 @@ describe('incomingEvent', () => {
expect(enqueueSessionEnd).not.toHaveBeenCalled();
});
});
-
-/**
- * MARK MEANS COUNT AND LOG: the marker does not suppress, so every test below
- * asserts the event was still INSERTED.
- */
-describe('duplicate marker', () => {
- const TTL_MS = 120_000;
- const OTHER_EVENT_ID = '99999999-8888-4777-8666-555555555555';
-
- /**
- * Enough of Redis for `SET key NX PX`, with a hand-driven clock so the
- * expiry is asserted rather than slept through. The REAL marker runs against
- * it, so the key shape and the `NX` semantics are under test too.
- */
- function fakeRedis() {
- const keys = new Map<string, number>();
- let nowMs = 0;
- return {
- advance: (ms: number) => {
- nowMs += ms;
- },
- keyCount: () => {
- for (const [key, expiresAt] of keys) {
- if (expiresAt <= nowMs) {
- keys.delete(key);
- }
- }
- return keys.size;
- },
- set: (key: string, _value: string, _px: 'PX', ttlMs: number) => {
- const expiresAt = keys.get(key);
- if (expiresAt !== undefined && expiresAt > nowMs) {
- return Promise.resolve(null);
- }
- keys.set(key, nowMs + ttlMs);
- return Promise.resolve('OK');
- },
- };
- }
-
- function depsWithRealMarker() {
- const redis = fakeRedis();
- const built = makeDeps();
- built.deps.markDuplicate = createDuplicateEventMarker({
- client: redis,
- ttlMs: TTL_MS,
- });
- return { ...built, redis };
- }
-
- test('marks the second delivery of one id, and inserts BOTH', async () => {
- const { deps, createEvent, ingest, duplicateMarked } = depsWithRealMarker();
- ingest.mockResolvedValue({ kind: 'extend', current: makeSession() });
- const envelope = buildJobData({ id: producedEventId });
-
- await incomingEvent(envelope, deps);
- expect(duplicateMarked).not.toHaveBeenCalled();
-
- await incomingEvent(envelope, deps);
- expect(duplicateMarked).toHaveBeenCalledTimes(1);
-
- // The whole point: the redelivery is COUNTED, not suppressed. Two
- // inserts, both carrying the producer's id.
- const inserted = createdEvents(createEvent);
- expect(inserted).toHaveLength(2);
- expect(inserted.every((event) => event.id === producedEventId)).toBe(true);
- });
-
- test('never marks distinct ids', async () => {
- const { deps, createEvent, ingest, duplicateMarked } = depsWithRealMarker();
- ingest.mockResolvedValue({ kind: 'extend', current: makeSession() });
-
- await incomingEvent(buildJobData({ id: producedEventId }), deps);
- await incomingEvent(buildJobData({ id: OTHER_EVENT_ID }), deps);
-
- expect(duplicateMarked).not.toHaveBeenCalled();
- expect(createdEvents(createEvent)).toHaveLength(2);
- });
-
- test('the key expires, so a replay past the TTL is unmarked', async () => {
- const { deps, ingest, duplicateMarked, redis } = depsWithRealMarker();
- ingest.mockResolvedValue({ kind: 'extend', current: makeSession() });
- const envelope = buildJobData({ id: producedEventId });
-
- await incomingEvent(envelope, deps);
- expect(redis.keyCount()).toBe(1);
-
- redis.advance(TTL_MS + 1);
- expect(redis.keyCount()).toBe(0);
-
- await incomingEvent(envelope, deps);
- expect(duplicateMarked).not.toHaveBeenCalled();
- });
-
- test('a payload with no producer-minted id costs no Redis call', async () => {
- const { deps, createEvent, ingest, markDuplicate } = ctx;
- ingest.mockResolvedValueOnce({ kind: 'extend', current: makeSession() });
-
- await incomingEvent(buildJobData(), deps);
-
- expect(markDuplicate).not.toHaveBeenCalled();
- expect(createdEvents(createEvent)).toHaveLength(1);
- });
-
- /**
- * THE REGRESSION TEST THAT MATTERS. A blocking Redis call in this path
- * previously evicted the consumer past its 30s session timeout — an
- * eviction is the only reassignment that costs duplicate rows. This must
- * not happen again.
- */
- test('Redis unavailable: the event is processed normally and nothing throws', async () => {
- const { deps, createEvent, ingest, markDuplicate, duplicateMarked } = ctx;
- ingest.mockResolvedValueOnce({ kind: 'extend', current: makeSession() });
- markDuplicate.mockImplementation(() =>
- Promise.reject(
- new Error(
- "Stream isn't writeable and enableOfflineQueue options is false"
- )
- )
- );
-
- const event = await incomingEvent(
- buildJobData({ id: producedEventId }),
- deps
- );
-
- expect(event).not.toBeNull();
- expect(createdEvents(createEvent)).toHaveLength(1);
- expect(createdEvents(createEvent)[0]!.id).toBe(producedEventId);
- // Fail open means fail SILENT to the counter: an unwritten marker is not
- // evidence of a duplicate.
- expect(duplicateMarked).not.toHaveBeenCalled();
- });
-
- test('the marker runs alongside the handler, never in front of it', async () => {
- // "Not slowed" asserted structurally rather than with a stopwatch: the
- // marker is started BEFORE the handler's own Redis work and awaited AFTER
- // it, so a slow marker overlaps a slow session read instead of adding to
- // it. A serial check would give mark:start, mark:end, ingest:start — which
- // is the shape that would put the eviction trigger back.
- const timeline: string[] = [];
- const slow = () => new Promise((resolve) => setTimeout(resolve, 20));
- const { deps, ingest, markDuplicate } = ctx;
- markDuplicate.mockImplementation(async () => {
- timeline.push('mark:start');
- await slow();
- timeline.push('mark:end');
- return false;
- });
- ingest.mockImplementation(async () => {
- timeline.push('ingest:start');
- await slow();
- timeline.push('ingest:end');
- return { kind: 'extend', current: makeSession() };
- });
-
- await incomingEvent(buildJobData({ id: producedEventId }), deps);
-
- expect(timeline.slice(0, 2)).toEqual(['mark:start', 'ingest:start']);
- expect(timeline).toContain('mark:end');
- });
-});
diff --git a/packages/core/src/modules/ingest/src/incoming-event-handler.ts b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
index bc0cce2cc..b4f55c9ca 100644
--- a/packages/core/src/modules/ingest/src/incoming-event-handler.ts
+++ b/packages/core/src/modules/ingest/src/incoming-event-handler.ts
@@ -28,7 +28,7 @@ import type { IClickhouseSession } from '../../session/session.service';
import { sessionEndsEnqueued } from '../../session/src/session.metrics';
import type { EnqueueSessionEndInput } from '../../session/src/session-end';
import type { IncomingEventPayload } from './incoming-event';
-import { duplicateEventsMarkedTotal, sessionsStarted } from './ingest.metrics';
+import { sessionsStarted } from './ingest.metrics';
const GLOBAL_PROPERTIES = ['__path', '__referrer', '__timestamp', '__revenue'];
@@ -65,8 +65,6 @@ export interface IncomingEventSessions {
export interface IncomingEventMetrics {
sessionStarted(kind: 'new' | 'boundary'): void;
sessionEndEnqueued(source: 'boundary'): void;
- /** One event whose producer-minted id had already been seen. */
- duplicateMarked(): void;
}
export interface IncomingEventDeps {
@@ -86,14 +84,6 @@ export interface IncomingEventDeps {
markFirstEvent(projectId: string): Promise<unknown>;
};
enqueueSessionEnd(input: EnqueueSessionEndInput): Promise<unknown>;
- /**
- * Claim the producer-minted event id. Resolves true when the id has been
- * seen before — a redelivery — and false on its first sighting.
- *
- * MARK, NOT DEDUPE: the caller counts and logs, and inserts the event
- * either way. It may reject; the caller then processes the event normally.
- */
- markDuplicate(eventId: string): Promise<boolean>;
metrics: IncomingEventMetrics;
}
@@ -115,12 +105,6 @@ export interface IncomingEventBindings {
deps: Ctx,
payload: IServiceCreateEventPayload
): Promise<unknown>;
- /**
- * `@openpanel/redis`'s `createDuplicateEventMarker`, already bound to the TTL
- * `apps/api` parsed. Injected rather than built here so the key prefix and
- * TTL stay out of the per-message path.
- */
- markDuplicateEvent(eventId: string): Promise<boolean>;
}
/**
@@ -148,11 +132,9 @@ export function createIncomingEventDeps(
},
},
enqueueSessionEnd: (input) => ctx.services.session.enqueueSessionEnd(input),
- markDuplicate: (eventId) => bindings.markDuplicateEvent(eventId),
metrics: {
sessionStarted: (kind) => sessionsStarted.inc({ kind }),
sessionEndEnqueued: (source) => sessionEndsEnqueued.inc({ source }),
- duplicateMarked: () => duplicateEventsMarkedTotal.inc(),
},
};
}
@@ -235,50 +217,6 @@ const parseRevenue = (revenue: unknown): number | undefined => {
return undefined;
};
-/**
- * Claim the event id and report a redelivery. THE EVENT IS INSERTED EITHER
- * WAY — this counts and logs, it does not drop, and nothing downstream reads
- * its answer. A false positive on a suppressing check would be silent data
- * loss, and whether the events table ever gets dedupe is not decided here.
- *
- * Catches redeliveries of the SAME id (crash, eviction, durability redelivery,
- * rebalance, restart). It does NOT catch a lost ACK, where the SDK re-sends and
- * the producer mints a fresh id per request.
- *
- * FAILS OPEN, AND NEVER REJECTS. Redis being away is exactly when redeliveries
- * happen, so an observability counter must not be the thing that delays or
- * loses an event — a handler blocked on Redis risks being evicted past its
- * session timeout, which itself causes duplicate rows.
- */
-function startDuplicateMark(
- eventId: string | undefined,
- projectId: string,
- logger: Logger,
- deps: IncomingEventDeps
-): Promise<void> {
- if (!eventId) {
- return Promise.resolve();
- }
- return deps
- .markDuplicate(eventId)
- .then((seenBefore) => {
- if (!seenBefore) {
- return;
- }
- deps.metrics.duplicateMarked();
- logger.warn(
- { eventId, projectId },
- 'DUPLICATE event id — already ingested, inserting it anyway'
- );
- })
- .catch((error) => {
- logger.warn(
- { err: error, eventId },
- 'could not mark duplicate — this event is unchecked'
- );
- });
-}
-
export async function incomingEvent(
jobPayload: IncomingEventPayload,
deps: IncomingEventDeps,
@@ -294,21 +232,7 @@ export async function incomingEvent(
kafkaOffset: meta.offset,
})
: deps.logger;
- // Started BEFORE the handler's own Redis work and awaited AFTER it, so the
- // marker's round trip overlaps the session buffer's GET and EVAL on the same
- // client: healthy it costs the handler nothing measurable, and under a
- // frozen Redis its bound is one the handler was already paying.
- const duplicateMark = startDuplicateMark(
- jobPayload.id,
- jobPayload.projectId,
- logger,
- deps
- );
- try {
- return await ingestIncomingEvent(jobPayload, deps, logger);
- } finally {
- await duplicateMark;
- }
+ return await ingestIncomingEvent(jobPayload, deps, logger);
}
async function ingestIncomingEvent(
diff --git a/packages/core/src/modules/ingest/src/ingest.metrics.ts b/packages/core/src/modules/ingest/src/ingest.metrics.ts
index 4922ecb44..aabdcdedf 100644
--- a/packages/core/src/modules/ingest/src/ingest.metrics.ts
+++ b/packages/core/src/modules/ingest/src/ingest.metrics.ts
@@ -4,21 +4,6 @@ import client from 'prom-client';
import { registry } from '../../../metrics';
import type { ConsumerMetrics, DeadLetterReason } from './consumer';
-// Events whose producer-minted id had already been seen. This is a MARKER, not
-// a dedupe: the event is inserted either way and this counter is the whole
-// point of the check. The older offset-keyed counter lived in one process's
-// heap and was blind to every duplicate that mattered (161 real duplicates,
-// 0 reprocessed increments).
-//
-// It UNDERCOUNTS by design: a duplicate whose marker could not be written
-// (Redis away) is not counted, because the check fails open rather than
-// delaying the event.
-export const duplicateEventsMarkedTotal = new client.Counter({
- name: 'ingest_duplicate_events_marked_total',
- help: 'Events whose producer-minted id had already been seen (marked, still inserted)',
- registers: [registry],
-});
-
// Handler exceptions on the Kafka ingest path, counted per attempt — retries
// included, so the series shows real failure pressure and not just the
// messages that ran out of attempts.
diff --git a/packages/core/test/request-id-end-to-end.test.ts b/packages/core/test/request-id-end-to-end.test.ts
index 25ece8fa8..a5f36c9a4 100644
--- a/packages/core/test/request-id-end-to-end.test.ts
+++ b/packages/core/test/request-id-end-to-end.test.ts
@@ -530,8 +530,6 @@ function ingestDeps() {
const ingestBindings: IncomingEventBindings = {
checkNotificationRulesForEvent: () => Promise.resolve(null),
- // Never a duplicate: this suite is about the requestId.
- markDuplicateEvent: () => Promise.resolve(false),
};
function ingestEnvelope(requestId?: string): IncomingEventPayload {
diff --git a/packages/redis/duplicate-marker.test.ts b/packages/redis/duplicate-marker.test.ts
deleted file mode 100644
index d8881a796..000000000
--- a/packages/redis/duplicate-marker.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/** The event-keyed duplicate marker at the Redis boundary: one `SET key NX PX`, the key shape, and which reply means "seen before". Uses an in-memory stand-in with real `NX` and expiry semantics. */
-
-import { describe, expect, it } from 'vitest';
-import {
- createDuplicateEventMarker,
- DUPLICATE_MARKER_KEY_PREFIX,
- type DuplicateMarkerRedisClient,
-} from './duplicate-marker';
-
-const TTL_MS = 120_000;
-const EVENT_ID = '11111111-2222-4333-8444-555555555555';
-const OTHER_EVENT_ID = '99999999-8888-4777-8666-555555555555';
-
-function fakeRedis() {
- const expiries = new Map<string, number>();
- const commands: unknown[][] = [];
- let nowMs = 0;
-
- const client: DuplicateMarkerRedisClient = {
- set(key, value, expiryMode, ttlMs, setMode) {
- commands.push([key, value, expiryMode, ttlMs, setMode]);
- const expiresAt = expiries.get(key);
- if (expiresAt !== undefined && expiresAt > nowMs) {
- return Promise.resolve(null);
- }
- expiries.set(key, nowMs + ttlMs);
- return Promise.resolve('OK');
- },
- };
-
- return {
- client,
- commands,
- advance: (ms: number) => {
- nowMs += ms;
- },
- };
-}
-
-describe('createDuplicateEventMarker', () => {
- it('reports the first sighting of an id as not-a-duplicate', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- });
-
- expect(await mark(EVENT_ID)).toBe(false);
- });
-
- it('reports the second sighting of the same id as a duplicate', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- });
-
- await mark(EVENT_ID);
-
- expect(await mark(EVENT_ID)).toBe(true);
- });
-
- it('keeps distinct ids independent', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- });
-
- await mark(EVENT_ID);
-
- expect(await mark(OTHER_EVENT_ID)).toBe(false);
- });
-
- it('forgets an id once its key has expired', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- });
-
- await mark(EVENT_ID);
- redis.advance(TTL_MS + 1);
-
- expect(await mark(EVENT_ID)).toBe(false);
- });
-
- it('costs exactly one command per event, a prefixed SET NX PX', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- });
-
- await mark(EVENT_ID);
-
- expect(redis.commands).toEqual([
- [`${DUPLICATE_MARKER_KEY_PREFIX}${EVENT_ID}`, '1', 'PX', TTL_MS, 'NX'],
- ]);
- });
-
- it('takes a key prefix override without touching the default', async () => {
- const redis = fakeRedis();
- const mark = createDuplicateEventMarker({
- client: redis.client,
- ttlMs: TTL_MS,
- keyPrefix: 'test:dup:',
- });
-
- await mark(EVENT_ID);
-
- expect(redis.commands[0]![0]).toBe(`test:dup:${EVENT_ID}`);
- expect(DUPLICATE_MARKER_KEY_PREFIX).toBe('ingest:duplicate:');
- });
-
- it('rejects when Redis does not answer, leaving the decision to the caller', async () => {
- const mark = createDuplicateEventMarker({
- client: {
- set: () => Promise.reject(new Error('Stream is not writeable')),
- },
- ttlMs: TTL_MS,
- });
-
- await expect(mark(EVENT_ID)).rejects.toThrow('Stream is not writeable');
- });
-});
diff --git a/packages/redis/duplicate-marker.ts b/packages/redis/duplicate-marker.ts
deleted file mode 100644
index ae7d73c1a..000000000
--- a/packages/redis/duplicate-marker.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * The ingest consumer's duplicate MARKER.
- *
- * It is keyed on the EVENT, not on a Kafka offset. The event `id` is
- * producer-minted, so a redelivered message re-presents the same id. A key
- * therefore survives restarts, rebalances, evictions and process boundaries,
- * none of which an in-process watermark would.
- *
- * MARK MEANS COUNT AND LOG. IT DOES NOT MEAN DROP. This tells the caller the
- * id has been seen before; the caller inserts the event either way. A false
- * positive on a suppressing check is silent data loss, so whether the events
- * table ever gets real dedupe is a separate decision from this marker.
- *
- * ONE round trip, `SET key NX PX`: the set and the "did it already exist" answer are the same command.
- *
- * IT MUST BE GIVEN THE CACHE CLIENT. That one fails fast: offline queue off
- * once connected, `commandTimeout` 500 ms. `getRedisQueue` keeps
- * `maxRetriesPerRequest: null` for BullMQ and would block a handler for tens
- * of seconds, risking exactly the kind of consumer eviction — past its Kafka
- * session timeout — that produces duplicate rows.
- */
-
-/** Live key prefix. An operator has to be able to find these. */
-export const DUPLICATE_MARKER_KEY_PREFIX = 'ingest:duplicate:';
-
-/**
- * The narrow slice of a Redis client this needs. Structural rather than
- * ioredis's `Redis`, so a test can satisfy it without a server.
- */
-export interface DuplicateMarkerRedisClient {
- set(
- key: string,
- value: string,
- expiryMode: 'PX',
- ttlMs: number,
- setMode: 'NX'
- ): Promise<string | null>;
-}
-
-export interface DuplicateEventMarkerOptions {
- client: DuplicateMarkerRedisClient;
- /**
- * How long a marker outlives its event. It only has to outlive the REPLAY
- * window, not the data.
- */
- ttlMs: number;
- /** Overridable for tests; production uses the constant above. */
- keyPrefix?: string;
-}
-
-/** The marker's only stored value — presence is the whole signal. */
-const MARKER_VALUE = '1';
-
-/**
- * @returns true when this event id has been seen before, false when this call
- * is the first sighting.
- *
- * REJECTS when Redis does not answer. The caller decides what that means, and
- * on the ingest path the answer is always "process the event normally" — an
- * observability counter must never be the reason an event is delayed or lost.
- */
-export function createDuplicateEventMarker(
- options: DuplicateEventMarkerOptions
-): (eventId: string) => Promise<boolean> {
- const keyPrefix = options.keyPrefix ?? DUPLICATE_MARKER_KEY_PREFIX;
-
- return async (eventId: string): Promise<boolean> => {
- const stored = await options.client.set(
- `${keyPrefix}${eventId}`,
- MARKER_VALUE,
- 'PX',
- options.ttlMs,
- 'NX'
- );
- // `SET NX` answers 'OK' when it wrote the key and null when one was
- // already there — so null IS the duplicate.
- return stored === null;
- };
-}
diff --git a/packages/redis/index.ts b/packages/redis/index.ts
index 709bee287..5e8eb97bb 100644
--- a/packages/redis/index.ts
+++ b/packages/redis/index.ts
@@ -1,6 +1,5 @@
export * from './cachable';
export * from './dead-letter';
-export * from './duplicate-marker';
export * from './publisher';
export * from './redis';
export * from './run-every';