ingest-api: serialize idempotent ingest to fix SQLSTATE 23000 races
CI / Test ingest-api (push) Has been cancelled
CI / Test api (push) Has been cancelled
CI / Lint and typecheck admin-ui (push) Has been cancelled
CI / Validate Docker build (push) Has been cancelled

Concurrent POSTs with the same Idempotency-Key could pass the initial
SELECT and collide on INSERT into er_ingest_idempotency (unique on
ingest_key_id + idempotency_key), surfacing ER_DUP_ENTRY and risking
duplicate occurrences. Acquire a per-key MySQL named lock before the
idempotency read; on duplicate insert, roll back and replay the stored
response. Document 503 idempotency_busy when GET_LOCK times out.

Adds an integration test for parallel identical idempotent requests (BIT-2530).

Made-with: Cursor
This commit is contained in:
David Santos committed 2026-04-12 10:34:15 +00:00
1 parent 78003b001d
commit 6c22dc8bb9
3 files changed
+142 -14

No files matched your search

+7
View File
@@ -180,6 +180,13 @@ export async function buildApp(input: { env: IngestEnv; pool: Pool }): Promise<F
message: { type: "string" },
},
},
503: {
type: "object",
properties: {
error: { type: "string" },
message: { type: "string" },
},
},
500: {
type: "object",
properties: {
@@ -406,6 +406,50 @@ describe.skipIf(!_testUrl)("two-project passive ingest (BIT-179)", () => {
expect(Number((occ[0] as { c: number }).c)).toBe(3);
});
it("parallel identical idempotent requests yield one stored occurrence", async () => {
const _payload = {
events: [
{
schema_version: 1,
occurred_at: "2026-03-22T14:00:00.000Z",
level: "info",
message: "parallel idempotent ingest probe",
fingerprint: "fp-parallel-idem-probe",
},
],
};
const _headers = {
authorization: `Bearer ${_tokenA}`,
"idempotency-key": "idem-parallel-probe-1",
};
const [_r1, _r2] = await Promise.all([
_app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: _payload,
}),
_app.inject({
method: "POST",
url: "/v1/ingest/events",
headers: _headers,
payload: _payload,
}),
]);
expect(_r1.statusCode).toBe(200);
expect(_r2.statusCode).toBe(200);
expect(_r1.body).toBe(_r2.body);
const [occ] = await _pool.execute<RowDataPacket[]>(
`SELECT COUNT(*) AS c
FROM er_incident_occurrences o
INNER JOIN er_incidents i ON i.id = o.incident_id
WHERE i.project_id = ?
AND o.message = 'parallel idempotent ingest probe'`,
[_projectIdA],
);
expect(Number((occ[0] as { c: number }).c)).toBe(1);
});
it("returns 409 when idempotency key is reused with a different body", async () => {
const _headers = {
authorization: `Bearer ${_tokenA}`,
+91 -14
View File
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import type { Pool, PoolConnection } from "mysql2/promise";
import type { ResultSetHeader, RowDataPacket } from "mysql2";
import {
@@ -45,6 +46,25 @@ export type IngestSkippedResult = {
export type IngestResultItem = IngestStoredResult | IngestSkippedResult;
/** Named lock for parallel idempotent ingests (MySQL max lock name length 64). */
function _idempotencyLockName(ingestKeyId: string, idempotencyKey: string): string {
const h = createHash("sha256")
.update(ingestKeyId, "utf8")
.update("\0", "utf8")
.update(idempotencyKey, "utf8")
.digest("hex")
.slice(0, 32);
return `eri_${h}`;
}
function _isMysqlDuplicateKey(err: unknown): boolean {
if (err === null || typeof err !== "object") {
return false;
}
const o = err as { code?: string; errno?: number };
return o.code === "ER_DUP_ENTRY" || o.errno === 1062;
}
function _parseStoredJson(raw: unknown): unknown {
if (raw === null || raw === undefined) {
return raw;
@@ -69,12 +89,33 @@ export async function processIngestBatch(input: {
events: IngestEventInput[];
idempotencyKey: string | null;
bodyHash: string;
}): Promise<{ status: 200 | 409; body: unknown }> {
}): Promise<{ status: 200 | 409 | 503; body: unknown }> {
const _client = await input.pool.getConnection();
let _lockName: string | null = null;
let _lockHeld = false;
try {
await _client.query("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED");
await _client.beginTransaction();
if (input.idempotencyKey !== null) {
_lockName = _idempotencyLockName(input.ingestKeyId, input.idempotencyKey);
const [lockRows] = await _client.query<RowDataPacket[]>("SELECT GET_LOCK(?, 30) AS got", [
_lockName,
]);
const _got = (lockRows[0] as { got: number | null } | undefined)?.got;
if (_got !== 1) {
await _client.rollback();
return {
status: 503,
body: {
error: "idempotency_busy",
message:
"Could not serialize this idempotent ingest; retry after a short backoff.",
},
};
}
_lockHeld = true;
const [rows] = await _client.execute<RowDataPacket[]>(
`SELECT body_hash, response_json, http_status
FROM er_ingest_idempotency
@@ -125,19 +166,52 @@ export async function processIngestBatch(input: {
const _firstStored = _results.find((r): r is IngestStoredResult => !("skipped" in r));
const _firstIncidentId = _firstStored?.incident_id;
if (typeof _firstIncidentId === "string") {
await _client.execute(
`INSERT INTO er_ingest_idempotency (
ingest_key_id, project_id, idempotency_key, body_hash, incident_id, http_status, response_json
) VALUES (?, ?, ?, ?, ?, 200, ?)`,
[
input.ingestKeyId,
input.projectId,
input.idempotencyKey,
input.bodyHash,
_firstIncidentId,
JSON.stringify(_responseBody),
],
);
try {
await _client.execute(
`INSERT INTO er_ingest_idempotency (
ingest_key_id, project_id, idempotency_key, body_hash, incident_id, http_status, response_json
) VALUES (?, ?, ?, ?, ?, 200, ?)`,
[
input.ingestKeyId,
input.projectId,
input.idempotencyKey,
input.bodyHash,
_firstIncidentId,
JSON.stringify(_responseBody),
],
);
} catch (_insErr) {
if (!_isMysqlDuplicateKey(_insErr)) {
throw _insErr;
}
const [idemRows] = await _client.execute<RowDataPacket[]>(
`SELECT body_hash, response_json, http_status
FROM er_ingest_idempotency
WHERE ingest_key_id = ?
AND idempotency_key = ?
LIMIT 1`,
[input.ingestKeyId, input.idempotencyKey],
);
const _idem = idemRows[0] as
| { body_hash: string; response_json: unknown; http_status: number }
| undefined;
if (!_idem) {
throw _insErr;
}
if (_idem.body_hash !== input.bodyHash) {
await _client.rollback();
return {
status: 409,
body: {
error: "idempotency_conflict",
message:
"The same Idempotency-Key was reused with a different request body. Use a new key or retry the original payload.",
},
};
}
await _client.rollback();
return { status: 200, body: _parseStoredJson(_idem.response_json) };
}
}
}
@@ -151,6 +225,9 @@ export async function processIngestBatch(input: {
await _client.rollback();
throw _err;
} finally {
if (_lockHeld && _lockName !== null) {
await _client.query("SELECT RELEASE_LOCK(?)", [_lockName]);
}
_client.release();
}
}