Skip to content

Commit

Permalink
fix(grpc): Memory leak due to open channel references
Browse files Browse the repository at this point in the history
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
  • Loading branch information
SophiaH67 committed Sep 14, 2023
1 parent 11fc112 commit 7667e19
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions lib/health-indicator/microservice/grpc.health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,12 @@ export class GRPCHealthIndicator extends HealthIndicator {
this.checkDependantPackages();
}

/**
* A cache of open channels for the health indicator
* This is used to prevent opening new channels for every health check
*/
private readonly openChannels = new Map<string, GRPCHealthService>();

/**
* Checks if the dependant packages are present
*/
Expand Down Expand Up @@ -185,13 +191,19 @@ export class GRPCHealthIndicator extends HealthIndicator {

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

const client = this.createClient<GrpcOptions>(settings);

let healthService: GRPCHealthService;
try {
healthService = client.getService<GRPCHealthService | any>(
settings.healthServiceName as string,
);
if (this.openChannels.has(service)) {
healthService = this.openChannels.get(service)!;
} else {
const client = this.createClient<GrpcOptions>(settings);

healthService = client.getService<GRPCHealthService>(
settings.healthServiceName as string,
);

this.openChannels.set(service, healthService);
}
} catch (err) {
if (err instanceof TypeError) throw err;
if (isError(err)) {
Expand Down

0 comments on commit 7667e19

Please sign in to comment.