Back to Blog
infrastructureGCPSupabaseAuto-scalingDockerInfrastructure

Auto-Scaling Supabase Studio on GCP with Managed Instance Groups

How we deploy Supabase Studio on GCP with auto-scaling, auto-healing, and zero-downtime updates using Managed Instance Groups and Container-Optimized OS.

Auto-Scaling Supabase Studio on GCP with Managed Instance Groups

In previous posts, we covered the database, networking, and security layers of our self-hosted Supabase setup. This post covers the application layer: how we deploy and scale Supabase Studio.

Our goals:

  • Auto-scaling: handle traffic spikes without manual intervention
  • Auto-healing: replace unhealthy instances automatically
  • Zero-downtime updates: deploy new versions without interruption
  • Cost efficiency: scale down when traffic is low

What is Supabase Studio?

Supabase Studio is the web-based admin interface for managing your Supabase/PostgreSQL database. It includes:

  • SQL Editor: run queries directly
  • Table Editor: visual database management
  • API Documentation: auto-generated from your schema
  • Auth Management: user administration

It's open source and runs as a Docker container, which makes it a good fit for self-hosting. Here it runs with postgres-meta alone, so the SQL editor, table editor and other database pages work. The API docs and Auth pages call Supabase's API gateway, PostgREST and Auth, which this setup doesn't run.

The architecture

Supabase Studio on a regional instance group
Global Load Balancer(SSL Termination)Regional Instance GroupZone AVMStudioZone BVMStudioCloud SQL (Private IP)

Instance Template

The foundation of auto-scaling is the instance template. It defines what each VM looks like:

this.instanceTemplate = new gcp.compute.InstanceTemplate(
  `${resourceName}-template`,
  {
    namePrefix: `${resourceName}-template-`,
    machineType: machineType,
    region: region,
    tags: ["supabase-studio", "allow-ssh"],
 
    disks: [
      {
        sourceImage: "projects/cos-cloud/global/images/family/cos-stable",
        autoDelete: true,
        boot: true,
        diskSizeGb: 50,
        diskType: "hyperdisk-balanced",
      },
    ],
 
    networkInterfaces: [
      {
        network: args.networking.vpc.id,
        subnetwork: args.networking.subnet.id,
        // No external IP - instances are private
      },
    ],
 
    serviceAccount: {
      email: this.serviceAccount.email,
      scopes: ["cloud-platform"],
    },
 
    // The startup script and its settings. Secrets go in as Secret Manager
    // version names only; the VM reads the values at boot.
    metadata: {
      "google-logging-enabled": "true",
      "google-monitoring-enabled": "true",
      "startup-script": startupScript, // common.sh followed by the script below
      "studio-image": "supabase/studio:2026.10.12-sha-3699278",
      "pg-meta-image": "supabase/postgres-meta:v0.100.0",
      "proxy-image": "nginx:1.30.6-alpine",
      "proxy-port": "8000",
      "db-host": args.database.privateIp,
      "db-port": "5432",
      "db-name": args.database.database.name,
      "db-user": args.database.user.name,
      "studio-organization-name": "Acme Corp",
      "studio-project-name": "Production",
      "db-password-secret": dbPasswordVersion.name,
      "pg-meta-crypto-key-secret": cryptoKeyVersion.name,
      "studio-htpasswd-secret": htpasswdVersion.name,
    },
 
    shieldedInstanceConfig: {
      enableSecureBoot: true,
      enableVtpm: true,
      enableIntegrityMonitoring: true,
    },
  },
  {
    parent: this,
    dependsOn: [args.database.instance, args.database.database, args.database.user],
  },
);

Key decisions

  • Container-Optimized OS: We use cos-stable (Container-Optimized OS). It's:
    • Minimal and secure
    • Optimized for running Docker
    • Auto-updates the OS
    • Maintained by Google
  • No external IP: Instances don't have public IPs. They access the internet through Cloud NAT (for pulling Docker images) and are accessed through the load balancer.
  • Hyperdisk Balanced: For the boot disk, we use hyperdisk-balanced. It offers better IOPS than standard persistent disk, which helps with container startup times. It's also the only choice for the C4D machines we use (below): C4D doesn't support Persistent Disk, only Hyperdisk.
  • Dependencies: The template depends on the database being ready. No point starting Studio if it can't connect to PostgreSQL.

The startup script

When a VM boots, it runs this script to configure and start Supabase Studio. It's the one in our open-source template. It holds no values of its own: settings come from the instance's metadata and secrets from Secret Manager, through four small helpers (attr, read_secret, retry and wait_for_docker) in the template's common.sh, which runs first.

readonly APP_DIR=/var/lib/supabase-studio
readonly DOCKER_NETWORK=supabase
 
STUDIO_IMAGE="$(attr studio-image)"
PG_META_IMAGE="$(attr pg-meta-image)"
PROXY_IMAGE="$(attr proxy-image)"
PROXY_PORT="$(attr proxy-port)"
DB_HOST="$(attr db-host)"
DB_PORT="$(attr db-port)"
DB_NAME="$(attr db-name)"
DB_USER="$(attr db-user)"
ORGANIZATION_NAME="$(attr studio-organization-name)"
PROJECT_NAME="$(attr studio-project-name)"
 
DB_PASSWORD="$(read_secret "$(attr db-password-secret)")"
PG_META_CRYPTO_KEY="$(read_secret "$(attr pg-meta-crypto-key-secret)")"
HTPASSWD="$(read_secret "$(attr studio-htpasswd-secret)")"
 
umask 077
mkdir -p "${APP_DIR}/snippets"
 
# Docker reads env files when it creates a container, so the values are
# never on a command line.
#
# PGSSLMODE: Cloud SQL accepts only TLS connections. Studio's connection
# string carries no SSL settings, so postgres-meta falls back to PGSSLMODE
# for every connection. no-verify encrypts without checking the certificate.
cat >"${APP_DIR}/pg-meta.env" <<EOF
PG_META_PORT=8080
PGSSLMODE=no-verify
PG_META_DB_HOST=${DB_HOST}
PG_META_DB_PORT=${DB_PORT}
PG_META_DB_NAME=${DB_NAME}
PG_META_DB_USER=${DB_USER}
PG_META_DB_PASSWORD=${DB_PASSWORD}
CRYPTO_KEY=${PG_META_CRYPTO_KEY}
EOF
 
# Studio builds its own connection string from the POSTGRES_* values and
# sends it to postgres-meta, encrypted with the shared crypto key.
cat >"${APP_DIR}/studio.env" <<EOF
HOSTNAME=0.0.0.0
STUDIO_PG_META_URL=http://pg-meta:8080
POSTGRES_HOST=${DB_HOST}
POSTGRES_PORT=${DB_PORT}
POSTGRES_DB=${DB_NAME}
POSTGRES_PASSWORD=${DB_PASSWORD}
POSTGRES_USER_READ_WRITE=${DB_USER}
PG_META_CRYPTO_KEY=${PG_META_CRYPTO_KEY}
DEFAULT_ORGANIZATION_NAME=${ORGANIZATION_NAME}
DEFAULT_PROJECT_NAME=${PROJECT_NAME}
SNIPPETS_MANAGEMENT_FOLDER=/app/snippets
ENABLED_FEATURES_LOGS_ALL=false
NEXT_TELEMETRY_DISABLED=1
EOF
 
printf '%s\n' "${HTPASSWD}" >"${APP_DIR}/htpasswd"
# 101 is the nginx user in the official image; its workers read this file.
chown 101:101 "${APP_DIR}/htpasswd"
chmod 0400 "${APP_DIR}/htpasswd"
 
cat >"${APP_DIR}/nginx.conf" <<'EOF'
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
 
server {
    listen 8000;
    server_tokens off;
    client_max_body_size 50m;
 
    # Docker's DNS, re-resolved so a recreated studio container is found.
    resolver 127.0.0.11 valid=10s ipv6=off;
    set $studio http://studio:3000;
 
    # The health check: this exact path, without credentials.
    location = /healthz {
        access_log off;
        proxy_pass $studio/api/platform/profile;
    }
 
    location / {
        auth_basic "Supabase Studio";
        auth_basic_user_file /etc/nginx/htpasswd;
 
        proxy_pass $studio;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        # Studio doesn't need the basic-auth credentials.
        proxy_set_header Authorization "";
        proxy_read_timeout 120s;
        proxy_send_timeout 120s;
    }
}
EOF
chmod 0444 "${APP_DIR}/nginx.conf"
 
wait_for_docker
docker network inspect "${DOCKER_NETWORK}" >/dev/null 2>&1 ||
  docker network create "${DOCKER_NETWORK}" >/dev/null
 
for image in "${PG_META_IMAGE}" "${STUDIO_IMAGE}" "${PROXY_IMAGE}"; do
  retry docker pull --quiet "${image}" >/dev/null
done
 
# Recreate the containers on every boot so they pick up changed settings.
docker rm -f studio-proxy studio pg-meta >/dev/null 2>&1 || true
 
LOG_OPTS=(--log-opt max-size=10m --log-opt max-file=3)
 
docker run -d --name pg-meta --network "${DOCKER_NETWORK}" --restart always \
  "${LOG_OPTS[@]}" \
  --env-file "${APP_DIR}/pg-meta.env" \
  "${PG_META_IMAGE}" >/dev/null
 
docker run -d --name studio --network "${DOCKER_NETWORK}" --restart always \
  "${LOG_OPTS[@]}" \
  --env-file "${APP_DIR}/studio.env" \
  --mount "type=bind,source=${APP_DIR}/snippets,target=/app/snippets" \
  "${STUDIO_IMAGE}" >/dev/null
 
docker run -d --name studio-proxy --network "${DOCKER_NETWORK}" --restart always \
  "${LOG_OPTS[@]}" \
  -p "${PROXY_PORT}:8000" \
  --mount "type=bind,source=${APP_DIR}/nginx.conf,target=/etc/nginx/conf.d/default.conf,readonly" \
  --mount "type=bind,source=${APP_DIR}/htpasswd,target=/etc/nginx/htpasswd,readonly" \
  "${PROXY_IMAGE}" >/dev/null

Nothing waits for postgres-meta before Studio starts. Studio only calls it when someone opens a page, and the health check below decides when the VM gets traffic.

The connection from postgres-meta to Cloud SQL is encrypted, and Cloud SQL refuses any that isn't: the template's database sets sslMode: "ENCRYPTED_ONLY". postgres-meta doesn't check the server's certificate, though. The certificate names only the instance's <id>.<region>.sql.goog DNS name, postgres-meta connects to the private IP, and pointing it at the server CA breaks Studio with ERR_TLS_CERT_ALTNAME_INVALID.

Settings and secrets

The instance template above hands the script everything it needs as metadata. The image tags are the ones in Supabase's self-hosted release 0.8.3. Take Studio and postgres-meta from the same release, so Studio runs with the postgres-meta version it shipped with. The environment variables follow that release's Docker Compose file for the same two containers. What's left out is for parts we don't run (the API gateway, Auth, PostgREST, Edge Functions and the AI assistant), and NEXT_TELEMETRY_DISABLED turns off Next.js telemetry.

For secrets, the metadata only holds the name of a Secret Manager version. Each secret is created by Pulumi, and the VMs' service account can read those three secrets and no others:

const dbPasswordSecret = new gcp.secretmanager.Secret(
  `${resourceName}-db-password`,
  {
    secretId: `${resourceName}-db-password`,
    replication: { auto: {} },
  },
  { parent: this },
);
 
const dbPasswordVersion = new gcp.secretmanager.SecretVersion(
  `${resourceName}-db-password`,
  {
    secret: dbPasswordSecret.id,
    secretData: args.secrets.apply(s => s.infra.postgresPassword),
  },
  { parent: this },
);
 
new gcp.secretmanager.SecretIamMember(
  `${resourceName}-db-password-access`,
  {
    secretId: dbPasswordSecret.id,
    role: "roles/secretmanager.secretAccessor",
    member: pulumi.interpolate`serviceAccount:${this.serviceAccount.email}`,
  },
  { parent: this },
);
 
// cryptoKeyVersion and htpasswdVersion are made the same way.

The crypto key is a random string that Studio and postgres-meta share: Studio encrypts the connection string it sends with it, and postgres-meta decrypts it. The htpasswd secret holds a salted hash of the Studio password, not the password itself.

Anyone who can view the instance template now sees secret names, not values. The values still end up on each VM, in the env files under /var/lib/supabase-studio and in the containers' configuration, where root can read them. And because a new secret version or image tag changes the metadata, it changes the instance template too, so pulumi up rolls out new VMs that read it.

Studio also has no login of its own when you self-host it, and its API runs SQL as the database user. So it gets two locks. The network decides who reaches it: only traffic from our VPN gets past Cloud Armor, as described in the VPN post. And nginx asks for a password before anything reaches Studio.

Three containers

Each VM runs three containers:

  1. pg-meta: postgres-meta, the API Studio uses to read and change the database. It has no authentication, so it publishes no port.
  2. studio: the actual Supabase Studio web UI, also unpublished
  3. studio-proxy: nginx with basic auth, the only container with a published port (8000)

They communicate over a private Docker network.

The proxy's basic auth is one login that everyone shares. If anyone uses Studio on production health data, read the Studio login problem in our Supabase HIPAA guide first.

Health checks

Each VM gets two health checks on the same path. The load balancer's is fast, so traffic moves off a failing VM within about 30 seconds:

this.healthCheck = new gcp.compute.HealthCheck(
  `${resourceName}-health-check`,
  {
    name: `${resourceName}-health-check`,
    checkIntervalSec: 10,
    timeoutSec: 5,
    healthyThreshold: 2,
    unhealthyThreshold: 3,
    httpHealthCheck: {
      port: 8000,
      requestPath: "/healthz",
    },
  },
  { parent: this },
);

Auto-healing gets its own, slower check. A rebooted Studio VM takes about a minute to answer again, and with the load balancer's 30 seconds, the instance group deletes and recreates it instead of waiting. In our test deploy on November 5, 2026, that took 4 minutes 29 seconds with one VM, and the VM's saved SQL snippets went with its disk. With the slower check, the same reset recovered in 59 seconds:

this.autohealingHealthCheck = new gcp.compute.HealthCheck(
  `${resourceName}-autohealing-hc`,
  {
    name: `${resourceName}-autohealing-hc`,
    checkIntervalSec: 20,
    timeoutSec: 5,
    healthyThreshold: 2,
    unhealthyThreshold: 6,
    httpHealthCheck: {
      port: 8000,
      requestPath: "/healthz",
    },
  },
  { parent: this },
);

Configuration explained

SettingLoad balancerAuto-healingMeaning
checkIntervalSec1020Seconds between checks
timeoutSec55Seconds a check waits for an answer
healthyThreshold22Successes in a row to count as healthy
unhealthyThreshold36Failures in a row to count as unhealthy

So the load balancer stops sending traffic to a VM after 30 seconds of failures, and auto-healing repairs it after 2 minutes. Google's API allows at most 10 failures in a row, so a longer wait means checking less often.

The health endpoint

We hit /healthz on port 8000. nginx answers that one path without asking for a password and passes it to Studio's /api/platform/profile. In self-hosted Studio, that endpoint returns a fixed profile without querying the database, so a 200 means nginx and the Studio server are up and answering. It's a liveness check, not a database check.

That's the right job for auto-healing. An instance whose Studio process has hung gets replaced, while a database outage, which new VMs wouldn't fix, doesn't set off a wave of replacements. Watch the database separately, with Cloud SQL's own monitoring and alerts.

The firewall rule

Health check probes don't come through the load balancer. Google sends them straight to each VM's internal IP from 35.191.0.0/16, and the load balancer's own requests reach the VMs from 130.211.0.0/22 and 35.191.0.0/16 (Google's firewall requirements). Without a VPC firewall rule that lets those ranges in, every VM fails its health check. This rule is the only way into the Studio VMs:

this.firewall = new gcp.compute.Firewall(
  `${resourceName}-allow-lb`,
  {
    name: `${resourceName}-allow-lb`,
    network: args.networking.vpc.id,
    direction: "INGRESS",
    allows: [{ protocol: "tcp", ports: ["8000"] }],
    sourceRanges: ["35.191.0.0/16", "130.211.0.0/22"],
    targetTags: ["supabase-studio"],
  },
  { parent: this },
);

Cloud Armor plays no part in this. It filters requests at the load balancer, so it never sees the probes.

Managed Instance Group

The instance group manages the VMs:

this.instanceGroupManager = new gcp.compute.RegionInstanceGroupManager(
  `${resourceName}-mig`,
  {
    name: `${resourceName}-mig`,
    region: region,
    baseInstanceName: resourceName,
    distributionPolicyZones: [`${region}-a`, `${region}-b`],
 
    versions: [{ instanceTemplate: this.instanceTemplate.selfLinkUnique }],
 
    namedPorts: [{ name: "http", port: 8000 }],
 
    autoHealingPolicies: {
      healthCheck: this.autohealingHealthCheck.id,
      initialDelaySec: 300,
    },
 
    updatePolicy: {
      type: "PROACTIVE",
      minimalAction: "REPLACE",
      maxSurgeFixed: 2,
      maxUnavailableFixed: 0,
      replacementMethod: "SUBSTITUTE",
    },
  },
  { parent: this },
);

There's no targetSize. The autoscaler below owns the number of instances, and the Google provider's docs say to leave targetSize unset when an autoscaler is attached; otherwise every deploy resets the group to that size.

Regional distribution

We spread instances across two zones (region-a and region-b). If one zone has issues, the other keeps serving traffic.

Auto-healing

The autoHealingPolicies configuration:

  • Uses the slower auto-healing check, so a VM that's only rebooting isn't replaced
  • initialDelaySec: 300: wait 5 minutes before checking (startup takes time)
  • A VM that fails it for 2 minutes is recreated from the instance template

Update policy

The updatePolicy controls how new versions roll out:

SettingValueEffect
typePROACTIVEApply updates immediately
minimalActionREPLACECreate new instances (don't just restart)
maxSurgeFixed2Create up to 2 extra instances during update
maxUnavailableFixed0Never have fewer than target instances
replacementMethodSUBSTITUTEDelete old, create new (vs. recreate in-place)

This gives us zero-downtime deployments:

  1. New instances are created with the new template
  2. Once healthy, traffic shifts to them
  3. Old instances are terminated

Autoscaler

The autoscaler adjusts instance count based on load:

this.autoscaler = new gcp.compute.RegionAutoscaler(
  `${resourceName}-autoscaler`,
  {
    name: `${resourceName}-autoscaler`,
    region: region,
    target: this.instanceGroupManager.id,
    autoscalingPolicy: {
      minReplicas: minInstances,
      maxReplicas: maxInstances,
      cooldownPeriod: 60,
      cpuUtilization: { target: 0.7 },
    },
  },
  { parent: this },
);

Scaling policy

  • minReplicas: never go below this (1 for dev, 2 for prod)
  • maxReplicas: never exceed this (keeps costs bounded)
  • cooldownPeriod: give a new VM 60 seconds to start up before its CPU counts toward scaling out (Google now calls this the initialization period)
  • cpuUtilization.target: scale up when average CPU exceeds 70%

Environment differences

SettingDevProd
minReplicas12
maxReplicas12

For dev, we fix at 1 instance (cost savings). For prod, we ensure at least 2 for high availability.

Backend service

The backend service connects the load balancer to the instance group:

this.backendService = new gcp.compute.BackendService(
  `${resourceName}-backend`,
  {
    name: `${resourceName}-backend`,
    protocol: "HTTP",
    portName: "http",
    timeoutSec: 30,
    healthChecks: this.healthCheck.id,
    securityPolicy: securityPolicy?.selfLink,
    backends: [
      {
        group: this.instanceGroupManager.instanceGroup,
        balancingMode: "UTILIZATION",
        capacityScaler: 1.0,
      },
    ],
    logConfig: { enable: true, sampleRate: 1.0 },
  },
  { parent: this },
);
  • Timeouts: timeoutSec: 30 is how long the load balancer waits for an instance to answer a request before it gives up. It isn't connection draining. Draining, where Google waits for in-flight requests to finish before an instance is removed, is a separate setting: connectionDrainingTimeoutSec.
  • Logging: logConfig: { enable: true, sampleRate: 1.0 } logs every request. In production, you might reduce sampleRate to save on logging costs.

Load balancer

We covered the load balancer in detail in the infrastructure post. Key points:

  • Global IP: single static IP for DNS
  • SSL termination: Google-managed certificate
  • HTTP to HTTPS redirect: all traffic forced to HTTPS
this.loadBalancer = new LoadBalancer(
  `${resourceName}-lb`,
  {
    name: resourceName,
    domain: args.domain,
    backendService: this.backendService,
  },
  { parent: this },
);

Putting it all together

The complete service component:

const supabaseStudio = new SupabaseStudioService("supabase-studio", {
  name: "supabase-studio",
  projectId: config.projectId,
  region: config.region,
  domain: `db.${config.environment}.example.com`,
  networking: networking,
  database: database,
  secrets: secrets,
  machineType: "c4d-standard-2",
  minInstances: config.environment === "prod" ? 2 : 1,
  maxInstances: config.environment === "prod" ? 2 : 1,
  vpnPublicIp: vpn?.publicIp,
});

Machine type

We use c4d-standard-2:

  • 2 vCPUs
  • 7 GB RAM
  • General-purpose (C4D series)

This is plenty for Supabase Studio. The containers are lightweight.

Deployment workflow

When we run pulumi up:

  1. Template changes? If the startup script or machine config changed, a new template is created
  2. Rolling update: new instances are created with the new template
  3. Health check passes: traffic shifts to new instances
  4. Old instances terminated: previous version instances are deleted

The whole process takes 5-10 minutes and requires no manual intervention.

Monitoring

  • Built-in metrics: With google-monitoring-enabled: true, we get:
    • CPU utilization
    • Memory usage
    • Disk I/O
    • Network traffic
  • Custom health checks: For deeper monitoring, we could add:
    • Database connection latency
    • Container startup time
    • API response times
  • Logging: Container logs go to Cloud Logging via google-logging-enabled: true. We can:
    • Search and filter logs
    • Set up alerts on error patterns
    • Export to BigQuery for analysis

Common issues and fixes

  1. Startup too slow. If instances take too long to start, they might fail health checks during boot. Solutions:
    • Increase initialDelaySec in auto-healing policy
    • Optimize Docker image pulls (use regional mirrors)
    • Pre-pull images in a base image
  2. Memory pressure. If instances run out of memory:
    • Increase machine type
    • Add swap (not ideal but works)
    • Optimize container memory limits
  3. Database connection pool exhaustion. Each Studio instance opens connections to the database. With many instances:
    • Monitor max_connections in PostgreSQL
    • Consider connection pooling (PgBouncer)
    • Limit concurrent Studio instances
  4. Slow health check response. If the health endpoint is slow:
    • Check the VM's CPU and memory (the endpoint doesn't touch the database)
    • Increase health check timeout
    • Optimize the health endpoint

Cost optimization

These tips cut the cost of the Studio instances. To compare the whole self-hosted bill with Supabase Cloud for your own usage, use our Supabase pricing calculator.

  • Right-size instances: Start small. Monitor CPU and memory. Scale up only if needed.
  • Use committed use discounts: For predictable workloads, committed use discounts save 20-50%.
  • Preemptible/Spot instances: For dev environments, preemptible instances cost 60-80% less. They can be terminated with 30 seconds notice, but for non-production, that's usually fine.

What's next

In the final post of this series, we cover how we run PostgreSQL in three writable regions, bringing the database closer to users around the world.


Want Supabase Studio and the rest of your stack running in your own Google Cloud project? We set up and run self-hosted Supabase for teams that need control over their data.

Sachin Mour
Founder of Pulore, ex-CTO at Hexis
Share:

Want Supabase on your own cloud?

We set up and run self-hosted Supabase on Google Cloud for teams that need control over their data: private networking, managed PostgreSQL, backups and monitoring, all defined as code. A new setup is a two-week, fixed-price project from $8,000.