Skip to content

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

improvements: address concurrency feedback

Scott Wilson23996e84bb02
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index ea7ceb3bfa..a300d79095 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -64,6 +64,12 @@ export const mockKeyStore = (): TKeyStoreFactory => {
incrementBy: async () => {
return 1;
},
+ incrementByAndRefreshExpiryIfUnderLimit: async () => {
+ return 1;
+ },
+ decrementByOrDelete: async () => {
+ return 0;
+ },
pgGetIntItem: async (key) => {
const value = store[key];
if (typeof value === "number") {
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 72931c5ec5..6c2651e81f 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -202,6 +202,8 @@ export type TKeyStoreFactory = {
deleteItemsByKeyIn: (keys: string[]) => Promise<number>;
deleteItems: (arg: TDeleteItems) => Promise<number>;
incrementBy: (key: string, value: number) => Promise<number>;
+ incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;
+ decrementByOrDelete: (key: string) => Promise<number>;
getKeysByPattern: (pattern: string, limit?: number) => Promise<string[]>;
// list operations
listPush: (key: string, value: string) => Promise<number>;
@@ -326,6 +328,52 @@ export const keyStoreFactory = (
const incrementBy = async (key: string, value: number) => primaryRedis.incrby(key, value);
+ // Atomic admit: INCR by 1; if the post-INCR count is over the cap, DECR back and
+ // signal rejection without touching EXPIRE — so failed probes against an orphaned
+ // counter cannot keep refreshing its TTL. Otherwise refresh the TTL alongside the
+ // successful admit. Returns -1 for rejection, otherwise the post-INCR count.
+ const INCREMENT_AND_REFRESH_EXPIRY_IF_UNDER_LIMIT_SCRIPT = `
+ local count = redis.call("INCR", KEYS[1])
+ if count > tonumber(ARGV[1]) then
+ redis.call("DECR", KEYS[1])
+ return -1
+ end
+ redis.call("EXPIRE", KEYS[1], ARGV[2])
+ return count
+ `;
+
+ // Atomic release: DECR but never below 0, and never leave a no-TTL key behind. If
+ // the counter is missing or already ≤ 1, DEL so the next admit creates a fresh
+ // key with a fresh TTL. Does NOT touch EXPIRE — the slot is being released.
+ const DECREMENT_OR_DELETE_SCRIPT = `
+ local current = redis.call("GET", KEYS[1])
+ if not current or tonumber(current) <= 1 then
+ redis.call("DEL", KEYS[1])
+ return 0
+ end
+ return redis.call("DECR", KEYS[1])
+ `;
+
+ const incrementByAndRefreshExpiryIfUnderLimit = async (
+ key: string,
+ limit: number,
+ expiryInSeconds: number
+ ): Promise<number> => {
+ const result = await primaryRedis.eval(
+ INCREMENT_AND_REFRESH_EXPIRY_IF_UNDER_LIMIT_SCRIPT,
+ 1,
+ key,
+ limit,
+ expiryInSeconds
+ );
+ return Number(result);
+ };
+
+ const decrementByOrDelete = async (key: string): Promise<number> => {
+ const result = await primaryRedis.eval(DECREMENT_OR_DELETE_SCRIPT, 1, key);
+ return Number(result);
+ };
+
const setExpiry = async (key: string, expiryInSeconds: number) => primaryRedis.expire(key, expiryInSeconds);
const ttl = async (key: string) => primaryRedis.ttl(key);
@@ -455,6 +503,8 @@ export const keyStoreFactory = (
deleteItem,
deleteItems,
incrementBy,
+ incrementByAndRefreshExpiryIfUnderLimit,
+ decrementByOrDelete,
acquireLock(resources: string[], duration: number, settings?: Partial<Settings>) {
return redisLock.acquire(resources, duration, settings);
},
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index 5b4458f613..3dd7881182 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -82,6 +82,12 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
incrementBy: async () => {
return 1;
},
+ incrementByAndRefreshExpiryIfUnderLimit: async () => {
+ return 1;
+ },
+ decrementByOrDelete: async () => {
+ return 0;
+ },
acquireLock: () => {
return Promise.resolve({
release: () => {}
diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.ts
index acafa11e78..362b0bfc64 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.ts
@@ -86,7 +86,7 @@ type TSecretSyncQueueFactoryDep = {
cronJob: TCronJobFactory;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementBy" | "setExpiry">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
folderDAL: TSecretFolderDALFactory;
secretV2BridgeDAL: Pick<
TSecretV2BridgeDALFactory,
@@ -137,7 +137,7 @@ const JITTER_MS = 10 * 1000;
const REQUEUE_MS = 30 * 1000;
const REQUEUE_LIMIT = 120;
const CONNECTION_CONCURRENCY_LIMIT = 5;
-const CONNECTION_CONCURRENCY_TTL_SECONDS = (REQUEUE_MS * REQUEUE_LIMIT) / 1000;
+const CONNECTION_CONCURRENCY_TTL_SECONDS = (REQUEUE_MS * REQUEUE_LIMIT) / 1000 / 2;
const getRequeueDelay = (failureCount?: number) => {
const jitter = Math.random() * JITTER_MS;
@@ -228,44 +228,25 @@ export const secretSyncQueueFactory = ({
folderCommitService
});
- // Admission via INCRBY: the INCR itself is atomic, so concurrent admits cannot exceed
- // CONNECTION_CONCURRENCY_LIMIT. setExpiry always runs (success and over-limit paths) so
- // the key never persists TTL-less, and any post-INCR failure fires a compensating DECR.
+ // INCR + cap check + EXPIRE happen atomically inside a Lua script. TTL is refreshed
+ // only when a slot is actually claimed; failed probes (over-limit) and releases
+ // never touch EXPIRE — so an orphaned counter from a worker that died mid-sync
+ // can't have its expiry indefinitely shoved forward by subsequent admit attempts,
+ // and ages out within CONNECTION_CONCURRENCY_TTL_SECONDS of the last successful
+ // admit.
const $tryAdmitConnectionConcurrency = async (connectionId: string) => {
const key = KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId);
- const count = await keyStore.incrementBy(key, 1);
-
- if (count <= 0) {
- logger.warn(
- `SecretSync connection concurrency counter drifted non-positive after admit [connectionId=${connectionId}] [count=${count}]`
- );
- }
-
- try {
- // INCR on a missing key creates it without a TTL; EXPIRE is what arms it. Calling
- // this on every path prevents an unarmed key from permanently locking the connection
- // if a future admit returns over-limit and skips setExpiry.
- await keyStore.setExpiry(key, CONNECTION_CONCURRENCY_TTL_SECONDS);
-
- if (count > CONNECTION_CONCURRENCY_LIMIT) {
- await keyStore.incrementBy(key, -1);
- return false;
- }
-
- return true;
- } catch (err) {
- await keyStore.incrementBy(key, -1).catch(() => {});
- throw err;
- }
+ const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
+ key,
+ CONNECTION_CONCURRENCY_LIMIT,
+ CONNECTION_CONCURRENCY_TTL_SECONDS
+ );
+ return count !== -1;
};
const $releaseConnectionConcurrency = async (connectionId: string) => {
const key = KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId);
- await keyStore.incrementBy(key, -1);
- // EXPIRE on a missing key is a no-op; on an existing one it refreshes the TTL. The
- // counter can briefly go negative if the key TTL expired while a job was running, but
- // it self-corrects as orphan releases land and future admits' INCRs climb back up.
- await keyStore.setExpiry(key, CONNECTION_CONCURRENCY_TTL_SECONDS);
+ await keyStore.decrementByOrDelete(key);
};
const $getInfisicalSecrets = async (
@@ -1230,7 +1211,7 @@ export const secretSyncQueueFactory = ({
await lock.release();
}
},
- { concurrency: 5 }
+ { concurrency: 15 }
);
const startDailySecretSyncRetryJob = () => {