Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/idle-delivery-polling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'seamless-auth-api': patch
---

Webhook and audit sink delivery no longer query the database every second on every instance when nothing is configured to deliver to. Since 0.23.0 both loops ran once a second regardless, which kept pooled connections open and a serverless Postgres (Aurora Serverless v2, Neon and similar) from scaling down. Each loop now polls once a second while a webhook endpoint exists or an audit sink is enabled, and every 30 seconds otherwise, with a single read. Creating an endpoint or creating or enabling a sink wakes the loop on that instance at once; other instances pick it up within 30 seconds. Creating the first webhook endpoint starts delivery at the newest event, as before, so no history is replayed.
2 changes: 1 addition & 1 deletion docs/adr/0005-extensibility-callouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Webhooks and login hook calls are signed with the [Standard Webhooks](https://gi

A dispatcher reads `auth_events` past a cursor (`event_dispatch_cursors`) by `seq` and turns matching rows into deliveries. An event is sent only once its row has committed, nothing is lost between happening and being queued, and the SIEM stream (#420) reads the same rows with the same hashes.

The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second.
The chain trigger updates the chain head row on every insert and holds that lock until commit, so committed rows always form a gapless prefix of `seq`: the cursor cannot step past a row that is still to commit. On first run the cursor starts at the newest row, so turning webhooks on does not replay history. Replicas take turns through an advisory lock. Delivery workers claim due rows with `FOR UPDATE SKIP LOCKED` and lease them past the request timeout, so a replica that dies mid-send leaves the delivery due again shortly after. The loop polls once a second while an endpoint exists. With none it polls every 30 seconds and reads only a count, so an instance with webhooks unused leaves the database idle; creating the first endpoint starts the cursor at the newest row under the dispatch lock, since dispatch did not run while there were none.

### E3. A small, versioned event catalog

Expand Down
24 changes: 12 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions src/lib/deliveryPoller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright © 2026 Fells Code, LLC
* Licensed under the Apache License, Version 2.0
* See LICENSE file in the project root for full license information
*/

export const BUSY_POLL_MS = 1000;
// Long enough that the pool drops its idle connections and a serverless database can scale
// down between ticks when nothing is configured to deliver to.
export const IDLE_POLL_MS = 30_000;

export interface DeliveryPoller {
/** Runs a tick at once, or right after the one in flight. */
wake(): void;
stop(): void;
}

/**
* Runs `tick` after `BUSY_POLL_MS` when it reports work to watch for, after `IDLE_POLL_MS`
* when it does not. Ticks never overlap.
*/
export function startDeliveryPoller(tick: () => Promise<boolean>): DeliveryPoller {
let timer: ReturnType<typeof setTimeout> | null = null;
let running = false;
let wokenWhileRunning = false;
let stopped = false;

function schedule(delayMs: number) {
if (stopped) return;
timer = setTimeout(run, delayMs);
timer.unref();
}

function run() {
timer = null;
running = true;
void tick()
.catch(() => false)
.then((busy) => {
running = false;
const woken = wokenWhileRunning;
wokenWhileRunning = false;
schedule(woken ? 0 : busy ? BUSY_POLL_MS : IDLE_POLL_MS);
});
}

schedule(BUSY_POLL_MS);

return {
wake() {
if (stopped) return;
if (running) {
wokenWhileRunning = true;
return;
}
if (timer) clearTimeout(timer);
schedule(0);
},
stop() {
stopped = true;
if (timer) clearTimeout(timer);
timer = null;
},
};
}
48 changes: 25 additions & 23 deletions src/services/auditSinkService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import type {
CreateAuditSinkRequest,
UpdateAuditSinkRequest,
} from '@seamless-auth/types';
import { Op, QueryTypes } from 'sequelize';
import { QueryTypes } from 'sequelize';

import {
eventRecord,
sendToSink,
sinkDestinationProblem,
testRecord,
} from '../lib/auditSinkTransport.js';
import { type DeliveryPoller, startDeliveryPoller } from '../lib/deliveryPoller.js';
import { AuditSink } from '../models/auditSinks.js';
import { getSequelize } from '../models/index.js';
import getLogger from '../utils/logger.js';
Expand Down Expand Up @@ -122,14 +123,17 @@ export async function createSink(input: CreateAuditSinkRequest, actorUserId: str
assertSettings(input.settings);
const cursorSeq = await startingCursor(input.startAfterSeq);

return AuditSink.create({
const sink = await AuditSink.create({
name: input.name,
kind: input.settings.kind,
settings: input.settings,
enabled: input.enabled ?? true,
cursorSeq: String(cursorSeq),
createdBy: actorUserId,
});

poller?.wake();
return sink;
}

/** A change of settings or a re-enable is tried at once rather than after the backoff. */
Expand All @@ -147,6 +151,7 @@ export async function updateSink(id: string, input: UpdateAuditSinkRequest) {
nextAttemptAt: null,
});

poller?.wake();
return sink;
}

Expand Down Expand Up @@ -251,34 +256,31 @@ async function drainSink(id: string) {
}
}

/** One pass over every enabled sink that is due. Errors are logged, not thrown. */
export async function runAuditSinkTick() {
let poller: DeliveryPoller | null = null;

/**
* One pass over every enabled sink that is due. Returns whether any sink is enabled, which
* decides how soon the next pass runs. Errors are logged, not thrown.
*/
export async function runAuditSinkTick(): Promise<boolean> {
try {
const sinks = await AuditSink.findAll({
attributes: ['id'],
where: {
enabled: true,
[Op.or]: [{ nextAttemptAt: null }, { nextAttemptAt: { [Op.lte]: now() } }],
},
attributes: ['id', 'nextAttemptAt'],
where: { enabled: true },
});
await Promise.all(sinks.map((sink) => drainSink(sink.id)));
const at = now();
const due = sinks.filter((sink) => !sink.nextAttemptAt || sink.nextAttemptAt <= at);
await Promise.all(due.map((sink) => drainSink(sink.id)));
return sinks.length > 0;
} catch (error) {
logger.error(`Audit sink tick failed: ${(error as Error).message}`);
return false;
}
}

const TICK_MS = 1000;

/** Polls once a second, like webhook delivery. Idle, it is one read of a small table. */
/** Polls once a second while a sink is enabled, otherwise every 30 seconds. */
export function startAuditSinkDelivery() {
let running = false;
const timer = setInterval(() => {
if (running) return;
running = true;
void runAuditSinkTick().finally(() => {
running = false;
});
}, TICK_MS);
timer.unref();
return timer;
poller?.stop();
poller = startDeliveryPoller(runAuditSinkTick);
return poller;
}
77 changes: 53 additions & 24 deletions src/services/webhookService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
signedCalloutHeaders,
} from '../lib/calloutSigning.js';
import { CalloutError, calloutRequest, calloutUrlProblem } from '../lib/calloutTransport.js';
import { type DeliveryPoller, startDeliveryPoller } from '../lib/deliveryPoller.js';
import { getSequelize } from '../models/index.js';
import { User } from '../models/users.js';
import { WebhookDelivery, type WebhookDeliveryAttributes } from '../models/webhookDeliveries.js';
Expand Down Expand Up @@ -148,15 +149,38 @@ export async function createEndpoint(
assertSecretKey();

const secret = generateCalloutSecret();
const endpoint = await WebhookEndpoint.create({
url: input.url,
description: input.description ?? null,
eventTypes: input.eventTypes,
enabled: input.enabled ?? true,
createdBy: actorUserId,
...secretColumns(secret),
const sequelize = getSequelize();
const endpoint = await sequelize.transaction(async (transaction) => {
// Dispatch does not run while no endpoint exists, so the cursor may be far behind. The first
// endpoint starts it at the newest row, under the dispatch lock, so turning webhooks on does
// not replay what happened while there were none (ADR 0005, D2).
await sequelize.query('SELECT pg_advisory_xact_lock(:key)', {
replacements: { key: DISPATCH_LOCK_KEY },
transaction,
});
if ((await WebhookEndpoint.count({ transaction })) === 0) {
await sequelize.query(
`INSERT INTO public.event_dispatch_cursors (name, "lastSeq", "updatedAt")
SELECT :name, coalesce(max(seq), 0), now() FROM public.auth_events
ON CONFLICT (name) DO UPDATE SET "lastSeq" = EXCLUDED."lastSeq", "updatedAt" = now()`,
{ replacements: { name: CURSOR_NAME }, transaction },
);
}

return WebhookEndpoint.create(
{
url: input.url,
description: input.description ?? null,
eventTypes: input.eventTypes,
enabled: input.enabled ?? true,
createdBy: actorUserId,
...secretColumns(secret),
},
{ transaction },
);
});

poller?.wake();
return { endpoint, secret };
}

Expand Down Expand Up @@ -197,6 +221,7 @@ export async function updateEndpoint(id: string, input: UpdateWebhookEndpointReq
)[0]
: 0;

if (reenabling) poller?.wake();
return { endpoint, released };
}

Expand Down Expand Up @@ -624,35 +649,39 @@ export async function pruneDeliveries(at: Date = now()) {
});
}

const TICK_MS = 1000;
const PRUNE_EVERY_TICKS = 3600;
const PRUNE_INTERVAL_MS = 60 * 60 * 1000;
let lastPrunedAt = 0;
let poller: DeliveryPoller | null = null;

/** One pass of dispatch and delivery. Errors are logged, not thrown, so the loop keeps running. */
export async function runWebhookTick(tick: number) {
/**
* One pass of dispatch and delivery. Returns whether any endpoint exists, which decides how soon
* the next pass runs. Deliveries cascade with their endpoint, so with none there is nothing to
* send or prune. Errors are logged, not thrown, so the loop keeps running.
*/
export async function runWebhookTick(at: number = Date.now()): Promise<boolean> {
try {
if ((await WebhookEndpoint.count()) === 0) return false;

while ((await dispatchWebhooks()) === DISPATCH_BATCH) {
// A full batch means more rows are waiting.
}
while ((await deliverDue()) === DELIVERY_BATCH) {
// Likewise for due deliveries.
}
if (tick % PRUNE_EVERY_TICKS === 0) await pruneDeliveries();
if (at - lastPrunedAt >= PRUNE_INTERVAL_MS) {
lastPrunedAt = at;
await pruneDeliveries();
}
return true;
} catch (error) {
logger.error(`Webhook tick failed: ${(error as Error).message}`);
return false;
}
}

/** Polls once a second. The loop is cheap when idle: two indexed reads. */
/** Polls once a second while an endpoint exists, otherwise every 30 seconds with one count. */
export function startWebhookDelivery() {
let tick = 0;
let running = false;
const timer = setInterval(() => {
if (running) return;
running = true;
void runWebhookTick(tick++).finally(() => {
running = false;
});
}, TICK_MS);
timer.unref();
return timer;
poller?.stop();
poller = startDeliveryPoller(() => runWebhookTick());
return poller;
}
12 changes: 12 additions & 0 deletions tests/integration/admin/webhooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@ import { Application } from 'express';
import request from 'supertest';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';

const { query, transaction } = vi.hoisted(() => {
const query = vi.fn();
const transaction = vi.fn(async (fn: (t: unknown) => unknown) => fn({}));
return { query, transaction };
});

vi.mock('../../../src/models/index.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/models/index.js')>();
return { ...actual, getSequelize: () => ({ query, transaction }) };
});

vi.mock('../../../src/lib/calloutTransport.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/lib/calloutTransport.js')>();
return { ...actual, calloutRequest: vi.fn() };
Expand Down Expand Up @@ -106,6 +117,7 @@ describe('webhook endpoints', () => {

expect(res.status).toBe(201);
expect(res.body.secret).toMatch(/^whsec_/);
expect(transaction).toHaveBeenCalledTimes(1);
// The audit log is permanent, so a token in the query string must not reach it.
expect(AuthEventService.log).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down
Loading