Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix: batch delete of expired identity access token revocations

Claude9ea65ba91511
diff --git a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
index 1d7e11da6e..ea3a688b65 100644
--- a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
@@ -1,6 +1,7 @@
import { TDbClient } from "@app/db";
import { TableName, TIdentityAccessTokenRevocations } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
type TRevocationRow = Pick<TIdentityAccessTokenRevocations, "id" | "identityId" | "revokedAt" | "createdAt" | "scope">;
@@ -20,6 +21,10 @@ type TInsertRevocationInput = {
scope?: string | null;
};
+const QUERY_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
+const REVOCATION_PRUNE_BATCH_SIZE = 10000;
+const MAX_RETRY_ON_FAILURE = 3;
+
export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
const insertRevocation = async (row: TInsertRevocationInput) => {
try {
@@ -69,12 +74,62 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
}
};
+ // Deletes expired revocation markers in bounded batches so a single run never holds a long-lived
+ // lock / large WAL burst against this high-volume table. Mirrors the batched-prune convention used
+ // by the other DailyResourceCleanup jobs (e.g. auditLogDAL.pruneAuditLog, userNotificationDAL.pruneNotifications,
+ // keyValueStoreDAL.pruneExpiredKeys): loop deleting up to REVOCATION_PRUNE_BATCH_SIZE rows at a time
+ // via an id subquery with LIMIT, retrying transient failures a bounded number of times, with a short
+ // pause between batches to let the DB "breathe".
const removeExpiredRevocations = async () => {
- try {
- await db(TableName.IdentityAccessTokenRevocation).where("expiresAt", "<", db.fn.now()).delete();
- } catch (error) {
- throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationRemoveExpired" });
+ let deletedRevocationIds: { id: string }[] = [];
+ let numberOfRetryOnFailure = 0;
+ let isRetrying = false;
+
+ logger.info(`daily-resource-cleanup: remove expired identity access token revocations started`);
+ do {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ deletedRevocationIds = await db.transaction(async (trx) => {
+ await trx.raw(`SET statement_timeout = ${QUERY_TIMEOUT_MS}`);
+
+ const findExpiredRevocationsSubQuery = trx(TableName.IdentityAccessTokenRevocation)
+ .where("expiresAt", "<", db.fn.now())
+ .select("id")
+ .limit(REVOCATION_PRUNE_BATCH_SIZE);
+
+ // eslint-disable-next-line no-await-in-loop
+ const results = await trx(TableName.IdentityAccessTokenRevocation)
+ .whereIn("id", findExpiredRevocationsSubQuery)
+ .del()
+ .returning("id");
+
+ // `IdentityAccessTokenRevocation` isn't registered in the global knex table-type map,
+ // so `results` resolves to `any[]`; cast explicitly like `findActiveRevocationsForToken` above.
+ return results as { id: string }[];
+ });
+
+ numberOfRetryOnFailure = 0; // reset
+ } catch (error) {
+ numberOfRetryOnFailure += 1;
+ deletedRevocationIds = [];
+ logger.error(error, "Failed to delete a batch of expired identity access token revocations on pruning");
+ } finally {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10); // time to breathe for db
+ });
+ }
+ isRetrying = numberOfRetryOnFailure > 0;
+ } while (deletedRevocationIds.length > 0 || (isRetrying && numberOfRetryOnFailure < MAX_RETRY_ON_FAILURE));
+
+ if (numberOfRetryOnFailure >= MAX_RETRY_ON_FAILURE) {
+ logger.error(
+ `daily-resource-cleanup: remove expired identity access token revocations completed with persistent errors after ${MAX_RETRY_ON_FAILURE} retries. Some revocations might not have been pruned.`
+ );
+ return;
}
+
+ logger.info(`daily-resource-cleanup: remove expired identity access token revocations completed`);
};
return {