Skip to content

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

fix(gateway-pools): cluster-safe claims and clean shutdown

bernie-g25958a667cc8
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index d49d59dbe0..597632baaf 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -79,6 +79,9 @@ export const mockKeyStore = (): TKeyStoreFactory => {
},
claimLeastLoaded: async (keys, baseOccupancies) => {
if (keys.length === 0) return 0;
+ if (keys.length !== baseOccupancies.length) {
+ throw new Error("claimLeastLoaded: baseOccupancies must have one entry per key");
+ }
let bestIdx = 0;
let bestTotal: number | null = null;
keys.forEach((key, i) => {
diff --git a/backend/src/keystore/keystore.test.ts b/backend/src/keystore/keystore.test.ts
new file mode 100644
index 0000000000..ea359c00a0
--- /dev/null
+++ b/backend/src/keystore/keystore.test.ts
@@ -0,0 +1,24 @@
+import { inMemoryKeyStore } from "./memory";
+
+describe("claimLeastLoaded", () => {
+ test("rejects a mismatched base-occupancy list rather than reading the ttl as a count", async () => {
+ const keyStore = inMemoryKeyStore();
+ await expect(keyStore.claimLeastLoaded(["a", "b"], [0], 60)).rejects.toThrow(
+ "baseOccupancies must have one entry per key"
+ );
+ });
+
+ test("claims the lowest total and counts existing reservations", async () => {
+ const keyStore = inMemoryKeyStore();
+ expect(await keyStore.claimLeastLoaded(["a", "b"], [5, 1], 60)).toBe(2);
+ expect(await keyStore.claimLeastLoaded(["a", "b"], [5, 1], 60)).toBe(2);
+ expect(await keyStore.claimLeastLoaded(["a", "b"], [5, 1], 60)).toBe(2);
+ expect(await keyStore.claimLeastLoaded(["a", "b"], [5, 1], 60)).toBe(2);
+ // b has now taken 4, so 1 + 4 ties a's 5 and the strict comparison leaves a first
+ expect(await keyStore.claimLeastLoaded(["a", "b"], [5, 1], 60)).toBe(1);
+ });
+
+ test("returns 0 for no candidates", async () => {
+ expect(await inMemoryKeyStore().claimLeastLoaded([], [], 60)).toBe(0);
+ });
+});
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 6adfd71881..7d4e193824 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -82,10 +82,14 @@ export const KeyStorePrefixes = {
ProxiedServiceUsageDebounce: (serviceId: string) => `proxied-service-usage-debounce:${serviceId}` as const,
ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`,
GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}`,
+ // The braces are a Redis Cluster hash tag: only the tagged part picks the slot, so these land on
+ // one node. Selection reads them for several gateways at once (one Lua script and two MGETs), and
+ // cluster refuses a multi-key command whose keys span slots. They are small counters, so
+ // concentrating them costs nothing. GatewayLoad is read one key at a time and needs no tag.
GatewayLoad: (gatewayId: string) => `gateway-load:${gatewayId}` as const,
- GatewayReportedLoad: (gatewayId: string) => `gateway-reported-load:${gatewayId}` as const,
- GatewayLoadReservation: (gatewayId: string) => `gateway-reservation:${gatewayId}` as const,
- GatewaySuspect: (gatewayId: string) => `gateway-suspect:${gatewayId}` as const,
+ GatewayReportedLoad: (gatewayId: string) => `gateway-reported-load:{gw-pool}:${gatewayId}` as const,
+ GatewayLoadReservation: (gatewayId: string) => `gateway-reservation:{gw-pool}:${gatewayId}` as const,
+ GatewaySuspect: (gatewayId: string) => `gateway-suspect:{gw-pool}:${gatewayId}` as const,
ActiveSSEConnectionsSet: (projectId: string, identityId: string) =>
`sse-connections:${projectId}:${identityId}` as const,
ActiveSSEConnections: (projectId: string, identityId: string, connectionId: string) =>
@@ -490,8 +494,11 @@ export const keyStoreFactory = (
end
end
if bestIdx == 0 then return 0 end
- redis.call("INCR", KEYS[bestIdx])
- redis.call("EXPIRE", KEYS[bestIdx], ttl)
+ -- Set the expiry only on the first increment. Refreshing it on every claim means a busy key
+ -- never elapses, so a crashed pod's leaked reservations would stay counted indefinitely.
+ if redis.call("INCR", KEYS[bestIdx]) == 1 then
+ redis.call("EXPIRE", KEYS[bestIdx], ttl)
+ end
return bestIdx
`;
@@ -502,6 +509,9 @@ export const keyStoreFactory = (
expiryInSeconds: number
): Promise<number> => {
if (keys.length === 0) return 0;
+ if (keys.length !== baseOccupancies.length) {
+ throw new Error("claimLeastLoaded: baseOccupancies must have one entry per key");
+ }
const result = await primaryRedis.eval(
CLAIM_LEAST_LOADED_SCRIPT,
keys.length,
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index 73a70c2e5d..ec210192e1 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -105,6 +105,9 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
},
claimLeastLoaded: async (keys, baseOccupancies) => {
if (keys.length === 0) return 0;
+ if (keys.length !== baseOccupancies.length) {
+ throw new Error("claimLeastLoaded: baseOccupancies must have one entry per key");
+ }
let bestIdx = 0;
let bestTotal: number | null = null;
keys.forEach((key, i) => {
diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
index 526be9dc2c..0150ae8831 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
@@ -34,7 +34,7 @@ describe("gatewayLoadTracker", () => {
const scores = await tracker.getScores([GW_A, GW_B]);
expect(scores.get(GW_A)?.score).toBe(0);
expect(scores.get(GW_B)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("counts open channels and releases them on close", async () => {
@@ -50,7 +50,7 @@ describe("gatewayLoadTracker", () => {
tracker.channelClosed(GW_A);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("a reservation counts toward the score before the channel opens", async () => {
@@ -62,7 +62,7 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)?.score).toBe(1);
expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("hands the reservation off to the channel instead of double counting", async () => {
@@ -80,7 +80,7 @@ describe("gatewayLoadTracker", () => {
tracker.channelClosed(GW_A);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("releases a reservation whose channel never opens", async () => {
@@ -98,7 +98,7 @@ describe("gatewayLoadTracker", () => {
await vi.advanceTimersByTimeAsync(240_000);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("sums another pod's published count alongside local channels", async () => {
@@ -109,7 +109,7 @@ describe("gatewayLoadTracker", () => {
tracker.channelOpened(GW_A);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("ignores a dead pod's stale count instead of counting it forever", async () => {
@@ -119,7 +119,7 @@ describe("gatewayLoadTracker", () => {
await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "dead-pod", `9:${Date.now() - 120_000}`);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("ignores a malformed published entry rather than scoring NaN", async () => {
@@ -129,7 +129,7 @@ describe("gatewayLoadTracker", () => {
await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "bad-pod", "not-a-count");
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("drops its own field once it holds nothing, so the hash does not grow per restart", async () => {
@@ -144,7 +144,7 @@ describe("gatewayLoadTracker", () => {
await flushPublishes();
expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("does not double count its own published field against its live count", async () => {
@@ -155,7 +155,7 @@ describe("gatewayLoadTracker", () => {
await flushPublishes();
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("prefers the gateway's own count over the platform's partial view", async () => {
@@ -168,7 +168,7 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(50);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("adds channels opened since the gateway's last report", async () => {
@@ -184,7 +184,7 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("does not sum its own view into the gateway's count", async () => {
@@ -199,7 +199,7 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(3);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("still adds reservations on top of a reported count", async () => {
@@ -211,7 +211,7 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(5);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("falls back to the platform's view for a gateway too old to report, and flags the scale", async () => {
@@ -225,7 +225,7 @@ describe("gatewayLoadTracker", () => {
expect(scores.get(GW_A)).toEqual({ base: 2, score: 2, reported: false });
expect(scores.get(GW_B)).toEqual({ base: 7, score: 7, reported: true });
- tracker.shutdown();
+ void tracker.shutdown();
});
test("falls back when a gateway stops reporting", async () => {
@@ -239,7 +239,7 @@ describe("gatewayLoadTracker", () => {
await vi.advanceTimersByTimeAsync(40_000);
expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("claims the least loaded member and reserves it in the same call", async () => {
@@ -256,7 +256,7 @@ describe("gatewayLoadTracker", () => {
// is the caller's view; the score here is this gateway's real occupancy plus that reservation.
expect((await tracker.getScores([GW_B])).get(GW_B)?.score).toBe(1);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("concurrent claims stop piling on once the minimum catches up", async () => {
@@ -277,7 +277,7 @@ describe("gatewayLoadTracker", () => {
expect(claims.filter((c) => c === GW_A)).toHaveLength(3);
expect(claims.filter((c) => c === GW_B)).toHaveLength(1);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("resolves a tie by the order it is given, so callers control the tie-break", async () => {
@@ -296,13 +296,27 @@ describe("gatewayLoadTracker", () => {
])
).toBe(GW_B);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("claims nothing when given no candidates", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
expect(await tracker.claimLeastLoaded([])).toBeUndefined();
- tracker.shutdown();
+ void tracker.shutdown();
+ });
+
+ test("clears its published counts on shutdown", async () => {
+ const keyStore = inMemoryKeyStore();
+ const tracker = initGatewayLoadTracker(keyStore);
+
+ tracker.channelOpened(GW_A);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(1);
+
+ // A rolling deploy would otherwise leave this pod's dead channels counting for the whole
+ // freshness window.
+ await tracker.shutdown();
+ expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(0);
});
test("marks and reports suspect gateways", async () => {
@@ -313,7 +327,7 @@ describe("gatewayLoadTracker", () => {
expect(suspect.has(GW_A)).toBe(true);
expect(suspect.has(GW_B)).toBe(false);
- tracker.shutdown();
+ void tracker.shutdown();
});
test("returns empty results for an empty gateway list without touching the store", async () => {
@@ -321,6 +335,6 @@ describe("gatewayLoadTracker", () => {
expect((await tracker.getScores([])).size).toBe(0);
expect((await tracker.getSuspect([])).size).toBe(0);
- tracker.shutdown();
+ void tracker.shutdown();
});
});
diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
index e9474acae8..3c5c083df1 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
@@ -41,7 +41,7 @@ type TGatewayLoadTracker = {
markSuspect: (gatewayId: string) => Promise<void>;
getScores: (gatewayIds: string[]) => Promise<Map<string, TGatewayScore>>;
getSuspect: (gatewayIds: string[]) => Promise<Set<string>>;
- shutdown: () => void;
+ shutdown: () => Promise<void>;
};
let tracker: TGatewayLoadTracker | undefined;
@@ -175,7 +175,10 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
const reserve = async (gatewayId: string) => {
try {
- await keyStore.incrementByWithExpiry(reservationKey(gatewayId), 1, RESERVATION_TTL_SECONDS);
+ // Routed through the same claim path as a pool selection so the expiry is set only on the
+ // first increment. incrementByWithExpiry refreshes it on every call, which on a busy gateway
+ // means the key never elapses and a crashed pod's reservations stay counted forever.
+ await keyStore.claimLeastLoaded([reservationKey(gatewayId)], [0], RESERVATION_TTL_SECONDS);
} catch (err) {
logger.debug({ err, gatewayId }, `Failed to reserve gateway capacity [gatewayId=${gatewayId}]`);
return;
@@ -284,12 +287,28 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
return suspect;
};
- const shutdown = () => {
+ const shutdown = async () => {
+ tracker = undefined;
clearInterval(refreshTimer);
if (debounceTimer) clearTimeout(debounceTimer);
for (const timer of reservationTimers) clearTimeout(timer);
pendingReservations.clear();
reservationTimers.clear();
+ publishChain.clear();
+
+ // Without this the published fields linger for the freshness window, so a rolling deploy leaves
+ // this pod's already-dead channels counting against those gateways.
+ const held = [...openChannels.keys()];
+ openChannels.clear();
+ await Promise.all(
+ held.map(async (gatewayId) => {
+ try {
+ await keyStore.hashDelete(loadKey(gatewayId), podId);
+ } catch (err) {
+ logger.debug({ err, gatewayId }, `Failed to clear published load on shutdown [gatewayId=${gatewayId}]`);
+ }
+ })
+ );
};
tracker = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7a5768a5ab..f5cd14a14d 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -580,7 +580,7 @@ export const registerRoutes = async (
// Reached from the gateway proxy layer in src/lib, which has no DI, so it is installed as a module
// singleton rather than threaded through every call site.
- initGatewayLoadTracker(keyStore);
+ const gatewayLoadTracker = initGatewayLoadTracker(keyStore);
await server.register(registerSecretScanningV2Webhooks, {
prefix: "/secret-scanning/webhooks"
@@ -4263,6 +4263,9 @@ export const registerRoutes = async (
}
server.addHook("onClose", async () => {
+ // Drops this pod's published counts, so a rolling deploy does not leave its already-dead
+ // channels counting against those gateways for the freshness window.
+ await gatewayLoadTracker.shutdown();
cronJobs.forEach((job) => job.stop());
await cronJob.stop();
await telemetryService.flushAll();