Skip to content

Commit 781c00e

Browse files
SophiaH67BrunnerLivio
authored andcommitted
fix(grpc): Memory leak due to open channel references
Channels reference themselves with timeout's, meaning that they cannot be garbage collected by v8. This is a workaround that stops us from creating more and more channels; thus fixing a memory leak. Resolves #2329
1 parent e049c7e commit 781c00e

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

lib/health-indicator/microservice/grpc.health.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ export class GRPCHealthIndicator extends HealthIndicator {
105105
this.checkDependantPackages();
106106
}
107107

108+
/**
109+
* A cache of open channels for the health indicator
110+
* This is used to prevent opening new channels for every health check
111+
*/
112+
private readonly openChannels = new Map<string, GRPCHealthService>();
113+
108114
/**
109115
* Checks if the dependant packages are present
110116
*/
@@ -185,13 +191,19 @@ export class GRPCHealthIndicator extends HealthIndicator {
185191

186192
const settings = { ...defaultOptions, ...options };
187193

188-
const client = this.createClient<GrpcOptions>(settings);
189-
190194
let healthService: GRPCHealthService;
191195
try {
192-
healthService = client.getService<GRPCHealthService | any>(
193-
settings.healthServiceName as string,
194-
);
196+
if (this.openChannels.has(service)) {
197+
healthService = this.openChannels.get(service)!;
198+
} else {
199+
const client = this.createClient<GrpcOptions>(settings);
200+
201+
healthService = client.getService<GRPCHealthService>(
202+
settings.healthServiceName as string,
203+
);
204+
205+
this.openChannels.set(service, healthService);
206+
}
195207
} catch (err) {
196208
if (err instanceof TypeError) throw err;
197209
if (isError(err)) {

0 commit comments

Comments
 (0)