1. Answers
  2. Scaling PostgreSQL instances with Kubernetes HPA

How do I scale PostgreSQL instances based on metrics with HPA?

In this guide, you will learn how to scale PostgreSQL instances using Kubernetes Horizontal Pod Autoscaler (HPA) based on CPU utilization metrics. We will define a PostgreSQL Deployment and set up an HPA to automatically adjust the number of replicas based on CPU usage.

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Define the PostgreSQL Deployment
const postgresqlDeployment = new k8s.apps.v1.Deployment("postgresql", {
    metadata: {
        name: "postgresql",
        labels: { app: "postgresql" },
    },
    spec: {
        replicas: 1,
        selector: {
            matchLabels: { app: "postgresql" },
        },
        template: {
            metadata: {
                labels: { app: "postgresql" },
            },
            spec: {
                containers: [{
                    name: "postgresql",
                    image: "postgres:13",
                    ports: [{ containerPort: 5432 }],
                    resources: {
                        requests: {
                            cpu: "500m",
                            memory: "512Mi",
                        },
                        limits: {
                            cpu: "1",
                            memory: "1Gi",
                        },
                    },
                }],
            },
        },
    },
});

// Define the Horizontal Pod Autoscaler (HPA)
const postgresqlHPA = new k8s.autoscaling.v1.HorizontalPodAutoscaler("postgresql-hpa", {
    metadata: {
        name: "postgresql-hpa",
    },
    spec: {
        scaleTargetRef: {
            apiVersion: "apps/v1",
            kind: "Deployment",
            name: "postgresql",
        },
        minReplicas: 1,
        maxReplicas: 5,
        targetCPUUtilizationPercentage: 70,
    },
});

// Export the name of the Deployment and HPA
export const deploymentName = postgresqlDeployment.metadata.name;
export const hpaName = postgresqlHPA.metadata.name;

Key Points

  • A PostgreSQL Deployment is created with a single replica and resource requests/limits.
  • A Horizontal Pod Autoscaler (HPA) is configured to scale the PostgreSQL Deployment based on CPU utilization.
  • The HPA adjusts the number of replicas between 1 and 5 to maintain an average CPU utilization of 70%.

Summary

In this guide, we set up a Kubernetes Deployment for PostgreSQL and configured a Horizontal Pod Autoscaler to automatically scale the number of PostgreSQL instances based on CPU utilization metrics. This ensures that the PostgreSQL service can handle varying loads efficiently.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up