Skip to content

Commit

Permalink
close idle connection
Browse files Browse the repository at this point in the history
  • Loading branch information
vrtnd committed Sep 4, 2024
1 parent c2bb073 commit cadd9f3
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/handlers/runAllAdapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import bridgeNetworks from "../data/bridgeNetworkData";
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
import { sql } from "../utils/db";
import { store } from "../utils/s3";
import { closeIdleConnections } from "../utils/wrappa/postgres/write";

const lambdaClient = new LambdaClient({});

Expand All @@ -24,6 +25,7 @@ async function invokeLambda(functionName: string, event: any) {
}

export default wrapScheduledLambda(async (event) => {
await closeIdleConnections();
const lastRecordedBlocks = await sql`SELECT jsonb_object_agg(bridge_id::text, subresult) as result
FROM (
SELECT bridge_id, jsonb_build_object('startBlock', MIN(tx_block), 'endBlock', MAX(tx_block)) as subresult
Expand Down
2 changes: 2 additions & 0 deletions src/handlers/runAllAdaptersHistorical.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { wrapScheduledLambda } from "../utils/wrap";
import bridgeNetworks from "../data/bridgeNetworkData";
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
import { closeIdleConnections } from "../utils/wrappa/postgres/write";

const lambdaClient = new LambdaClient({});

Expand All @@ -22,6 +23,7 @@ async function invokeLambda(functionName: string, event: any) {
}

const handler = async (_event: any) => {
await closeIdleConnections();
const now = Math.floor(Date.now() / 1000);
const oneDayAgo = now - 86400;
const halfDayAgo = now - 43200;
Expand Down
21 changes: 21 additions & 0 deletions src/utils/wrappa/postgres/write.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,24 @@ export const insertErrorRow = async (params: {
}
}
};

export const closeIdleConnections = async (idleTimeMinutes = 3) => {
try {
const result = await sql`
WITH closed AS (
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle'
AND state_change < NOW() - INTERVAL '${idleTimeMinutes} minutes'
AND pid <> pg_backend_pid()
)
SELECT COUNT(*) as closed_count FROM closed;
`;

const closedCount = parseInt(result[0].closed_count);
console.log(`${closedCount} idle connection(s) closed successfully. (Idle time: ${idleTimeMinutes} minutes)`);
return closedCount;
} catch (error) {
console.error(`Error closing idle connections (Idle time: ${idleTimeMinutes} minutes):`, error);
}
};

0 comments on commit cadd9f3

Please sign in to comment.