Skip to content

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

improvement: decrease gateway health check interval for HA (#6432)

Saif Ur Rahman32e604ab95a0
diff --git a/backend/src/db/migrations/20260515233927_add-gateway-heartbeat-ttl.ts b/backend/src/db/migrations/20260515233927_add-gateway-heartbeat-ttl.ts
new file mode 100644
index 0000000000..e13b60899e
--- /dev/null
+++ b/backend/src/db/migrations/20260515233927_add-gateway-heartbeat-ttl.ts
@@ -0,0 +1,33 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.GatewayV2, "heartbeatTTL"))) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.integer("heartbeatTTL").nullable();
+ });
+ }
+
+ await knex(TableName.GatewayV2).whereNotNull("heartbeat").whereNull("heartbeatTTL").update({ heartbeatTTL: 1800 });
+
+ if (await knex.schema.hasColumn(TableName.GatewayV2, "lastHealthCheckStatus")) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.dropColumn("lastHealthCheckStatus");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.GatewayV2, "heartbeatTTL")) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.dropColumn("heartbeatTTL");
+ });
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.GatewayV2, "lastHealthCheckStatus"))) {
+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {
+ t.string("lastHealthCheckStatus").nullable();
+ });
+ }
+}
diff --git a/backend/src/db/schemas/gateways-v2.ts b/backend/src/db/schemas/gateways-v2.ts
index aa286fe587..bc4506537c 100644
--- a/backend/src/db/schemas/gateways-v2.ts
+++ b/backend/src/db/schemas/gateways-v2.ts
@@ -20,8 +20,8 @@ export const GatewaysV2Schema = z.object({
heartbeat: z.date().nullable().optional(),
encryptedPamSessionKey: zodBuffer.nullable().optional(),
healthAlertedAt: z.date().nullable().optional(),
- lastHealthCheckStatus: z.string().nullable().optional(),
- tokenVersion: z.number().default(0)
+ tokenVersion: z.number().default(0),
+ heartbeatTTL: z.number().nullable().optional()
});
export type TGatewaysV2 = z.infer<typeof GatewaysV2Schema>;
diff --git a/backend/src/ee/routes/v1/gateway-pool-router.ts b/backend/src/ee/routes/v1/gateway-pool-router.ts
index bf1deeda48..93502537da 100644
--- a/backend/src/ee/routes/v1/gateway-pool-router.ts
+++ b/backend/src/ee/routes/v1/gateway-pool-router.ts
@@ -19,7 +19,7 @@ const SanitizedPoolMemberSchema = GatewaysV2Schema.pick({
id: true,
name: true,
heartbeat: true,
- lastHealthCheckStatus: true
+ heartbeatTTL: true
});
export const registerGatewayPoolRouter = async (server: FastifyZodProvider) => {
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 2d91c321db..3afa024d62 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -14,7 +14,7 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
createdAt: true,
updatedAt: true,
heartbeat: true,
- lastHealthCheckStatus: true
+ heartbeatTTL: true
});
export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
index 740715966a..4694ce6a45 100644
--- a/backend/src/ee/routes/v3/gateway-router.ts
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -22,7 +22,7 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
createdAt: true,
updatedAt: true,
heartbeat: true,
- lastHealthCheckStatus: true
+ heartbeatTTL: true
}).extend({
canRevoke: z.boolean()
});
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
index 118b294293..fa5f8f46e6 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
@@ -5,8 +5,7 @@ import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols } from "@app/lib/knex";
-import { GATEWAY_HEARTBEAT_TIMEOUT_MS } from "../gateway-v2/gateway-v2-constants";
-import { GatewayHealthCheckStatus } from "../gateway-v2/gateway-v2-types";
+import { HEARTBEAT_BUFFER_SECONDS } from "../gateway-v2/gateway-v2-constants";
export type TGatewayPoolDALFactory = ReturnType<typeof gatewayPoolDalFactory>;
@@ -15,8 +14,6 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
const findByOrgIdWithDetails = async (orgId: string) => {
try {
- const oneHourAgo = new Date(Date.now() - GATEWAY_HEARTBEAT_TIMEOUT_MS);
-
const pools = await db
.replicaNode()(TableName.GatewayPool)
.where(`${TableName.GatewayPool}.orgId`, orgId)
@@ -30,8 +27,7 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
.select(
db.raw(`COUNT(DISTINCT ${TableName.GatewayPoolMembership}."gatewayId") AS "memberCount"`),
db.raw(
- `COUNT(DISTINCT CASE WHEN ${TableName.GatewayV2}."heartbeat" > ? AND (${TableName.GatewayV2}."lastHealthCheckStatus" IS NULL OR ${TableName.GatewayV2}."lastHealthCheckStatus" != ?) THEN ${TableName.GatewayPoolMembership}."gatewayId" END) AS "healthyMemberCount"`,
- [oneHourAgo, GatewayHealthCheckStatus.Failed]
+ `COUNT(DISTINCT CASE WHEN COALESCE(${TableName.GatewayV2}."heartbeatTTL", 0) > 0 AND ${TableName.GatewayV2}."heartbeat" + make_interval(secs => COALESCE(${TableName.GatewayV2}."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW() THEN ${TableName.GatewayPoolMembership}."gatewayId" END) AS "healthyMemberCount"`
),
db.raw(
`COALESCE(array_agg(DISTINCT ${TableName.GatewayPoolMembership}."gatewayId") FILTER (WHERE ${TableName.GatewayPoolMembership}."gatewayId" IS NOT NULL), '{}') AS "memberGatewayIds"`
@@ -72,7 +68,7 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
`${TableName.GatewayV2}.id`,
`${TableName.GatewayV2}.name`,
`${TableName.GatewayV2}.heartbeat`,
- `${TableName.GatewayV2}.lastHealthCheckStatus`
+ `${TableName.GatewayV2}.heartbeatTTL`
);
return { ...pool, gateways: members };
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts
index d3a4b7b8f8..3d6415408e 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-membership-dal.ts
@@ -3,8 +3,7 @@ import { TableName, TGatewaysV2 } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
-import { GATEWAY_HEARTBEAT_TIMEOUT_MS } from "../gateway-v2/gateway-v2-constants";
-import { GatewayHealthCheckStatus } from "../gateway-v2/gateway-v2-types";
+import { HEARTBEAT_BUFFER_SECONDS } from "../gateway-v2/gateway-v2-constants";
export type TGatewayPoolMembershipDALFactory = ReturnType<typeof gatewayPoolMembershipDalFactory>;
@@ -13,18 +12,13 @@ export const gatewayPoolMembershipDalFactory = (db: TDbClient) => {
const findHealthyGatewaysByPoolId = async (poolId: string): Promise<TGatewaysV2[]> => {
try {
- const oneHourAgo = new Date(Date.now() - GATEWAY_HEARTBEAT_TIMEOUT_MS);
-
const gateways = await db
.replicaNode()(TableName.GatewayPoolMembership)
.where(`${TableName.GatewayPoolMembership}.gatewayPoolId`, poolId)
.join(TableName.GatewayV2, `${TableName.GatewayPoolMembership}.gatewayId`, `${TableName.GatewayV2}.id`)
- .where(`${TableName.GatewayV2}.heartbeat`, ">", oneHourAgo)
- .where((builder) => {
- void builder
- .whereNull(`${TableName.GatewayV2}.lastHealthCheckStatus`)
- .orWhereNot(`${TableName.GatewayV2}.lastHealthCheckStatus`, GatewayHealthCheckStatus.Failed);
- })
+ .whereRaw(
+ `COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) > 0 AND "${TableName.GatewayV2}"."heartbeat" + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) > NOW()`
+ )
.select(`${TableName.GatewayV2}.*`);
return gateways as TGatewaysV2[];
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
index 971c58bea3..45e7f2d9ac 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts
@@ -1,4 +1,5 @@
-export const GATEWAY_HEARTBEAT_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
+export const HEARTBEAT_BUFFER_SECONDS = 30;
+export const DEFAULT_HEARTBEAT_TTL = 1800; // 30 minutes — fallback for old gateways that don't report their interval
export const GATEWAY_ROUTING_INFO_OID = "1.3.6.1.4.1.12345.100.1";
export const GATEWAY_ACTOR_OID = "1.3.6.1.4.1.12345.100.2";
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
index 9c03e50e1f..ed16bd5c16 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts
@@ -5,7 +5,7 @@ import { GatewaysV2Schema, TableName, TGatewaysV2 } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";
-import { GatewayHealthCheckStatus } from "./gateway-v2-types";
+import { HEARTBEAT_BUFFER_SECONDS } from "./gateway-v2-constants";
export type TGatewayV2DALFactory = ReturnType<typeof gatewayV2DalFactory>;
@@ -27,20 +27,23 @@ export const gatewayV2DalFactory = (db: TDbClient) => {
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"));
if (isHeartbeatStale) {
- const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
+ // Gateway is stale when: heartbeat + heartbeatTTL + buffer < NOW(), OR heartbeatTTL = 0
+ // Only consider gateways that have heartbeat (registered and probed at least once)
+ void query.whereNotNull(`${TableName.GatewayV2}.heartbeat`);
void query.where((builder) => {
void builder
- .where(`${TableName.GatewayV2}.heartbeat`, "<", oneHourAgo)
- .orWhere(`${TableName.GatewayV2}.lastHealthCheckStatus`, GatewayHealthCheckStatus.Failed);
+ .where(
+ db.raw(
+ `"${TableName.GatewayV2}"."heartbeat" + make_interval(secs => COALESCE("${TableName.GatewayV2}"."heartbeatTTL", 0) + ${HEARTBEAT_BUFFER_SECONDS}) < NOW()`
+ )
+ )
+ .orWhere(`${TableName.GatewayV2}.heartbeatTTL`, 0);
});
+ // Notification cooldown: only alert if never alerted or last alert was over 1 hour ago
void query.where((v) => {
void v
.whereNull(`${TableName.GatewayV2}.healthAlertedAt`)
- .orWhere(
- `${TableName.GatewayV2}.healthAlertedAt`,
- "<",
- db.ref("heartbeat").withSchema(TableName.GatewayV2)
- );
+ .orWhere(`${TableName.GatewayV2}.healthAlertedAt`, "<", db.raw("NOW() - interval '1 hour'"));
});
}
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index e4cfa68aad..6eeb0f8a45 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -41,9 +41,14 @@ import { TRelayDALFactory } from "../relay/relay-dal";
import { TRelayServiceFactory } from "../relay/relay-service";
import { TResourceAuthMethodServiceFactory } from "../resource-auth-method/resource-auth-method-service";
import { TAwsAuthMethodConfig } from "../resource-auth-method/resource-auth-method-types";
-import { GATEWAY_ACTOR_OID, GATEWAY_ROUTING_INFO_OID, PAM_INFO_OID } from "./gateway-v2-constants";
+import {
+ DEFAULT_HEARTBEAT_TTL,
+ GATEWAY_ACTOR_OID,
+ GATEWAY_ROUTING_INFO_OID,
+ PAM_INFO_OID
+} from "./gateway-v2-constants";
import { TGatewayV2DALFactory } from "./gateway-v2-dal";
-import { GatewayHealthCheckStatus, TGatewayV2ConnectionDetails } from "./gateway-v2-types";
+import { TGatewayV2ConnectionDetails } from "./gateway-v2-types";
import { TOrgGatewayConfigV2DALFactory } from "./org-gateway-config-v2-dal";
// Temporary limit until gateway limiting is implemented at the relay level
@@ -843,14 +848,14 @@ export const gatewayV2ServiceFactory = ({
throw new NotFoundError({ message: `Gateway connection details for gateway ${gatewayId} not found.` });
}
- let isGatewayReachable = false;
+ let probeResponse: string | undefined;
try {
- isGatewayReachable = await withGatewayV2Proxy(
+ probeResponse = await withGatewayV2Proxy(
async (port) => {
- return new Promise<boolean>((resolve, reject) => {
+ return new Promise<string>((resolve, reject) => {
const socket = new net.Socket();
- let responseReceived = false;
let isResolved = false;
+ const chunks: Buffer[] = [];
socket.setTimeout(10000);
@@ -861,12 +866,21 @@ export const gatewayV2ServiceFactory = ({
};
socket.on("data", (data: Buffer) => {
- const response = data.toString().trim();
- if (response === "PONG" && !isResolved) {
+ chunks.push(data);
+ const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
+ if (totalLength > 1024) {
+ if (!isResolved) {
+ isResolved = true;
+ cleanup();
+ reject(new Error("Probe response exceeded 1KB limit"));
+ }
+ return;
+ }
+ const response = Buffer.concat(chunks).toString().trim();
+ if ((response === "PONG" || response.includes("\n") || response.endsWith("}")) && !isResolved) {
isResolved = true;
- responseReceived = true;
cleanup();
- resolve(true);
+ resolve(response);
}
});
@@ -887,10 +901,10 @@ export const gatewayV2ServiceFactory = ({
});
socket.on("close", () => {
- if (!isResolved && !responseReceived) {
+ if (!isResolved) {
isResolved = true;
cleanup();
- reject(new Error("Connection closed without receiving PONG"));
+ reject(new Error("Connection closed without receiving response"));
}
});
@@ -898,31 +912,42 @@ export const gatewayV2ServiceFactory = ({
});
},
{
- protocol: GatewayProxyProtocol.Ping,
+ protocol: GatewayProxyProtocol.Health,
relayHost: gatewayV2ConnectionDetails.relayHost,
gateway: gatewayV2ConnectionDetails.gateway,
relay: gatewayV2ConnectionDetails.relay
}
);
} catch (err) {
- await gatewayV2DAL.updateById(gatewayId, {
- heartbeat: new Date(),
- lastHealthCheckStatus: GatewayHealthCheckStatus.Failed
- });
+ // Probe failed — gateway is unreachable. Mark TTL as 0 but preserve the last successful heartbeat timestamp.
+ await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
throw err;
}
- if (!isGatewayReachable) {
- await gatewayV2DAL.updateById(gatewayId, {
- heartbeat: new Date(),
- lastHealthCheckStatus: GatewayHealthCheckStatus.Failed
- });
+ if (!probeResponse) {
+ await gatewayV2DAL.updateById(gatewayId, { heartbeatTTL: 0 });
throw new BadRequestError({ message: `Gateway ${gatewayId} is not reachable` });
}
+ // Parse the response to extract heartbeatTTL.
+ // New gateways respond with JSON: {"status":"ok","heartbeatTTL":180}
+ // Old gateways respond with plain: PONG
+ let heartbeatTTL = DEFAULT_HEARTBEAT_TTL;
+ if (probeResponse.startsWith("{")) {
+ try {
+ const parsed = JSON.parse(probeResponse) as { status?: string; heartbeatTTL?: number };
+ if (parsed.status === "ok" && typeof parsed.heartbeatTTL === "number" && parsed.heartbeatTTL > 0) {
+ heartbeatTTL = parsed.heartbeatTTL;
+ }
+ } catch {
+ // Malformed JSON — fall back to default TTL since the gateway *was* reachable
+ logger.warn({ gatewayId, probeResponse }, "Gateway health probe returned unparseable JSON, using default TTL");
+ }
+ }
+
await gatewayV2DAL.updateById(gatewayId, {
heartbeat: new Date(),
- lastHealthCheckStatus: GatewayHealthCheckStatus.Healthy
+ heartbeatTTL
});
};
@@ -1066,7 +1091,7 @@ export const gatewayV2ServiceFactory = ({
logger.warn(
{ gatewayIds: unhealthyGateways.map((g) => g.id) },
- "Found gateways with last heartbeat over an hour ago. Sending notifications."
+ "Found gateways that may be offline or unreachable. Sending notifications."
);
const gatewaysByOrg = groupBy(unhealthyGateways, (gw) => gw.orgId);
@@ -1083,7 +1108,7 @@ export const gatewayV2ServiceFactory = ({
}
const gatewayNames = gateways.map((g) => `"${g.name}"`).join(", ");
- const body = `The following gateway(s) in your organization may be offline as they haven't reported a heartbeat in over an hour: ${gatewayNames}. Please check their status.`;
+ const body = `The following gateway(s) in your organization may be offline or unreachable: ${gatewayNames}. Please check their status.`;
await notificationService.createUserNotifications(
admins.map((admin) => ({
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
index 9766049402..68adcfd4d1 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-types.ts
@@ -1,8 +1,3 @@
-export enum GatewayHealthCheckStatus {
- Healthy = "healthy",
- Failed = "failed"
-}
-
export type TGatewayV2ConnectionDetails = {
relayHost: string;
gateway: {
diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
index 9b61f86016..6c6dbd9900 100644
--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-service.ts
@@ -321,7 +321,7 @@ export const resourceAuthMethodServiceFactory = ({
}
await gatewayV2DAL.updateById(
gateway.id,
- { $incr: { tokenVersion: 1 }, heartbeat: null, lastHealthCheckStatus: null },
+ { $incr: { tokenVersion: 1 }, heartbeat: null, heartbeatTTL: null },
tx
);
return { deletedTokenCount };
@@ -385,7 +385,7 @@ export const resourceAuthMethodServiceFactory = ({
const refreshed = await gatewayV2DAL.updateById(gateway.id, {
$incr: { tokenVersion: 1 },
heartbeat: null,
- lastHealthCheckStatus: null
+ heartbeatTTL: null
});
const accessToken = mintGatewayJwt({
@@ -433,7 +433,7 @@ export const resourceAuthMethodServiceFactory = ({
if (!existing) throw new NotFoundError({ message: `Gateway ${linkedGatewayId} not found` });
return gatewayV2DAL.updateById(
existing.id,
- { $incr: { tokenVersion: 1 }, heartbeat: null, lastHealthCheckStatus: null },
+ { $incr: { tokenVersion: 1 }, heartbeat: null, heartbeatTTL: null },
tx
);
});
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index 3a5a7fcc96..8e77800e1d 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -84,12 +84,13 @@ export const createGatewayConnection = async (
): Promise<net.Socket> => {
const appCfg = getConfig();
- const protocolToAlpn = {
- [GatewayProxyProtocol.Http]: "infisical-http-proxy",
- [GatewayProxyProtocol.Tcp]: "infisical-tcp-proxy",
- [GatewayProxyProtocol.Ping]: "infisical-ping",
- [GatewayProxyProtocol.Pam]: "infisical-pam-proxy",
- [GatewayProxyProtocol.PamSessionCancellation]: "infisical-pam-session-cancellation"
+ const protocolToAlpn: Record<string, string[]> = {
+ [GatewayProxyProtocol.Http]: ["infisical-http-proxy"],
+ [GatewayProxyProtocol.Tcp]: ["infisical-tcp-proxy"],
+ [GatewayProxyProtocol.Ping]: ["infisical-ping"],
+ [GatewayProxyProtocol.Health]: ["infisical-health", "infisical-ping"],
+ [GatewayProxyProtocol.Pam]: ["infisical-pam-proxy"],
+ [GatewayProxyProtocol.PamSessionCancellation]: ["infisical-pam-session-cancellation"]
};
const tlsOptions: tls.ConnectionOptions = {
@@ -100,7 +101,7 @@ export const createGatewayConnection = async (
minVersion: "TLSv1.2",
maxVersion: "TLSv1.3",
rejectUnauthorized: true,
- ALPNProtocols: [protocolToAlpn[protocol]],
+ ALPNProtocols: protocolToAlpn[protocol],
checkServerIdentity: appCfg.isDevelopmentMode ? () => undefined : tls.checkServerIdentity
};
diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.ts
index 4b821db872..d20c954dec 100644
--- a/backend/src/lib/gateway/types.ts
+++ b/backend/src/lib/gateway/types.ts
@@ -8,6 +8,7 @@ export enum GatewayProxyProtocol {
Http = "http",
Tcp = "tcp",
Ping = "ping",
+ Health = "health",
Pam = "pam",
PamSessionCancellation = "pam-session-cancellation"
}
diff --git a/docs/documentation/platform/gateways/gateway-pools.mdx b/docs/documentation/platform/gateways/gateway-pools.mdx
index 271241740c..1536a8ed2f 100644
--- a/docs/documentation/platform/gateways/gateway-pools.mdx
+++ b/docs/documentation/platform/gateways/gateway-pools.mdx
@@ -19,7 +19,7 @@ Gateway Pools provide high availability for your gateway infrastructure. A pool
3. At request time, the platform picks a random healthy gateway from the pool and routes through it.
4. If a gateway goes down, subsequent requests automatically route through the remaining healthy gateways.
-A gateway is considered healthy if it has sent a heartbeat within the last hour and its last health check did not fail.
+A gateway is considered healthy if it has sent a successful heartbeat within its TTL window.
## Creating a Gateway Pool
diff --git a/docs/documentation/platform/gateways/overview.mdx b/docs/documentation/platform/gateways/overview.mdx
index b3f77efe4e..02a0d74e7b 100644
--- a/docs/documentation/platform/gateways/overview.mdx
+++ b/docs/documentation/platform/gateways/overview.mdx
@@ -61,7 +61,7 @@ The Gateway system uses SSH reverse tunnels for secure, firewall-friendly connec
## Health Check
-To monitor their operational status, both gateways and relays transmit hourly heartbeats. A component is considered unhealthy if a heartbeat is not received for over an hour.
+To monitor their operational status, gateways transmit heartbeats every 3 minutes. Each heartbeat includes a TTL (time-to-live) indicating how long the gateway should be considered healthy. If no successful heartbeat is received before the TTL expires, the gateway is marked as unhealthy. Relays continue to transmit hourly heartbeats and are considered unhealthy if a heartbeat is not received within one hour.
Infisical automatically notifies all organization admins of unhealthy gateway or relay statuses through email and in-app notifications.
diff --git a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
index 4a092e452a..54273fcf68 100644
--- a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
+++ b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
@@ -7,7 +7,7 @@ import { Select, SelectItem, Tooltip } from "@app/components/v2";
import { useSubscription } from "@app/context";
import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
-import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";
+import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { PoolHealthBadge } from "@app/pages/organization/NetworkingPage/components/GatewayTab/components/PoolHealthBadge";
type GatewayPickerValue = {
@@ -70,12 +70,7 @@ export const GatewayPicker = ({
const v2Gateways = gateways?.filter((g) => !g.isV1) ?? [];
- const isOnline = (gw: (typeof v2Gateways)[number]) =>
- "heartbeat" in gw &&
- gw.heartbeat &&
- new Date(gw.heartbeat).getTime() > Date.now() - 60 * 60 * 1000 &&
- (!("lastHealthCheckStatus" in gw) ||
- gw.lastHealthCheckStatus !== GatewayHealthCheckStatus.Failed);
+ const isOnline = (gw: (typeof v2Gateways)[number]) => isGatewayHealthy(gw);
const itemHoverV3 =
"[&_[data-radix-collection-item]:hover]:bg-foreground/5 [&_[data-radix-collection-item][data-highlighted]]:bg-foreground/5";
diff --git a/frontend/src/hooks/api/gateway-pools/types.ts b/frontend/src/hooks/api/gateway-pools/types.ts
index 9154b84c72..d67f2b07a9 100644
--- a/frontend/src/hooks/api/gateway-pools/types.ts
+++ b/frontend/src/hooks/api/gateway-pools/types.ts
@@ -49,7 +49,7 @@ export type TGatewayPoolMember = {
id: string;
name: string;
heartbeat: string | null;
- lastHealthCheckStatus: string | null;
+ heartbeatTTL: number | null;
};
export type TGatewayPoolWithMembers = {
diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.ts
index f2c0a2379c..797b376242 100644
--- a/frontend/src/hooks/api/gateways-v2/types.ts
+++ b/frontend/src/hooks/api/gateways-v2/types.ts
@@ -1,8 +1,3 @@
-export enum GatewayHealthCheckStatus {
- Healthy = "healthy",
- Failed = "failed"
-}
-
export type TGatewayV2 = {
id: string;
identityId: string | null;
@@ -10,7 +5,7 @@ export type TGatewayV2 = {
createdAt: string;
updatedAt: string;
heartbeat: string | null;
- lastHealthCheckStatus: GatewayHealthCheckStatus | null;
+ heartbeatTTL: number | null;
canRevoke: boolean;
connectedResourcesCount: number;
identity: {
diff --git a/frontend/src/hooks/api/gateways-v2/utils.ts b/frontend/src/hooks/api/gateways-v2/utils.ts
new file mode 100644
index 0000000000..a88483a669
--- /dev/null
+++ b/frontend/src/hooks/api/gateways-v2/utils.ts
@@ -0,0 +1,14 @@
+export const HEARTBEAT_BUFFER_SECONDS = 30;
+
+export const isGatewayHealthy = (gateway: {
+ heartbeat?: string | null;
+ heartbeatTTL?: number | null;
+}): boolean => {
+ if (!gateway.heartbeat) return false;
+ if (!gateway.heartbeatTTL) return false;
+ return (
+ new Date(gateway.heartbeat).getTime() +
+ (gateway.heartbeatTTL + HEARTBEAT_BUFFER_SECONDS) * 1000 >
+ Date.now()
+ );
+};
diff --git a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
index 4c690955f0..e298e26d56 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
@@ -13,18 +13,17 @@ import {
OrgRelayPermissionActions
} from "@app/context/OrgPermissionContext/types";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
-import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";
+import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { relayQueryKeys } from "@app/hooks/api/relays/queries";
import { TRelay } from "@app/hooks/api/relays/types";
-const ONE_HOUR_MS = 60 * 60 * 1000;
-const ONE_DAY_MS = 24 * ONE_HOUR_MS;
+const ONE_DAY_MS = 24 * 60 * 60 * 1000;
+const RELAY_HEARTBEAT_TIMEOUT_MS = 60 * 60 * 1000;
const DISMISS_STORAGE_KEY = "network-health-banner-dismissed-at";
-const isHeartbeatStale = (heartbeat?: string | null): boolean => {
+const isRelayHeartbeatStale = (heartbeat?: string | null): boolean => {
if (!heartbeat) return true;
- const heartbeatDate = new Date(heartbeat);
- return heartbeatDate.getTime() < Date.now() - ONE_HOUR_MS;
+ return new Date(heartbeat).getTime() < Date.now() - RELAY_HEARTBEAT_TIMEOUT_MS;
};
const wasDismissedWithinLastDay = (): boolean => {
@@ -64,27 +63,16 @@ export const NetworkHealthBanner = () => {
const unreachableGateways = useMemo(
() =>
gateways?.filter((g) => {
- if (
- "lastHealthCheckStatus" in g &&
- g.lastHealthCheckStatus === GatewayHealthCheckStatus.Failed
- ) {
- return true;
- }
- if (!("heartbeat" in g)) return false;
- // Skip gateways that have never connected (both fields null)
- if (
- g.heartbeat === null &&
- ("lastHealthCheckStatus" in g ? g.lastHealthCheckStatus : null) === null
- )
- return false;
- return isHeartbeatStale(g.heartbeat);
+ if (g.isV1) return false;
+ return !isGatewayHealthy(g);
}).length ?? 0,
[gateways]
);
const unreachableRelays = useMemo(
() =>
- relays?.filter((r) => r.orgId && r.heartbeat && isHeartbeatStale(r.heartbeat)).length ?? 0,
+ relays?.filter((r) => r.orgId && r.heartbeat && isRelayHeartbeatStale(r.heartbeat)).length ??
+ 0,
[relays]
);
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
index 5426baa621..04bb12f25c 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayDetailsCard/GatewayDetailsCard.tsx
@@ -4,7 +4,6 @@ import { format } from "date-fns";
import { CheckIcon, ClipboardListIcon, PencilIcon, TriangleAlertIcon } from "lucide-react";
import { OrgPermissionCan } from "@app/components/permissions";
-import { Tooltip } from "@app/components/v2";
import {
Alert,
AlertDescription,
@@ -20,7 +19,10 @@ import {
DetailLabel,
DetailValue,
IconButton,
- Separator
+ Separator,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
} from "@app/components/v3";
import { useOrganization } from "@app/context";
import {
@@ -30,19 +32,19 @@ import {
import { useTimedReset } from "@app/hooks";
import {
GatewayAuthMethodView,
- GatewayHealthCheckStatus,
TGatewayV2,
TGatewayV2WithAuthMethod
} from "@app/hooks/api/gateways-v2/types";
+import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { GatewayAuthMethodModal } from "../GatewayAuthMethod/GatewayAuthMethodModal";
import { ViewGatewayAuth } from "../GatewayAuthMethod/ViewGatewayAuth";
const HealthBadge = ({ gateway }: { gateway: TGatewayV2 }) => {
- if (!gateway.heartbeat && !gateway.lastHealthCheckStatus) {
+ if (!gateway.heartbeat && !gateway.heartbeatTTL) {
return <Badge variant="warning">Unregistered</Badge>;
}
- if (gateway.lastHealthCheckStatus === GatewayHealthCheckStatus.Healthy) {
+ if (isGatewayHealthy(gateway)) {
return <Badge variant="success">Healthy</Badge>;
}
return <Badge variant="danger">Unreachable</Badge>;
@@ -78,18 +80,21 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
<DetailLabel>ID</DetailLabel>
<DetailValue className="flex items-center gap-x-1">
<span className="font-mono text-xs">{gateway.id}</span>
- <Tooltip content="Copy gateway ID to clipboard">
- <IconButton
- aria-label="copy gateway id"
- onClick={() => {
- navigator.clipboard.writeText(gateway.id);
- setCopyTextId("Copied");
- }}
- variant="ghost"
- size="xs"
- >
- {isCopyingId ? <CheckIcon /> : <ClipboardListIcon className="text-label" />}
- </IconButton>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label="copy gateway id"
+ onClick={() => {
+ navigator.clipboard.writeText(gateway.id);
+ setCopyTextId("Copied");
+ }}
+ variant="ghost"
+ size="xs"
+ >
+ {isCopyingId ? <CheckIcon /> : <ClipboardListIcon className="text-label" />}
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Copy gateway ID to clipboard</TooltipContent>
</Tooltip>
</DetailValue>
</Detail>
@@ -100,10 +105,17 @@ export const GatewayDetailsCard = ({ gateway }: { gateway: TGatewayV2WithAuthMet
</DetailValue>
</Detail>
<Detail>
- <DetailLabel>Last Heartbeat</DetailLabel>
+ <DetailLabel>Last Seen</DetailLabel>
<DetailValue>
{gateway.heartbeat ? (
- format(new Date(gateway.heartbeat), "PPpp")
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="cursor-default">
+ {format(new Date(gateway.heartbeat), "PPpp")}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{new Date(gateway.heartbeat).toUTCString()}</TooltipContent>
+ </Tooltip>
) : (
<span className="text-muted">—</span>
)}
diff --git a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
index 9fb8df1779..09acf6cbbd 100644
--- a/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/GatewayDetailsByIDPage/components/GatewayPageHeader/GatewayPageHeader.tsx
@@ -59,7 +59,7 @@ export const GatewayPageHeader = ({ gateway, orgId }: { gateway: TGatewayV2; org
}
};
- const isRegistered = Boolean(gateway.heartbeat || gateway.lastHealthCheckStatus);
+ const isRegistered = Boolean(gateway.heartbeat || gateway.heartbeatTTL);
const { canRevoke } = gateway;
return (
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
index 4c57a9c15f..d70c49c90b 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
@@ -227,7 +227,7 @@ export const GatewayTab = withPermission(
<Tooltip
asChild={false}
className="normal-case"
- content="The last known healthcheck. Triggers every 1 hour."
+ content="The last known healthcheck. Triggers every 3 minutes."
>
<FontAwesomeIcon icon={faInfoCircle} className="ml-2" />
</Tooltip>
@@ -300,9 +300,7 @@ export const GatewayTab = withPermission(
<Td>
<GatewayHealthStatus
heartbeat={"heartbeat" in el ? el.heartbeat : null}
- lastHealthCheckStatus={
- "lastHealthCheckStatus" in el ? el.lastHealthCheckStatus : null
- }
+ heartbeatTTL={"heartbeatTTL" in el ? el.heartbeatTTL : null}
/>
</Td>
<Td className="w-5" onClick={(e) => e.stopPropagation()}>
@@ -325,17 +323,14 @@ export const GatewayTab = withPermission(
>
Copy ID
</DropdownMenuItem>
- {!el.isV1 &&
- ("heartbeat" in el
- ? !!el.heartbeat || !!el.lastHealthCheckStatus
- : false) && (
- <DropdownMenuItem
- icon={<FontAwesomeIcon icon={faHeartPulse} />}
- onClick={() => handleTriggerHealthCheck(el.id)}
- >
- Trigger Health Check
- </DropdownMenuItem>
- )}
+ {!el.isV1 && (!!el.heartbeat || !!el.heartbeatTTL) && (
+ <DropdownMenuItem
+ icon={<FontAwesomeIcon icon={faHeartPulse} />}
+ onClick={() => handleTriggerHealthCheck(el.id)}
+ >
+ Trigger Health Check
+ </DropdownMenuItem>
+ )}
{el.isV1 && (
<OrgPermissionCan
I={OrgGatewayPermissionActions.EditGateways}
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
index a4b74def49..559509cda8 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayHealthStatus.tsx
@@ -1,62 +1,34 @@
-import { faClock } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { format } from "date-fns";
-import { Tooltip } from "@app/components/v2";
-import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
export const GatewayHealthStatus = ({
heartbeat,
- lastHealthCheckStatus,
- isPending,
- isExpired
+ heartbeatTTL
}: {
heartbeat?: string | null;
- lastHealthCheckStatus?: GatewayHealthCheckStatus | null;
- isPending?: boolean;
- isExpired?: boolean;
+ heartbeatTTL?: number | null;
}) => {
- if (isExpired) {
- return (
- <Tooltip content="Enrollment token has expired. Re-enroll to generate a new one.">
- <span className="inline-flex cursor-default items-center gap-1.5 text-red-400">
- Expired
- </span>
- </Tooltip>
- );
- }
-
- if (isPending) {
- return (
- <Tooltip content="Waiting for gateway to enroll using the CLI command">
- <span className="inline-flex cursor-default items-center gap-1.5 text-yellow-500">
- <FontAwesomeIcon icon={faClock} className="size-3" />
- Pending
- </span>
- </Tooltip>
- );
- }
-
- if (!heartbeat && !lastHealthCheckStatus) {
- return (
- <Tooltip content="Gateway has not connected yet">
- <span className="cursor-default text-yellow-500">Unregistered</span>
- </Tooltip>
- );
+ if (!heartbeat && !heartbeatTTL) {
+ return <span className="cursor-default text-yellow-500">Unregistered</span>;
}
const heartbeatDate = heartbeat ? new Date(heartbeat) : null;
-
- const isHealthy = lastHealthCheckStatus === GatewayHealthCheckStatus.Healthy;
-
- const tooltipContent = heartbeatDate
- ? `Last health check: ${heartbeatDate.toLocaleString()}`
- : "No health check data available";
+ const isHealthy = isGatewayHealthy({ heartbeat, heartbeatTTL });
return (
- <Tooltip content={tooltipContent}>
- <span className={`cursor-default ${isHealthy ? "text-green-400" : "text-red-400"}`}>
- {isHealthy ? "Healthy" : "Unreachable"}
- </span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className={`cursor-default ${isHealthy ? "text-green-400" : "text-red-400"}`}>
+ {isHealthy ? "Healthy" : "Unreachable"}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>
+ {heartbeatDate
+ ? `Last seen: ${format(heartbeatDate, "PPpp")} (${heartbeatDate.toUTCString()})`
+ : "No data available"}
+ </TooltipContent>
</Tooltip>
);
};
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
index fc5b9edcdb..29e6a4375c 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
@@ -41,7 +41,7 @@ import { useAddGatewayToPool, useRemoveGatewayFromPool } from "@app/hooks/api/ga
import { TGatewayPool } from "@app/hooks/api/gateway-pools/types";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { useTriggerGatewayV2Heartbeat } from "@app/hooks/api/gateways-v2";
-import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";
+import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { PoolHealthBadge } from "./PoolHealthBadge";
@@ -208,14 +208,7 @@ export const PoolDetailSheet = ({ isOpen, onOpenChange, pool }: Props) => {
</TableRow>
)}
{memberGateways.map((gw) => {
- const hasHeartbeat =
- "heartbeat" in gw &&
- gw.heartbeat &&
- new Date(gw.heartbeat).getTime() > Date.now() - 60 * 60 * 1000;
- const isNotFailed =
- !("lastHealthCheckStatus" in gw) ||
- gw.lastHealthCheckStatus !== GatewayHealthCheckStatus.Failed;
- const isOnline = hasHeartbeat && isNotFailed;
+ const isOnline = isGatewayHealthy(gw);
return (
<TableRow key={gw.id}>