Skip to content

Commit

Permalink
feat: add HPA scaling based on memory to web service (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenrob authored Aug 31, 2022
1 parent cafb145 commit 07c7ee1
Show file tree
Hide file tree
Showing 4 changed files with 459 additions and 13 deletions.
5 changes: 4 additions & 1 deletion lib/web-service/web-service-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ export interface HorizontalPodAutoscalerProps {
readonly maxReplicas: number;

/** Target average CPU utilization, as a percentage of the request. */
readonly cpuTargetUtilization: number;
readonly cpuTargetUtilization?: number;

/** Target average memory utilization, as a percentage of the request. */
readonly memoryTargetUtilization?: number;
}

export interface NginxContainerProps {
Expand Down
54 changes: 42 additions & 12 deletions lib/web-service/web-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
KubeHorizontalPodAutoscalerV2Beta2,
KubeIngress,
KubeService,
MetricSpecV2Beta2,
Quantity,
Volume,
} from "../../imports/k8s";
Expand Down Expand Up @@ -282,6 +283,18 @@ export class WebService extends Construct {
"Release stage must be specified when canary deployments are enabled"
);
}

if (
props.horizontalPodAutoscaler &&
!(
props.horizontalPodAutoscaler.cpuTargetUtilization ||
props.horizontalPodAutoscaler.memoryTargetUtilization
)
) {
throw new Error(
"Either cpuTargetUtilization or memoryTargetUtilization must be specified to use a horizontalPodAutoscaler"
);
}
}

findPorts(props: WebServiceProps): {
Expand Down Expand Up @@ -388,6 +401,34 @@ export class WebService extends Construct {
props: HorizontalPodAutoscalerProps,
labels: { [key: string]: string }
): void {
const metrics: Array<MetricSpecV2Beta2> = [];

if (props.cpuTargetUtilization) {
metrics.push({
type: "Resource",
resource: {
name: "cpu",
target: {
type: "Utilization",
averageUtilization: props.cpuTargetUtilization,
},
},
});
}

if (props.memoryTargetUtilization) {
metrics.push({
type: "Resource",
resource: {
name: "memory",
target: {
type: "Utilization",
averageUtilization: props.memoryTargetUtilization,
},
},
});
}

new KubeHorizontalPodAutoscalerV2Beta2(this, `${deployment.node.id}-hpa`, {
metadata: {
labels,
Expand All @@ -400,18 +441,7 @@ export class WebService extends Construct {
},
minReplicas: props.minReplicas,
maxReplicas: props.maxReplicas,
metrics: [
{
type: "Resource",
resource: {
name: "cpu",
target: {
type: "Utilization",
averageUtilization: props.cpuTargetUtilization,
},
},
},
],
metrics: metrics,
},
});
}
Expand Down
Loading

0 comments on commit 07c7ee1

Please sign in to comment.