Nov 20, 20268 min read

How to Migrate Neon Postgres to Google Cloud SQL

Move a Neon database into Cloud SQL for PostgreSQL in your own GCP project: dump over the direct connection, strip Neon roles, Neon Auth references and Neon-only extensions, restore through a private connection, and choose between a write freeze and logical replication for the cutover.

Illustration for How to Migrate Neon Postgres to Google Cloud SQL

Neon is standard Postgres, so the data moves with pg_dump and pg_restore. The work is in the parts that only exist on Neon: the pooled connection string, roles like neon_superuser, Neon Auth's neon_auth schema and RLS policies that call auth.user_id().

This guide moves the database into Cloud SQL for PostgreSQL in your own GCP project, next to the Cloud Run or GKE services that use it, with Encore or by hand.

Ways to Move Neon Postgres to Cloud SQL at a Glance

Encore in your GCP projectCloud SQL by hand
Who creates Cloud SQLEncore, on the first deploy, or an imported instanceYou, with Terraform, gcloud or the console
NetworkPrivate network per environmentPrivate IP or public IP with authorized networks, your choice
Reaching the databaseencore db conn-uriCloud SQL Auth Proxy
Schema afterwardsBootstrap migration, then files in the repoYour migration tool
Access checksAuth handler plus owner filters in queriesYour API code, or rewritten RLS policies
CutoverDump and restore with a write freezeDump and restore, or logical replication into the instance

What Depends on Neon?

Run every command below over the direct connection string, the hostname without -pooler. Neon's pooled endpoint runs PgBouncer in transaction mode, and Neon's pooling docs recommend the direct connection for dumps, restores and migrations. Then list what will not move as-is:

-- Extensions: compare with the Cloud SQL list for your version SELECT extname, extversion FROM pg_extension; -- Row Level Security policies that rely on Neon's Data API SELECT tablename, policyname, qual FROM pg_policies WHERE schemaname = 'public'; -- Foreign keys into Neon-managed schemas SELECT conrelid::regclass AS from_table, confrelid::regclass AS to_table FROM pg_constraint WHERE contype = 'f' AND confrelid::regclass::text ~ '^(neon_auth|auth)\.';

Check the results against the Cloud SQL extension list: pgvector, pg_trgm and pgcrypto are supported, while pg_session_jwt, neon and neon_utils are Neon-specific. Cloud SQL also has no superuser. The closest role is cloudsqlsuperuser, so dumps need --no-owner --no-acl to drop the neon_superuser grants.

Neon Auth users need a users table of your own for foreign keys to point at. RLS policies on auth.user_id() either move into queries or get rewritten to read a setting your backend sets per transaction. Branches do not move: only the branch you dump does, and other environments start from migrations.

How Do You Migrate Neon to Cloud SQL with Encore?

Encore

Encore brings infrastructure from code to your GCP project: the database is declared in the service that uses it, and deploying to a GCP environment creates Cloud SQL in a private network. According to the GCP infrastructure docs, instances run the latest PostgreSQL version with automated daily backups kept for 7 days and point-in-time recovery. If you already created a Cloud SQL instance, you can import it into an environment instead.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

Turn the cleaned Neon schema into the bootstrap migration:

~/projects-app
$ mkdir -p projects/migrations$ pg_dump --schema-only --schema=public --no-owner --no-acl "$NEON_DIRECT_URL" > projects/migrations/1_bootstrap.up.sql

Edit the file to remove ENABLE ROW LEVEL SECURITY, the CREATE POLICY statements, Neon-only CREATE EXTENSION lines and foreign keys into neon_auth. For an app with projects and API tokens, the result looks like this:

-- projects/migrations/1_bootstrap.up.sql -- From pg_dump --schema-only, with RLS policies and pg_session_jwt removed. CREATE TABLE users ( id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE api_tokens ( token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE ); CREATE TABLE projects ( id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, owner_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE, name TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX projects_owner_idx ON projects (owner_id, created_at DESC);

Declare the service:

// projects/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("projects");

The database declaration and the auth handler replace the Data API's JWT check:

// projects/auth.ts import { APIError, Gateway, Header } from "encore.dev/api"; import { authHandler } from "encore.dev/auth"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { createHash } from "node:crypto"; // Cloud SQL in your GCP project, local Postgres with encore run. export const db = new SQLDatabase("projects", { migrations: "./migrations" }); interface AuthParams { authorization: Header<"Authorization">; } interface AuthData { userID: string; } export const auth = authHandler<AuthParams, AuthData>(async (params) => { const token = params.authorization.replace(/^Bearer /, ""); const hash = createHash("sha256").update(token).digest("hex"); const row = await db.queryRow<{ user_id: string }>` SELECT user_id FROM api_tokens WHERE token_hash = ${hash}`; if (!row) { throw APIError.unauthenticated("invalid token"); } return { userID: row.user_id }; }); export const gateway = new Gateway({ authHandler: auth });

The owner check that lived in an RLS policy becomes a filter in the query:

// projects/projects.ts import { api } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; import { db } from "./auth"; interface Project { id: number; name: string; createdAt: Date; } export const list = api( { expose: true, auth: true, method: "GET", path: "/projects" }, async (): Promise<{ projects: Project[] }> => { const userID = getAuthData()!.userID; const projects = await db.queryAll<Project>` SELECT id, name, created_at AS "createdAt" FROM projects WHERE owner_id = ${userID} ORDER BY created_at DESC LIMIT 100`; return { projects }; }, );

encore run starts Postgres locally and applies the bootstrap migration, which catches a leftover neon_auth reference before anything reaches GCP. A coding agent extending the service later adds 2_add_archived.up.sql, tests it against the local database, and the next deploy applies the same file to Cloud SQL.

Deploy and load the data

Connect your GCP account, create an environment on GCP with Cloud SQL as the database and push. Once the schema is applied, freeze writes on Neon, then load users first and the rest after:

~/projects-app
$ git push encore$ pg_dump --data-only --schema=public --format=custom -f data.dump "$NEON_DIRECT_URL"$ export CLOUDSQL_URL="$(encore db conn-uri projects --env=prod --admin)"$ pg_restore --data-only --no-owner --no-acl --single-transaction -d "$CLOUDSQL_URL" data.dump$ psql "$CLOUDSQL_URL" -c "ANALYZE;"

A data-only dump includes setval calls, so identity columns continue from the right value. Compare count(*) and max(created_at) on the main tables, then switch traffic to the Encore deployment.

Best fit: teams moving a Neon database into their own GCP project who want Cloud SQL and its private network created from the backend code, and access checks they can test locally.

Cloud SQL by Hand

Create the instance with private IP in your VPC, a database and an app user, then connect from your machine with the Cloud SQL Auth Proxy and apply the cleaned schema and data:

~
$ gcloud sql instances create app-db --database-version=POSTGRES_17 \ --tier=db-custom-2-7680 --region=europe-west1 --network=default --no-assign-ip$ gcloud sql databases create app --instance=app-db$ cloud-sql-proxy --private-ip --port 5433 my-project:europe-west1:app-db &$ psql "host=127.0.0.1 port=5433 user=postgres dbname=app" -f schema-cleaned.sql$ pg_restore --data-only --no-owner --no-acl -h 127.0.0.1 -p 5433 -U postgres -d app data.dump

The --private-ip flag only works from a machine that can reach the VPC, so run the proxy on a VM in the network or through a VPN. After the load you still own the rest: a least-privilege role for the app, the password in Secret Manager or IAM database authentication, and a way to apply the next migration in every environment.

Best fit: teams with an existing Cloud SQL layout in Terraform, or databases that keep RLS and need roles designed by hand.

How Do You Cut Over with Logical Replication?

For a database too large for a short write freeze, replicate first. Enabling logical replication on the Neon project permanently sets wal_level to logical and restarts its computes, and Neon's logical replication guide notes that inactive slots are removed after about 40 hours. With the schema applied on Cloud SQL, publish on Neon and subscribe from Cloud SQL:

-- On Neon, over the direct connection CREATE PUBLICATION to_cloudsql FOR TABLES IN SCHEMA public; -- On Cloud SQL, as a user with the REPLICATION attribute CREATE SUBSCRIPTION from_neon CONNECTION 'host=ep-cool-darkness-123456.europe-west2.aws.neon.tech dbname=app user=app_owner password=... sslmode=require' PUBLICATION to_cloudsql;

The subscriber connects out to Neon, so the instance needs a route to the internet, and Google's logical replication docs note that a high-availability instance cannot be a subscriber because its outgoing IP address can change. That makes this path a fit for an instance you create and configure yourself, which you can later import into Encore. Sequences are not replicated, so after writes to Neon stop and the subscriber catches up, move each one past its column's maximum:

SELECT setval(pg_get_serial_sequence('projects', 'id'), (SELECT COALESCE(max(id), 1) FROM projects));

Then drop the subscription on Cloud SQL and the publication on Neon, and keep the Neon project for a few days so a rollback only means pointing the app back at it.

How to Choose

Pick Encore when the backend is moving to your own GCP project and you want Cloud SQL, its network and the schema history created from the service code, with Neon Auth and Data API pieces replaced by code you can run locally. Pick Cloud SQL by hand when an infrastructure team owns the database layout or you need logical replication into a specific instance. For small databases a dump and restore with a short write freeze is simplest either way.

Frequently asked questions

How do I migrate from Neon to Cloud SQL?

Dump the schema with pg_dump --schema-only --no-owner --no-acl over Neon's direct connection string, remove Neon Auth references, RLS policies on auth.user_id() and Neon-only extensions, and apply it to Cloud SQL. Then load the data with a data-only dump and pg_restore, run ANALYZE, compare row counts and point the app at Cloud SQL.

Can Cloud SQL subscribe to a Neon publication?

Yes, Cloud SQL supports native logical replication as a subscriber, with a user that has the REPLICATION attribute. The subscriber connects out to Neon, so the instance needs an outgoing route to Neon's endpoint, and Google's docs note that a high-availability instance cannot be a subscriber because its outgoing IP address can change.

Do Neon extensions work on Cloud SQL?

Yes. Standard ones do. pgvector, pg_trgm and pgcrypto are available on Cloud SQL, while Neon's own neon and neon_utils extensions and pg_session_jwt, which backs the Data API's auth.user_id(), have no Cloud SQL equivalent and must be removed from the schema.

Does Encore support both Neon and Cloud SQL?

Yes. An Encore environment on GCP can use a Cloud SQL instance Encore provisions, an existing Cloud SQL instance you import, or a Neon project, and the database is declared the same way in code. Moving to Cloud SQL means creating a GCP environment with Cloud SQL and loading the data into it.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders