Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(gateway-pools): claim atomically, and close review gaps
bernie-ge2f4b2fcd9c1
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 83b8489aeb..d49d59dbe0 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -77,6 +77,23 @@ export const mockKeyStore = (): TKeyStoreFactory => {incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;},+ claimLeastLoaded: async (keys, baseOccupancies) => {+ if (keys.length === 0) return 0;+ let bestIdx = 0;+ let bestTotal: number | null = null;+ keys.forEach((key, i) => {+ const reserved = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ const total = baseOccupancies[i] + reserved;+ if (bestTotal === null || total < bestTotal) {+ bestTotal = total;+ bestIdx = i + 1;+ }+ });+ const chosen = keys[bestIdx - 1];+ const current = typeof store[chosen] === "string" ? parseInt(store[chosen] as string, 10) : 0;+ store[chosen] = String(current + 1);+ return bestIdx;+ },decrementByOrDelete: async (key) => {const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;const next = current - 1;diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex 6e4014bc26..bf2a582d7b 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -1,8 +1,9 @@import z from "zod";import { GatewaysV2Schema } from "@app/db/schemas";+import { GATEWAYS } from "@app/lib/api-docs";import { zodBuffer } from "@app/lib/zod";-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { gatewayLoadReportLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema } from "@app/server/lib/schemas";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";@@ -61,34 +62,34 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {}});- // Deliberately separate from /heartbeat: that one probes back through the relay and writes to the- // database, which is far too costly to run at the cadence pool selection needs. This only touches- // the load tracker's Redis keys.+ // Separate from /heartbeat because of what its handler costs, not how it is called: a heartbeat+ // makes the platform dial back through the relay to probe liveness and then writes to Postgres,+ // which is far too expensive at the cadence pool selection needs. This one only writes a Redis key,+ // and deliberately does not touch heartbeat, so a gateway cannot look alive by reporting load.server.route({method: "POST",url: "/load",config: {- rateLimit: writeLimit+ rateLimit: gatewayLoadReportLimit},schema: {operationId: "gatewayLoadReport",body: z.object({- activeChannels: z.number().int().min(0).max(1_000_000)+ activeChannels: z.number().int().min(0).max(1_000_000).describe(GATEWAYS.LOAD_REPORT.activeChannels)}),response: {200: z.object({- message: z.string()+ gatewayId: z.string().uuid().describe(GATEWAYS.LOAD_REPORT.gatewayId),+ activeChannels: z.number().int().describe(GATEWAYS.LOAD_REPORT.activeChannels)})}},onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {- await server.services.gatewayV2.reportLoad({+ return server.services.gatewayV2.reportLoad({orgPermission: req.permission,activeChannels: req.body.activeChannels});-- return { message: "Successfully reported gateway load" };}});diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts b/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.tsindex d757814285..8c77af798f 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-failover.test.ts@@ -6,13 +6,14 @@ const markSuspect = vi.fn();const getSuspect = vi.fn().mockResolvedValue(new Set<string>());const getScores = vi.fn();const reserve = vi.fn();+const claimLeastLoaded = vi.fn();vi.mock("@app/lib/logger", () => ({logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }}));vi.mock("@app/lib/gateway-v2/gateway-load-tracker", () => ({- getGatewayLoadTracker: () => ({ markSuspect, getSuspect, getScores, reserve })+ getGatewayLoadTracker: () => ({ markSuspect, getSuspect, getScores, reserve, claimLeastLoaded })}));// eslint-disable-next-line import/first@@ -40,8 +41,10 @@ describe("selectGatewayFromPool under load-tracker failure", () => {// clearAllMocks keeps implementations, so a rejection set by one test would leak into the next.markSuspect.mockResolvedValue(undefined);reserve.mockResolvedValue(undefined);+ // Without this the load-aware branch throws and every test silently measures the random fallback.+ claimLeastLoaded.mockImplementation(async (c: { id: string }[]) => c[0]?.id);getSuspect.mockResolvedValue(new Set<string>());- getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, reported: true }])));+ getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, base: 0, reported: true }])));});test("still selects, and spreads, when Redis reads fail", async () => {@@ -87,6 +90,34 @@ describe("selectGatewayFromPool under load-tracker failure", () => {await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).resolves.toBeDefined();});+ test("actually uses the load-aware claim, not the random fallback", async () => {+ const svc = buildService();+ claimLeastLoaded.mockResolvedValue("gw-c");++ for (let i = 0; i < 50; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ expect((await svc.selectGatewayFromPool({ poolId: POOL_ID })).id).toBe("gw-c");+ }+ expect(claimLeastLoaded).toHaveBeenCalled();+ // The atomic claim already reserved, so no separate write should follow it.+ expect(reserve).not.toHaveBeenCalled();+ });++ test("keeps the suspect filter when the load path fails", async () => {+ const svc = buildService();+ getSuspect.mockResolvedValue(new Set(["gw-a"]));+ // Anything after the suspect read blowing up must not re-admit the member that just failed.+ claimLeastLoaded.mockRejectedValue(new Error("EVAL failed"));++ const picked = new Set<string>();+ for (let i = 0; i < 200; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ picked.add((await svc.selectGatewayFromPool({ poolId: POOL_ID })).id);+ }+ expect(picked.has("gw-a")).toBe(false);+ expect(picked).toEqual(new Set(["gw-b", "gw-c"]));+ });+test("404s an unknown pool rather than blaming gateway health", async () => {const svc = gatewayPoolServiceFactory({gatewayPoolDAL: { findById: vi.fn().mockResolvedValue(undefined) },@@ -101,7 +132,7 @@ describe("selectGatewayFromPool under load-tracker failure", () => {} as unknown as TDeps);await expect(svc.selectGatewayFromPool({ poolId: POOL_ID })).rejects.toThrow(- `Gateway pool with ID ${POOL_ID} not found`+ `Gateway pool with ID '${POOL_ID}' not found`);});@@ -154,7 +185,7 @@ describe("runWithPoolFailover", () => {markSuspect.mockResolvedValue(undefined);reserve.mockResolvedValue(undefined);getSuspect.mockResolvedValue(new Set<string>());- getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, reported: true }])));+ getScores.mockResolvedValue(new Map(MEMBERS.map((m) => [m.id, { score: 0, base: 0, reported: true }])));});test("returns the result and the member it ran on", async () => {diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.ts b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.tsindex c3e6d8b554..475deffca3 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.test.ts@@ -1,154 +1,51 @@import { TGatewayScore } from "@app/lib/gateway-v2/gateway-load-tracker";-import { chooseLeastLoadedGateway, pickRandomGateway } from "./gateway-pool-selection-fns";+import { isPoolComparable, pickRandomGateway, shuffleForTieBreak } from "./gateway-pool-selection-fns";// Every member reports unless a test says otherwise; a mixed pool is covered separately.const reported = (entries: Record<string, number>): Map<string, TGatewayScore> =>- new Map(Object.entries(entries).map(([id, score]) => [id, { score, reported: true }]));+ new Map(Object.entries(entries).map(([id, score]) => [id, { score, base: score, reported: true }]));const gateways = [{ id: "a" }, { id: "b" }, { id: "c" }];-describe("chooseLeastLoadedGateway", () => {- test("returns undefined when there are no candidates", () => {- expect(chooseLeastLoadedGateway([], new Map())).toBeUndefined();- });-- test("returns the only candidate without consulting scores", () => {- const random = vi.fn();- expect(chooseLeastLoadedGateway([{ id: "a" }], new Map(), random)).toEqual({ id: "a" });- expect(random).not.toHaveBeenCalled();- });-- test("takes the clear minimum alone when the runner-up is not close", () => {- const scores = reported({ a: 10, b: 1, c: 4 });-- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "b" });- }- });-- test("spreads across members that tie exactly", () => {- const scores = reported({ a: 10, b: 1, c: 1 });-- const picked = new Set<string>();- for (let i = 0; i < 500; i += 1) {- picked.add(chooseLeastLoadedGateway(gateways, scores)!.id);- }-- expect(picked).toEqual(new Set(["b", "c"]));- });-- test("a single reservation is decisive, so a concurrent selection moves on", () => {- // A reservation is worth exactly +1. If a tie band of 1 were tolerated it would cancel the- // reservation out and re-shortlist the member the previous selection just claimed.- const pair = [{ id: "a" }, { id: "b" }];- const afterReservingA = reported({ a: 1, b: 0 });-- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(pair, afterReservingA)).toEqual({ id: "b" });- }+describe("isPoolComparable", () => {+ test("comparable when every member reports", () => {+ expect(isPoolComparable(gateways, reported({ a: 1, b: 2, c: 3 }))).toBe(true);});- test("does not hand a two-member pool a coin flip when one is busier", () => {- // Two gateways is the common HA pool size. Always shortlisting both would make the load score- // a no-op there and leave the pool behaving exactly like the old random selection.- const pair = [{ id: "a" }, { id: "b" }];- const scores = reported({ a: 8, b: 0 });-- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(pair, scores)).toEqual({ id: "b" });- }- });-- test("never sends half the traffic to a near-saturated member", () => {- const scores = reported({ a: 0, b: 99, c: 100 });-- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "a" });- }+ test("comparable when no member reports, since the scale is consistent", () => {+ const legacy = new Map(["a", "b", "c"].map((id) => [id, { score: 1, base: 1, reported: false }]));+ expect(isPoolComparable(gateways, legacy)).toBe(true);});- test("does not compare a member it has no data for", () => {- // c is absent entirely, so the set is not on one scale. Guessing it is idle would pull traffic- // toward the one member we know least about.- const scores = reported({ a: 5, b: 5 });- const picked = new Set<string>();- for (let i = 0; i < 500; i += 1) {- picked.add(chooseLeastLoadedGateway(gateways, scores)!.id);- }- expect(picked).toEqual(new Set(["a", "b", "c"]));- });-- test("gives a mixed-version pool no load awareness rather than a biased guess", () => {- // b is too old to report, so its score covers only platform-opened channels and is strictly- // lower than a reporting peer's true occupancy. Comparing them would favour b all rollout long.+ test("not comparable when the pool is mid-rollout", () => {const mixed = new Map([- ["a", { score: 40, reported: true }],- ["b", { score: 0, reported: false }],- ["c", { score: 41, reported: true }]+ ["a", { score: 40, base: 40, reported: true }],+ ["b", { score: 0, base: 0, reported: false }],+ ["c", { score: 41, base: 41, reported: true }]]);-- const tally: Record<string, number> = { a: 0, b: 0, c: 0 };- for (let i = 0; i < 3000; i += 1) {- tally[chooseLeastLoadedGateway(gateways, mixed)!.id] += 1;- }-- // Uniform, not "b wins every time".- for (const id of ["a", "b", "c"]) expect(tally[id]).toBeGreaterThan(700);+ expect(isPoolComparable(gateways, mixed)).toBe(false);});- test("uses load awareness when every member reports", () => {- const scores = reported({ a: 40, b: 0, c: 41 });- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(gateways, scores)).toEqual({ id: "b" });- }- });-- test("uses load awareness when no member reports, since the scale is consistent", () => {- const legacy = new Map([- ["a", { score: 9, reported: false }],- ["b", { score: 1, reported: false }],- ["c", { score: 8, reported: false }]- ]);- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(gateways, legacy)).toEqual({ id: "b" });- }+ test("not comparable when a member has no data at all", () => {+ expect(isPoolComparable(gateways, reported({ a: 5, b: 5 }))).toBe(false);});+});- test("reaches every member when the pool is idle and all scores tie", () => {- // A deterministic tie-break would shortlist the same two members forever, so a third gateway- // would sit unused for as long as the pool stays idle. That is the common case, not an edge case.- const seen = new Set<string>();+describe("shuffleForTieBreak", () => {+ test("reaches every position, which is what randomises ties in the claim", () => {+ const firsts = new Set<string>();for (let i = 0; i < 3000; i += 1) {- seen.add(chooseLeastLoadedGateway(gateways, new Map())!.id);- }- expect(seen).toEqual(new Set(["a", "b", "c"]));- });-- test("spreads an idle pool roughly evenly", () => {- const tally: Record<string, number> = { a: 0, b: 0, c: 0 };- for (let i = 0; i < 30_000; i += 1) {- tally[chooseLeastLoadedGateway(gateways, new Map())!.id] += 1;- }- // Uniform would be 10,000 each. Loose bound: this asserts nobody is starved, not an exact ratio.- for (const id of ["a", "b", "c"]) {- expect(tally[id]).toBeGreaterThan(7_000);- }- });-- test("still prefers the least loaded once scores differ", () => {- const scores = reported({ a: 50, b: 0, c: 1 });-- // Whatever the shuffle does, the heavily loaded member must never be shortlisted.- for (let i = 0; i < 500; i += 1) {- expect(chooseLeastLoadedGateway(gateways, scores)!.id).not.toBe("a");+ firsts.add(shuffleForTieBreak(gateways, Math.random)[0].id);}+ expect(firsts).toEqual(new Set(["a", "b", "c"]));});- test("does not mutate the caller's candidate array", () => {+ test("does not mutate the caller's array and keeps every member", () => {const input = [{ id: "c" }, { id: "a" }, { id: "b" }];- chooseLeastLoadedGateway(input, new Map(), () => 0);+ const out = shuffleForTieBreak(input, Math.random);expect(input.map((g) => g.id)).toEqual(["c", "a", "b"]);+ expect(out.map((g) => g.id).sort()).toEqual(["a", "b", "c"]);});});diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.tsindex eb1935a2fe..49a752052c 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-selection-fns.ts@@ -2,11 +2,6 @@ import { TGatewayScore } from "@app/lib/gateway-v2/gateway-load-tracker";export type TSelectableGateway = { id: string };-// Only exact ties are randomised. A reservation is worth exactly +1, so any wider band would cancel-// it out and re-shortlist the member a concurrent selection just claimed, which is the stampede the-// reservation exists to prevent.-const SCORE_TIE_BAND = 0;-export const pickRandomGateway = <T extends TSelectableGateway>(candidates: T[],random: () => number = Math.random@@ -16,47 +11,25 @@ export const pickRandomGateway = <T extends TSelectableGateway>(};/**- * Picks the least-loaded member, breaking between the two lowest at random.- *- * The random tie-break matters because every backend pod reads the same shared counters. Taking the- * strict minimum would make all of them choose the same idle gateway in the same instant and stampede- * it, which is the imbalance this is meant to remove.+ * False when some members report their own load and others are too old to, because the two numbers+ * are on different scales: a non-reporting member is counted only on channels this platform opened,+ * which is strictly lower than a reporting peer's true occupancy. Comparing them would pull traffic+ * onto un-upgraded gateways for a whole rollout, so such a pool gets no load awareness at all.*/-export const chooseLeastLoadedGateway = <T extends TSelectableGateway>(+export const isPoolComparable = <T extends TSelectableGateway>(candidates: T[],- scores: Map<string, TGatewayScore>,- random: () => number = Math.random-): T | undefined => {- if (candidates.length === 0) return undefined;- if (candidates.length === 1) return candidates[0];-- // A member too old to report its own count is scored only on the channels this platform opened,- // which is a strictly lower number than a reporting peer's true occupancy. Comparing the two would- // make the un-upgraded member look idle and pull traffic toward it for the whole rollout, so a- // mixed pool gets no load awareness at all rather than a biased guess.+ scores: Map<string, TGatewayScore>+): boolean => {const reportedCount = candidates.filter((c) => scores.get(c.id)?.reported).length;- if (reportedCount > 0 && reportedCount < candidates.length) {- return pickRandomGateway(candidates, random);- }+ return reportedCount === 0 || reportedCount === candidates.length;+};- // Shuffle before ranking. An idle pool scores every member zero, and a deterministic tie-break- // would then always shortlist the same two, leaving every member past the second with no traffic- // at all. Sort is stable, so shuffling first randomises ties while keeping the least-loaded order.+/** Ties are resolved by position, so shuffling first is what randomises between equally loaded members. */+export const shuffleForTieBreak = <T>(candidates: T[], random: () => number): T[] => {const shuffled = [...candidates];for (let i = shuffled.length - 1; i > 0; i -= 1) {const j = Math.floor(random() * (i + 1));[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];}-- const scoreOf = (id: string) => scores.get(id)?.score ?? 0;- const ranked = shuffled.sort((a, b) => scoreOf(a.id) - scoreOf(b.id));-- // Only shortlist the runner-up when it ties. Always taking the two lowest would hand a two-member- // pool a coin flip regardless of load, and would still send half the traffic to a near-saturated- // member in a pool scored {0, 99, 100}.- const best = scoreOf(ranked[0].id);- const runnerUp = scoreOf(ranked[1].id);- const shortlist = runnerUp - best <= SCORE_TIE_BAND ? ranked.slice(0, 2) : [ranked[0]];-- return shortlist[Math.floor(random() * shortlist.length)];+ return shuffled;};diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.tsindex 7a3a64e237..c7930c8862 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts@@ -19,7 +19,7 @@ import { TPermissionServiceFactory } from "../permission/permission-service-typeimport { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";import { TGatewayPoolDALFactory } from "./gateway-pool-dal";import { TGatewayPoolMembershipDALFactory } from "./gateway-pool-membership-dal";-import { chooseLeastLoadedGateway, pickRandomGateway } from "./gateway-pool-selection-fns";+import { isPoolComparable, pickRandomGateway, shuffleForTieBreak } from "./gateway-pool-selection-fns";import {DEFAULT_POOL_FAILOVER_ATTEMPTS,TAddGatewayToPoolDTO,@@ -262,7 +262,7 @@ export const gatewayPoolServiceFactory = ({const selectGatewayFromPool = async ({ poolId, exclude, filter, unavailableMessage }: TSelectGatewayFromPoolDTO) => {const targetPool = await gatewayPoolDAL.findById(poolId);if (!targetPool) {- throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });+ throw new NotFoundError({ message: `Gateway pool with ID '${poolId}' not found` });}const healthyGateways = await gatewayPoolMembershipDAL.findHealthyGatewaysByPoolId(poolId);@@ -279,6 +279,10 @@ export const gatewayPoolServiceFactory = ({const loadTracker = getGatewayLoadTracker();let selected: (typeof eligible)[number] | undefined;+ let claimedAtomically = false;+ // Outlives the try: if anything in the load path fails we still want the suspect filter, or the+ // fallback would happily hand back the member whose transport just failed.+ let pool = eligible;if (loadTracker) {try {@@ -287,24 +291,42 @@ export const gatewayPoolServiceFactory = ({// A pool where every member recently failed is still worth attempting: refusing to route is a// guaranteed outage, whereas the suspect marks may simply have aged badly.const candidates = eligible.filter((gateway) => !suspect.has(gateway.id));- const pool = candidates.length > 0 ? candidates : eligible;+ pool = candidates.length > 0 ? candidates : eligible;const scores = await loadTracker.getScores(pool.map((gateway) => gateway.id));- selected = chooseLeastLoadedGateway(pool, scores);++ if (isPoolComparable(pool, scores)) {+ // Choose and claim atomically. Reading the minimum and then writing the reservation as two+ // calls lets every concurrent selection observe the same minimum and pile onto it.+ const claimed = await loadTracker.claimLeastLoaded(+ shuffleForTieBreak(pool, Math.random).map((gateway) => ({+ id: gateway.id,+ base: scores.get(gateway.id)?.base ?? 0+ }))+ );+ selected = pool.find((gateway) => gateway.id === claimed);+ if (selected) claimedAtomically = true;+ } else {+ // Mixed-version pool: the scales are not comparable, so there is nothing to claim against.+ selected = pickRandomGateway(pool);+ }} catch (err) {logger.warn({ err, poolId }, `Gateway load lookup failed, falling back to random selection [poolId=${poolId}]`);}}- if (!selected) selected = pickRandomGateway(eligible);+ if (!selected) selected = pickRandomGateway(pool);if (!selected)throw new BadRequestError({ message: unavailableMessage ?? "Gateway pool has no healthy gateways." });// Bookkeeping must never be able to fail a selection, whatever the tracker does internally.- try {- await loadTracker?.reserve(selected.id);- } catch (err) {- logger.warn({ err, poolId }, `Failed to reserve gateway capacity [poolId=${poolId}]`);+ // The atomic path has already claimed its member.+ if (!claimedAtomically) {+ try {+ await loadTracker?.reserve(selected.id);+ } catch (err) {+ logger.warn({ err, poolId }, `Failed to reserve gateway capacity [poolId=${poolId}]`);+ }}logger.info(diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 6ef99e063b..0b9f193b02 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -994,18 +994,25 @@ export const gatewayV2ServiceFactory = ({orgPermission: OrgServiceActor;activeChannels: number;}) => {- const gateway =- orgPermission.type === ActorType.GATEWAY- ? await gatewayV2DAL.findById(orgPermission.id)- : await gatewayV2DAL.findOne({ orgId: orgPermission.orgId, identityId: orgPermission.id });+ let gateway;+ if (orgPermission.type === ActorType.GATEWAY) {+ gateway = await gatewayV2DAL.findById(orgPermission.id);+ } else {+ // Same check heartbeat makes: an identity whose gateway permission was revoked must not keep+ // submitting occupancy values and steering pool routing.+ await $validateIdentityAccessToGateway(orgPermission.orgId, orgPermission.id, orgPermission.authMethod);+ gateway = await gatewayV2DAL.findOne({ orgId: orgPermission.orgId, identityId: orgPermission.id });+ }if (!gateway || gateway.orgId !== orgPermission.orgId) {- throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });+ throw new NotFoundError({ message: `Gateway with ID '${orgPermission.id}' not found` });}// Deliberately no heartbeat side effect: liveness stays with /heartbeat so a gateway cannot look// healthy purely by reporting load, and so this stays a single Redis write.await getGatewayLoadTracker()?.recordReportedLoad(gateway.id, activeChannels);++ return { gatewayId: gateway.id, activeChannels };};const deleteGatewayById = async ({ orgPermission, id }: { orgPermission: OrgServiceActor; id: string }) => {diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex f3e61b83b3..6adfd71881 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -284,6 +284,7 @@ export type TKeyStoreFactory = {incrementBy: (key: string, value: number) => Promise<number>;incrementByAndRefreshExpiryIfUnderLimit: (key: string, limit: number, expiryInSeconds: number) => Promise<number>;decrementByOrDelete: (key: string) => Promise<number>;+ claimLeastLoaded: (keys: string[], baseOccupancies: number[], expiryInSeconds: number) => Promise<number>;incrementByWithExpiry: (key: string, value: number, expiryInSeconds: number) => Promise<number>;incrementSeededWithExpiry: (key: string, seed: number, expiryInSeconds: number) => Promise<number>;getKeysByPattern: (pattern: string, limit?: number) => Promise<string[]>;@@ -472,6 +473,45 @@ export const keyStoreFactory = (return Number(result);};+ // Choosing and claiming has to be one round trip. Done as separate read and write calls, every+ // concurrent selection reads the same minimum before any of them claims it and they all pile onto+ // the same gateway, which is the stampede the reservation exists to prevent.+ const CLAIM_LEAST_LOADED_SCRIPT = `+ local ttl = tonumber(ARGV[#ARGV])+ local bestIdx = 0+ local bestTotal = nil+ for i = 1, #KEYS do+ local reserved = tonumber(redis.call("GET", KEYS[i]) or "0")+ local total = tonumber(ARGV[i]) + reserved+ -- strict less-than, so ties fall to the caller's order (pre-shuffled for a random tie-break)+ if bestTotal == nil or total < bestTotal then+ bestTotal = total+ bestIdx = i+ end+ end+ if bestIdx == 0 then return 0 end+ redis.call("INCR", KEYS[bestIdx])+ redis.call("EXPIRE", KEYS[bestIdx], ttl)+ return bestIdx+ `;++ /** Returns the 1-based index of the claimed key, or 0 when no keys were given. */+ const claimLeastLoaded = async (+ keys: string[],+ baseOccupancies: number[],+ expiryInSeconds: number+ ): Promise<number> => {+ if (keys.length === 0) return 0;+ const result = await primaryRedis.eval(+ CLAIM_LEAST_LOADED_SCRIPT,+ keys.length,+ ...keys,+ ...baseOccupancies.map((n) => String(n)),+ String(expiryInSeconds)+ );+ return Number(result);+ };+const INCREMENT_WITH_EXPIRY = `local v = redis.call('INCRBY', KEYS[1], ARGV[1])redis.call('EXPIRE', KEYS[1], ARGV[2])@@ -659,6 +699,7 @@ export const keyStoreFactory = (incrementBy,incrementByAndRefreshExpiryIfUnderLimit,decrementByOrDelete,+ claimLeastLoaded,incrementByWithExpiry,incrementSeededWithExpiry,acquireLock(resources: string[], duration: number, settings?: Partial<Settings>) {diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 3366447c52..73a70c2e5d 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -103,6 +103,23 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {incrementByAndRefreshExpiryIfUnderLimit: async () => {return 1;},+ claimLeastLoaded: async (keys, baseOccupancies) => {+ if (keys.length === 0) return 0;+ let bestIdx = 0;+ let bestTotal: number | null = null;+ keys.forEach((key, i) => {+ const reserved = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;+ const total = baseOccupancies[i] + reserved;+ if (bestTotal === null || total < bestTotal) {+ bestTotal = total;+ bestIdx = i + 1;+ }+ });+ const chosen = keys[bestIdx - 1];+ const current = typeof store[chosen] === "string" ? parseInt(store[chosen] as string, 10) : 0;+ store[chosen] = String(current + 1);+ return bestIdx;+ },decrementByOrDelete: async (key) => {const current = typeof store[key] === "string" ? parseInt(store[key] as string, 10) : 0;const next = current - 1;diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 708c39ecc5..cc1489041b 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3857,6 +3857,11 @@ export const SECRET_SHARING = {} as const;export const GATEWAYS = {+ LOAD_REPORT: {+ activeChannels:+ "Number of channels the gateway is currently serving. Used to route new work to the least busy member of a gateway pool.",+ gatewayId: "ID of the gateway the report was recorded against."+ },CREATE: {name: "Name of the gateway.",authMethod:diff --git a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts b/backend/src/lib/gateway-v2/gateway-load-tracker.test.tsindex ab132a8b6a..526be9dc2c 100644--- a/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.test.ts@@ -171,13 +171,30 @@ describe("gatewayLoadTracker", () => {tracker.shutdown();});+ test("adds channels opened since the gateway's last report", async () => {+ const keyStore = inMemoryKeyStore();+ const tracker = initGatewayLoadTracker(keyStore);++ await tracker.recordReportedLoad(GW_A, 4);+ // Reports land every 10s. Without counting what opened since, every selection inside that window+ // reads the same stale 4 and piles onto this member.+ await vi.advanceTimersByTimeAsync(1_000);+ tracker.channelOpened(GW_A);+ tracker.channelOpened(GW_A);++ expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(6);++ tracker.shutdown();+ });+test("does not sum its own view into the gateway's count", async () => {const tracker = initGatewayLoadTracker(inMemoryKeyStore());- // The reported 3 already includes the 3 this pod opened; summing would say 6.+ // The reported 3 already includes the 3 this pod opened before the report; summing would say 6.tracker.channelOpened(GW_A);tracker.channelOpened(GW_A);tracker.channelOpened(GW_A);+ await vi.advanceTimersByTimeAsync(1_000);await tracker.recordReportedLoad(GW_A, 3);expect((await tracker.getScores([GW_A])).get(GW_A)?.score).toBe(3);@@ -205,8 +222,8 @@ describe("gatewayLoadTracker", () => {await tracker.recordReportedLoad(GW_B, 7);const scores = await tracker.getScores([GW_A, GW_B]);- expect(scores.get(GW_A)).toEqual({ score: 2, reported: false });- expect(scores.get(GW_B)).toEqual({ score: 7, reported: true });+ 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();});@@ -225,6 +242,69 @@ describe("gatewayLoadTracker", () => {tracker.shutdown();});+ test("claims the least loaded member and reserves it in the same call", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ const claimed = await tracker.claimLeastLoaded([+ { id: GW_A, base: 9 },+ { id: GW_B, base: 1 }+ ]);++ 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);++ tracker.shutdown();+ });++ test("concurrent claims stop piling on once the minimum catches up", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ // A unique minimum is the stampede case: read-then-write would send all four to the idle member+ // because none of them would see the others' claims. Each claim here raises its reservation, so+ // the traffic moves across once it reaches the busier member's level.+ const claims = await Promise.all(+ Array.from({ length: 4 }, () =>+ tracker.claimLeastLoaded([+ { id: GW_B, base: 2 },+ { id: GW_A, base: 0 }+ ])+ )+ );++ expect(claims.filter((c) => c === GW_A)).toHaveLength(3);+ expect(claims.filter((c) => c === GW_B)).toHaveLength(1);++ tracker.shutdown();+ });++ test("resolves a tie by the order it is given, so callers control the tie-break", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());++ expect(+ await tracker.claimLeastLoaded([+ { id: GW_A, base: 0 },+ { id: GW_B, base: 0 }+ ])+ ).toBe(GW_A);+ expect(+ await tracker.claimLeastLoaded([+ { id: GW_B, base: 0 },+ { id: GW_A, base: 0 }+ ])+ ).toBe(GW_B);++ tracker.shutdown();+ });++ test("claims nothing when given no candidates", async () => {+ const tracker = initGatewayLoadTracker(inMemoryKeyStore());+ expect(await tracker.claimLeastLoaded([])).toBeUndefined();+ tracker.shutdown();+ });+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.tsindex db36a6c971..19598d22b4 100644--- a/backend/src/lib/gateway-v2/gateway-load-tracker.ts+++ b/backend/src/lib/gateway-v2/gateway-load-tracker.ts@@ -26,6 +26,8 @@ const podId = crypto.randomUUID();export type TGatewayScore = {score: number;+ /** Occupancy excluding reservations, which the atomic claim reads for itself. */+ base: number;/** False when this member is too old to report its own count, so its score is on a different scale. */reported: boolean;};@@ -33,6 +35,7 @@ export type TGatewayScore = {type TGatewayLoadTracker = {recordReportedLoad: (gatewayId: string, activeChannels: number) => Promise<void>;reserve: (gatewayId: string) => Promise<void>;+ claimLeastLoaded: (candidates: { id: string; base: number }[]) => Promise<string | undefined>;channelOpened: (gatewayId: string) => void;channelClosed: (gatewayId: string) => void;markSuspect: (gatewayId: string) => Promise<void>;@@ -56,7 +59,9 @@ const reservationKey = KeyStorePrefixes.GatewayLoadReservation;const suspectKey = KeyStorePrefixes.GatewaySuspect;export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadTracker => {- const openChannels = new Map<string, number>();+ // 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[]>();@@ -64,8 +69,35 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadconst publishChain = new Map<string, Promise<void>>();+ const channelCount = (gatewayId: string) => openChannels.get(gatewayId)?.length ?? 0;++ const releaseReservation = async (gatewayId: string) => {+ try {+ await keyStore.decrementByOrDelete(reservationKey(gatewayId));+ } catch (err) {+ logger.debug({ err, gatewayId }, `Failed to release gateway reservation [gatewayId=${gatewayId}]`);+ }+ };++ // The key TTL is only a backstop for a pod that dies holding reservations; the channel handoff or+ // this timer is what normally releases them.+ function trackReservationRelease(gatewayId: string) {+ const timer = setTimeout(() => {+ reservationTimers.delete(timer);+ const queue = pendingReservations.get(gatewayId);+ const idx = queue?.indexOf(timer) ?? -1;+ if (queue && idx >= 0) queue.splice(idx, 1);+ void releaseReservation(gatewayId);+ }, RESERVATION_HOLD_MS);+ timer.unref();+ reservationTimers.add(timer);+ const queue = pendingReservations.get(gatewayId);+ if (queue) queue.push(timer);+ else pendingReservations.set(gatewayId, [timer]);+ }+const publishNow = async (gatewayId: string) => {- const count = openChannels.get(gatewayId) ?? 0;+ 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.@@ -121,16 +153,10 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad);};- const releaseReservation = async (gatewayId: string) => {- try {- await keyStore.decrementByOrDelete(reservationKey(gatewayId));- } catch (err) {- logger.debug({ err, gatewayId }, `Failed to release gateway reservation [gatewayId=${gatewayId}]`);- }- };-const channelOpened = (gatewayId: string) => {- openChannels.set(gatewayId, (openChannels.get(gatewayId) ?? 0) + 1);+ const open = openChannels.get(gatewayId);+ if (open) open.push(Date.now());+ else openChannels.set(gatewayId, [Date.now()]);// The channel now carries the load the reservation was standing in for. Holding both would// double count the member for the rest of the backstop window.const pending = pendingReservations.get(gatewayId);@@ -144,12 +170,10 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoad};const channelClosed = (gatewayId: string) => {- const next = (openChannels.get(gatewayId) ?? 0) - 1;- if (next > 0) {- openChannels.set(gatewayId, next);- } else {- openChannels.delete(gatewayId);- }+ const open = openChannels.get(gatewayId);+ // 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);};@@ -160,19 +184,24 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadlogger.debug({ err, gatewayId }, `Failed to reserve gateway capacity [gatewayId=${gatewayId}]`);return;}- // The key TTL is only a backstop for a pod that dies holding reservations.- const timer = setTimeout(() => {- reservationTimers.delete(timer);- const queue = pendingReservations.get(gatewayId);- const idx = queue?.indexOf(timer) ?? -1;- if (queue && idx >= 0) queue.splice(idx, 1);- void releaseReservation(gatewayId);- }, RESERVATION_HOLD_MS);- timer.unref();- reservationTimers.add(timer);- const queue = pendingReservations.get(gatewayId);- if (queue) queue.push(timer);- else pendingReservations.set(gatewayId, [timer]);+ trackReservationRelease(gatewayId);+ };++ /**+ * Picks and claims in one round trip. Ties fall to the caller's ordering, so the caller shuffles+ * first to keep the random tie-break that stops every pod choosing the same idle member.+ */+ const claimLeastLoaded = async (candidates: { id: string; base: number }[]) => {+ if (candidates.length === 0) return undefined;+ const idx = await keyStore.claimLeastLoaded(+ candidates.map((c) => reservationKey(c.id)),+ candidates.map((c) => c.base),+ RESERVATION_TTL_SECONDS+ );+ if (idx < 1 || idx > candidates.length) return undefined;+ const claimed = candidates[idx - 1].id;+ trackReservationRelease(claimed);+ return claimed;};const markSuspect = async (gatewayId: string) => {@@ -214,10 +243,20 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadgatewayIds.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 reportedOccupancy = parseStamped(reported[idx], reportedCutoff);+ const rawReported = reported[idx];+ const reportedOccupancy = parseStamped(rawReported, reportedCutoff);let occupancy = reportedOccupancy;- if (occupancy === undefined) {+ if (occupancy !== undefined) {+ // 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);@@ -226,10 +265,11 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadfor (const [, raw] of fields) {occupancy += parseStamped(raw, publishedCutoff) ?? 0;}- occupancy += openChannels.get(gatewayId) ?? 0;+ occupancy += channelCount(gatewayId);}scores.set(gatewayId, {+ base: occupancy,score: occupancy + (Number(reservations[idx] ?? 0) || 0),reported: reportedOccupancy !== undefined});@@ -259,6 +299,7 @@ export const initGatewayLoadTracker = (keyStore: TKeyStoreFactory): TGatewayLoadtracker = {recordReportedLoad,reserve,+ claimLeastLoaded,channelOpened,channelClosed,markSuspect,diff --git a/backend/src/server/config/rateLimiter.ts b/backend/src/server/config/rateLimiter.tsindex 536238fb2d..e4023659de 100644--- a/backend/src/server/config/rateLimiter.ts+++ b/backend/src/server/config/rateLimiter.ts@@ -38,6 +38,19 @@ export const writeLimit: RateLimitOptions = {keyGenerator: (req) => req.realIp};+// Gateways report load every 10s (6/min each). Keyed by the reporting gateway rather than by IP,+// because the write limiter's IP key is shared: ~100 gateways behind one NAT address would exhaust+// a 200/min quota on load reports alone, start getting 429s, and their entries would go stale.+export const gatewayLoadReportLimit: RateLimitOptions = {+ timeWindow: 60 * 1000,+ hook: "preValidation",+ max: 30,+ keyGenerator: (req) => {+ const actorId = (req as { permission?: { id?: string } }).permission?.id;+ return actorId ? `gateway-load:${actorId}` : req.realIp;+ }+};+// special endpointsexport const secretsLimit: RateLimitOptions = {// secrets, folders, secret importsdiff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.tsindex 114cd22b77..20d3cbe306 100644--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts@@ -180,7 +180,7 @@ export const identityKubernetesAuthServiceFactory = ({targetPort: inputs.targetPort ?? 443});if (!details) {- throw new NotFoundError({ message: `Connection details for gateway with ID ${gatewayId} not found` });+ throw new NotFoundError({ message: `Connection details for gateway with ID '${gatewayId}' not found` });}return $proxyThroughGatewayV2(details);}