From 83e807ac2464c33ec2edf8b4ed5c4c1040c33620 Mon Sep 17 00:00:00 2001 From: ajay Date: Mon, 5 Jan 2026 18:09:42 +0530 Subject: [PATCH] fix: improve API call connection handling to prevent downtime - Add HTTPS agent with connection pooling (keepAlive, maxSockets) - Improve timeout detection to catch ECONNABORTED errors - Add better axios configuration (maxRedirects, validateStatus) - Enhance error handling for more reliable monitoring This prevents false downtime reports by: 1. Reusing connections to reduce overhead 2. Better timeout detection triggering retry mechanism 3. Connection pooling for improved resilience during traffic spikes --- src/lib/server/services/apiCall.js | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/lib/server/services/apiCall.js b/src/lib/server/services/apiCall.js index 2f54ecf..a6928ba 100644 --- a/src/lib/server/services/apiCall.js +++ b/src/lib/server/services/apiCall.js @@ -69,11 +69,23 @@ class ApiCall { headers: axiosHeaders, timeout: timeout, transformResponse: (r) => r, + maxRedirects: 5, + validateStatus: () => true, + maxContentLength: Infinity, + maxBodyLength: Infinity, }; - if (!!this.monitor.type_data.allowSelfSignedCert) { - options.httpsAgent = new https.Agent({ rejectUnauthorized: false }); - } + // Always configure HTTPS agent for better connection handling + const httpsAgentOptions = { + keepAlive: true, + keepAliveMsecs: 30000, + maxSockets: 50, + maxFreeSockets: 10, + timeout: timeout, + rejectUnauthorized: !this.monitor.type_data.allowSelfSignedCert, + }; + + options.httpsAgent = new https.Agent(httpsAgentOptions); if (!!body) { options.data = body; @@ -89,16 +101,21 @@ class ApiCall { resp = data.data; } catch (err) { console.log(`Error in apiCall ${tag}`, err.message); - if (err.message.startsWith("timeout of") && err.message.endsWith("exceeded")) { + + // Better timeout detection + if (err.code === 'ECONNABORTED' || + (err.message && err.message.includes('timeout'))) { timeoutError = true; + console.log(`Retrying api call for ${tag} at ${Math.floor(Date.now()/1000)} due to timeout`); } + if (err.response !== undefined && err.response.status !== undefined) { statusCode = err.response.status; } if (err.response !== undefined && err.response.data !== undefined) { resp = err.response.data; } else { - resp = JSON.stringify(resp); + resp = err.message || ""; } } finally { const end = Date.now();