Skip to content

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

refactor(gateway-pools): drop the platform-side load count

bernie-gdbf9a84475c9
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.ts
index 597632baaf..13a1c5fd0f 100644
--- a/backend/e2e-test/mocks/keystore.ts
+++ b/backend/e2e-test/mocks/keystore.ts
@@ -138,14 +138,6 @@ export const mockKeyStore = (): TKeyStoreFactory => {
hashGet: async (key, field) => {
return hashStore[key]?.[field] ?? null;
},
- hashGetAll: async (key) => {
- return { ...(hashStore[key] ?? {}) };
- },
- hashDelete: async (key, field) => {
- if (!hashStore[key]?.[field]) return 0;
- delete hashStore[key][field];
- return 1;
- },
pgIncrementBy: async () => {
return 1;
},
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 7d4e193824..19547530ee 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -85,8 +85,7 @@ export const KeyStorePrefixes = {
// 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,
+ // concentrating them costs nothing.
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,
@@ -316,8 +315,6 @@ export type TKeyStoreFactory = {
// hash operations
hashSet: (key: string, field: string, value: string) => Promise<number>;
hashGet: (key: string, field: string) => Promise<string | null>;
- hashGetAll: (key: string) => Promise<Record<string, string>>;
- hashDelete: (key: string, field: string) => Promise<number>;
// pg
pgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;
pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;
@@ -592,10 +589,6 @@ export const keyStoreFactory = (
const hashGet = async (key: string, field: string) => primaryRedis.hget(key, field);
- const hashGetAll = async (key: string) => primaryRedis.hgetall(key);
-
- const hashDelete = async (key: string, field: string) => primaryRedis.hdel(key, field);
-
// List operations
const listPush = async (key: string, value: string) => primaryRedis.rpush(key, value);
@@ -724,8 +717,6 @@ export const keyStoreFactory = (
pgIncrementBy,
hashSet,
hashGet,
- hashGetAll,
- hashDelete,
listPush,
listRange,
listRemove,
diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.ts
index ec210192e1..725a6890a2 100644
--- a/backend/src/keystore/memory.ts
+++ b/backend/src/keystore/memory.ts
@@ -83,14 +83,6 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {
hashGet: async (key, field) => {
return hashStore[key]?.[field] ?? null;
},
- hashGetAll: async (key) => {
- return { ...(hashStore[key] ?? {}) };
- },
- hashDelete: async (key, field) => {
- if (!hashStore[key]?.[field]) return 0;
- delete hashStore[key][field];
- return 1;
- },
pgIncrementBy: async () => {
return 1;
},
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 0150ae8831..da6ef786ea 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts
@@ -1,4 +1,3 @@
-import { KeyStorePrefixes } from "@app/keystore/keystore";
import { inMemoryKeyStore } from "@app/keystore/memory";
import { initGatewayLoadTracker } from "./gateway-load-tracker";
@@ -15,11 +14,6 @@ vi.mock("@app/lib/logger", () => ({
const GW_A = "11111111-1111-1111-1111-111111111111";
const GW_B = "22222222-2222-2222-2222-222222222222";
-// The debounce means a publish lands on a later tick of the event loop.
-const flushPublishes = async () => {
- await vi.advanceTimersByTimeAsync(500);
-};
-
describe("gatewayLoadTracker", () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -32,55 +26,72 @@ describe("gatewayLoadTracker", () => {
test("scores an idle gateway at zero", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
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);
+ expect(scores.get(GW_A)?.base).toBe(0);
+ expect(scores.get(GW_B)?.base).toBe(0);
void tracker.shutdown();
});
- test("counts open channels and releases them on close", async () => {
+ test("counts open channels on top of a report and releases them on close", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+ await tracker.recordReportedLoad(GW_A, 0);
+ await tracker.recordReportedLoad(GW_B, 0);
+ await vi.advanceTimersByTimeAsync(1_000);
+
tracker.channelOpened(GW_A);
tracker.channelOpened(GW_A);
tracker.channelOpened(GW_B);
- expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)?.score).toBe(2);
- expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)?.score).toBe(1);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_A)?.base).toBe(2);
+ expect((await tracker.getScores([GW_A, GW_B])).get(GW_B)?.base).toBe(1);
tracker.channelClosed(GW_A);
tracker.channelClosed(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(0);
void tracker.shutdown();
});
- test("a reservation counts toward the score before the channel opens", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
+ // Reservations are only ever read by the claim script, so that is where they have to be observed.
+ // getScores deliberately does not fold them in, or every decision would fetch them twice.
+ test("a reservation steers the next claim away before the channel opens", async () => {
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
await tracker.reserve(GW_A);
// Without this the second concurrent selection would read zero and stampede the same gateway.
- 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);
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 0 },
+ { id: GW_B, base: 0 }
+ ])
+ ).toBe(GW_B);
- void tracker.shutdown();
+ tracker.shutdown();
});
test("hands the reservation off to the channel instead of double counting", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());
- await tracker.reserve(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+ await tracker.recordReportedLoad(GW_A, 0);
+ await vi.advanceTimersByTimeAsync(1_000);
- // The channel now carries the load the reservation stood in for, so the score must stay at 1
- // rather than counting both.
+ await tracker.reserve(GW_A);
+ // The channel now carries the load the reservation stood in for. Counting both would show A at
+ // two for one connection.
tracker.channelOpened(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(1);
+ // Equal bases with the reservation released is a tie, which the script gives to the first entry.
+ // Had the reservation survived the handoff, A would total two and B would win.
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 1 },
+ { id: GW_B, base: 1 }
+ ])
+ ).toBe(GW_A);
tracker.channelClosed(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(0);
- void tracker.shutdown();
+ tracker.shutdown();
});
test("releases a reservation whose channel never opens", async () => {
@@ -91,71 +102,24 @@ describe("gatewayLoadTracker", () => {
// eslint-disable-next-line no-await-in-loop
await tracker.reserve(GW_A);
}
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(10);
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 0 },
+ { id: GW_B, base: 5 }
+ ])
+ ).toBe(GW_B);
// Left to accumulate these would turn the score into "selections in the last N seconds", which
// is request-count round-robin rather than occupancy.
await vi.advanceTimersByTimeAsync(240_000);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
-
- void tracker.shutdown();
- });
-
- test("sums another pod's published count alongside local channels", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
-
- await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "other-pod", `5:${Date.now()}`);
- tracker.channelOpened(GW_A);
-
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);
- void tracker.shutdown();
- });
-
- test("ignores a dead pod's stale count instead of counting it forever", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
-
- 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);
- void tracker.shutdown();
- });
-
- test("ignores a malformed published entry rather than scoring NaN", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
-
- await keyStore.hashSet(KeyStorePrefixes.GatewayLoad(GW_A), "bad-pod", "not-a-count");
-
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(0);
- void tracker.shutdown();
- });
-
- test("drops its own field once it holds nothing, so the hash does not grow per restart", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
-
- tracker.channelOpened(GW_A);
- await flushPublishes();
- expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(1);
-
- tracker.channelClosed(GW_A);
- await flushPublishes();
- expect(Object.keys(await keyStore.hashGetAll(KeyStorePrefixes.GatewayLoad(GW_A)))).toHaveLength(0);
-
- void tracker.shutdown();
- });
-
- test("does not double count its own published field against its live count", async () => {
- const keyStore = inMemoryKeyStore();
- const tracker = initGatewayLoadTracker(keyStore);
-
- tracker.channelOpened(GW_A);
- await flushPublishes();
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 0 },
+ { id: GW_B, base: 5 }
+ ])
+ ).toBe(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
- void tracker.shutdown();
+ tracker.shutdown();
});
test("prefers the gateway's own count over the platform's partial view", async () => {
@@ -166,7 +130,7 @@ describe("gatewayLoadTracker", () => {
tracker.channelOpened(GW_A);
await tracker.recordReportedLoad(GW_A, 50);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(50);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(50);
void tracker.shutdown();
});
@@ -182,7 +146,7 @@ describe("gatewayLoadTracker", () => {
tracker.channelOpened(GW_A);
tracker.channelOpened(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(6);
void tracker.shutdown();
});
@@ -197,7 +161,7 @@ describe("gatewayLoadTracker", () => {
await vi.advanceTimersByTimeAsync(1_000);
await tracker.recordReportedLoad(GW_A, 3);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(3);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(3);
void tracker.shutdown();
});
@@ -205,39 +169,49 @@ describe("gatewayLoadTracker", () => {
test("still adds reservations on top of a reported count", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
- // A reservation covers a channel the gateway has not seen yet, so it is additive.
+ // A reservation covers a channel the gateway has not seen yet, so it is additive to the report.
await tracker.recordReportedLoad(GW_A, 4);
await tracker.reserve(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(5);
+ const base = (await tracker.getScores([GW_A])).get(GW_A)?.base;
+ expect(base).toBe(4);
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 4 },
+ { id: GW_B, base: 4 }
+ ])
+ ).toBe(GW_B);
- void tracker.shutdown();
+ tracker.shutdown();
});
- test("falls back to the platform's view for a gateway too old to report, and flags the scale", async () => {
+ test("flags a gateway too old to report instead of inventing a count for it", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
+ // Selection refuses to compare a pool containing this member, so scoring it from the channels
+ // we happened to open would only be a number that looks like an occupancy without being one.
tracker.channelOpened(GW_A);
tracker.channelOpened(GW_A);
await tracker.recordReportedLoad(GW_B, 7);
const scores = await tracker.getScores([GW_A, GW_B]);
- expect(scores.get(GW_A)).toEqual({ base: 2, score: 2, reported: false });
- expect(scores.get(GW_B)).toEqual({ base: 7, score: 7, reported: true });
+ expect(scores.get(GW_A)).toEqual({ base: 0, reported: false });
+ expect(scores.get(GW_B)).toEqual({ base: 7, reported: true });
void tracker.shutdown();
});
- test("falls back when a gateway stops reporting", async () => {
+ test("stops trusting a gateway that goes quiet", async () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
await tracker.recordReportedLoad(GW_A, 40);
tracker.channelOpened(GW_A);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(40);
+ expect((await tracker.getScores([GW_A])).get(GW_A)?.base).toBe(40);
- // Past the freshness window the stale 40 must not pin the member out of rotation forever.
+ // Past the freshness window the stale 40 must not pin the member out of rotation forever. It
+ // drops to unreported, which takes the whole pool off load-aware selection.
await vi.advanceTimersByTimeAsync(40_000);
- expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(1);
+ expect((await tracker.getScores([GW_A])).get(GW_A)).toEqual({ base: 0, reported: false });
void tracker.shutdown();
});
@@ -252,9 +226,14 @@ describe("gatewayLoadTracker", () => {
expect(claimed).toBe(GW_B);
// Claiming and reserving must be one operation, otherwise concurrent selections all read the
- // same minimum before any of them writes and every one of them routes to it. The base passed in
- // 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);
+ // same minimum before any of them writes and every one of them routes to it. Repeating the call
+ // with the same bases has to move, which only happens if the first claim also wrote.
+ expect(
+ await tracker.claimLeastLoaded([
+ { id: GW_A, base: 1 },
+ { id: GW_B, base: 1 }
+ ])
+ ).toBe(GW_A);
void tracker.shutdown();
});
@@ -305,20 +284,6 @@ describe("gatewayLoadTracker", () => {
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 () => {
const tracker = initGatewayLoadTracker(inMemoryKeyStore());
diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
index 3c5c083df1..0cd62bf4c4 100644
--- a/backend/src/lib/gateway-v2/gateway-load-tracker.ts
+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts
@@ -1,5 +1,3 @@
-import crypto from "node:crypto";
-
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { logger } from "../logger";
@@ -14,21 +12,14 @@ const RESERVATION_TTL_SECONDS = 240;
// gateway handshake 120s, so releasing sooner would reopen the window the reservation covers.
const RESERVATION_HOLD_MS = 230_000;
const SUSPECT_TTL_SECONDS = 60;
-const LOAD_HASH_TTL_SECONDS = 600;
-
-// Another pod's published count is ignored past this age, so a pod that dies stops skewing selection
-// instead of leaving its channels counted forever.
-const PUBLISHED_COUNT_MAX_AGE_MS = 90_000;
-const PUBLISH_DEBOUNCE_MS = 250;
-const PUBLISH_REFRESH_MS = 20_000;
-
-const podId = crypto.randomUUID();
export type TGatewayScore = {
- score: number;
- /** Occupancy excluding reservations, which the atomic claim reads for itself. */
+ /**
+ * Occupancy without reservations. The claim script reads the reservation keys itself, so adding
+ * them here as well would mean fetching them twice for the same decision.
+ */
base: number;
- /** False when this member is too old to report its own count, so its score is on a different scale. */
+ /** False when this member is too old to report its own count, which disables load-aware selection. */
reported: boolean;
};
@@ -41,7 +32,7 @@ type TGatewayLoadTracker = {
markSuspect: (gatewayId: string) => Promise<void>;
getScores: (gatewayIds: string[]) => Promise<Map<string, TGatewayScore>>;
getSuspect: (gatewayIds: string[]) => Promise<Set<string>>;
- shutdown: () => Promise<void>;
+ shutdown: () => void;
};
let tracker: TGatewayLoadTracker | undefined;
@@ -49,7 +40,6 @@ let tracker: TGatewayLoadTracker | undefined;
const REPORTED_LOAD_TTL_SECONDS = 60;
const REPORTED_LOAD_MAX_AGE_MS = 35_000;
-const loadKey = KeyStorePrefixes.GatewayLoad;
const reportedKey = KeyStorePrefixes.GatewayReportedLoad;
const reservationKey = KeyStorePrefixes.GatewayLoadReservation;
const suspectKey = KeyStorePrefixes.GatewaySuspect;
@@ -58,14 +48,8 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
// Open timestamps rather than a bare count, so a channel opened since a gateway's last report can
// be added on top of that report instead of being invisible until the next one lands.
const openChannels = new Map<string, number[]>();
- const pendingPublish = new Set<string>();
const reservationTimers = new Set<NodeJS.Timeout>();
const pendingReservations = new Map<string, NodeJS.Timeout[]>();
- let debounceTimer: NodeJS.Timeout | undefined;
-
- const publishChain = new Map<string, Promise<void>>();
-
- const channelCount = (gatewayId: string) => openChannels.get(gatewayId)?.length ?? 0;
const releaseReservation = async (gatewayId: string) => {
try {
@@ -92,55 +76,6 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
else pendingReservations.set(gatewayId, [timer]);
}
- const publishNow = async (gatewayId: string) => {
- const count = channelCount(gatewayId);
- try {
- // Holding nothing means dropping the field rather than writing a zero, so the hash only ever
- // carries pods with live channels instead of accumulating one entry per restart.
- if (count === 0) {
- await keyStore.hashDelete(loadKey(gatewayId), podId);
- return;
- }
- await keyStore.hashSet(loadKey(gatewayId), podId, `${count}:${Date.now()}`);
- await keyStore.setExpiry(loadKey(gatewayId), LOAD_HASH_TTL_SECONDS);
- } catch (err) {
- logger.debug({ err, gatewayId }, `Failed to publish gateway load [gatewayId=${gatewayId}]`);
- }
- };
-
- // Overlapping flushes must not interleave, or a hashSet for count 1 can land after the hashDelete
- // for count 0 and leave this pod's field claiming load it does not hold.
- const publish = (gatewayId: string) => {
- const prev = publishChain.get(gatewayId) ?? Promise.resolve();
- const next = prev.then(() => publishNow(gatewayId));
- publishChain.set(gatewayId, next);
- return next;
- };
-
- const flushPending = () => {
- const ids = [...pendingPublish];
- pendingPublish.clear();
- debounceTimer = undefined;
- void Promise.all(ids.map((id) => publish(id)));
- };
-
- const schedulePublish = (gatewayId: string) => {
- pendingPublish.add(gatewayId);
- if (!debounceTimer) {
- debounceTimer = setTimeout(flushPending, PUBLISH_DEBOUNCE_MS);
- debounceTimer.unref();
- }
- };
-
- // Long-lived channels change the count once and then sit for hours, so the timestamp has to be
- // refreshed independently or other pods would age the entry out while it is still accurate.
- const refreshTimer = setInterval(() => {
- for (const gatewayId of openChannels.keys()) {
- schedulePublish(gatewayId);
- }
- }, PUBLISH_REFRESH_MS);
- refreshTimer.unref();
-
const recordReportedLoad = async (gatewayId: string, activeChannels: number) => {
await keyStore.setItemWithExpiry(
reportedKey(gatewayId),
@@ -162,7 +97,6 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
reservationTimers.delete(timer);
void releaseReservation(gatewayId);
}
- schedulePublish(gatewayId);
};
const channelClosed = (gatewayId: string) => {
@@ -170,7 +104,6 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
// Drops the oldest: only the count and the open times matter, not which socket this was.
open?.shift();
if (!open?.length) openChannels.delete(gatewayId);
- schedulePublish(gatewayId);
};
const reserve = async (gatewayId: string) => {
@@ -220,58 +153,35 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
const scores = new Map<string, TGatewayScore>();
if (gatewayIds.length === 0) return scores;
- const [published, reservations, reported] = await Promise.all([
- Promise.all(gatewayIds.map((id) => keyStore.hashGetAll(loadKey(id)))),
- keyStore.getItemsPrimary(gatewayIds.map((id) => reservationKey(id))),
- keyStore.getItemsPrimary(gatewayIds.map((id) => reportedKey(id)))
- ]);
+ const reported = await keyStore.getItemsPrimary(gatewayIds.map((id) => reportedKey(id)));
- const now = Date.now();
- const publishedCutoff = now - PUBLISHED_COUNT_MAX_AGE_MS;
- const reportedCutoff = now - REPORTED_LOAD_MAX_AGE_MS;
+ const reportedCutoff = Date.now() - REPORTED_LOAD_MAX_AGE_MS;
- const parseStamped = (raw: string | null, cutoff: number) => {
+ const parseStamped = (raw: string | null) => {
if (!raw) return undefined;
const [countStr, tsStr] = raw.split(":");
const count = Number(countStr);
const at = Number(tsStr);
- if (!Number.isFinite(count) || !Number.isFinite(at) || at < cutoff) return undefined;
- return count;
+ if (!Number.isFinite(count) || !Number.isFinite(at) || at < reportedCutoff) return undefined;
+ return { count, at };
};
gatewayIds.forEach((gatewayId, idx) => {
- // Never sum the two views: the gateway's own count already includes the channels this pod
- // opened, so adding the per-pod counters would double count platform traffic.
- const rawReported = reported[idx];
- const reportedOccupancy = parseStamped(rawReported, reportedCutoff);
- let occupancy = reportedOccupancy;
+ const report = parseStamped(reported[idx]);
- if (occupancy !== undefined) {
+ // A gateway that cannot report is left at zero on purpose. Selection refuses to compare a pool
+ // containing one, so the number is never used, and inventing a platform-side count here would
+ // only look like a real occupancy to whoever reads it next.
+ let occupancy = 0;
+ if (report) {
// The report is a snapshot up to its own timestamp. Anything this pod opened since then is
// not in it yet, and without this every selection inside one report interval reads the same
// stale number and piles onto the same member.
- const reportedAt = Number((rawReported ?? "").split(":")[1]);
- const openedSinceReport = Number.isFinite(reportedAt)
- ? (openChannels.get(gatewayId) ?? []).filter((openedAt) => openedAt > reportedAt).length
- : 0;
- occupancy += openedSinceReport;
- } else {
- const fields = Object.entries(published[idx] ?? {})
- // This pod's in-memory count is always fresher than what it last published.
- .filter(([fieldPodId]) => fieldPodId !== podId);
-
- occupancy = 0;
- for (const [, raw] of fields) {
- occupancy += parseStamped(raw, publishedCutoff) ?? 0;
- }
- occupancy += channelCount(gatewayId);
+ const openedSinceReport = (openChannels.get(gatewayId) ?? []).filter((openedAt) => openedAt > report.at).length;
+ occupancy = report.count + openedSinceReport;
}
- scores.set(gatewayId, {
- base: occupancy,
- score: occupancy + (Number(reservations[idx] ?? 0) || 0),
- reported: reportedOccupancy !== undefined
- });
+ scores.set(gatewayId, { base: occupancy, reported: report !== undefined });
});
return scores;
@@ -287,28 +197,14 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad
return suspect;
};
- const shutdown = async () => {
+ // Nothing here writes to Redis. Reservations this pod still holds are left to their TTL, which is
+ // the backstop that exists precisely for a pod that goes away without releasing them.
+ const shutdown = () => {
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 5ab5c843ff..752b61138c 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -4266,7 +4266,7 @@ 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();
+ gatewayLoadTracker.shutdown();
cronJobs.forEach((job) => job.stop());
await cronJob.stop();
await telemetryService.flushAll();