Migrate from CockroachDB to PostgreSQL

A planning guide for moving a CockroachDB workload to a self-hosted, single-primary PostgreSQL cluster, covering what moves cleanly, what needs rework, and how to cut over safely.

On this page

Migrate from CockroachDB to PostgreSQL: what the move involves

The move is feasible when your write volume fits one primary node. If a renewal, a change to the CockroachDB Software License or a data residency requirement is pushing you off CockroachDB, the first question is not which database to adopt but whether your workload needs distributed writes at all. Many clusters are sized for resilience and convenience rather than for write throughput that a single PostgreSQL primary cannot handle. Confirm your peak sustained write rate, transaction size and growth trend from your own monitoring before you commit to a target design, because that number decides whether a single-primary cluster is enough. The work is usually shared by the platform team, a DBA who owns the PostgreSQL side, and the application teams who own the SQL and retry logic, often with an implementation partner supplying cluster build, replication and cutover testing. Expect the effort and risk to depend on how much CockroachDB-specific SQL, types and functions your schema uses, and on whether your application already retries transactions that fail with serialization errors. Those factors vary widely between systems, so ask for an assessment of your actual schema and code paths rather than relying on a general duration.

The practical work falls into four areas. First, export and schema translation: you will move tables, indexes, constraints and data, then review sequences, since CockroachDB unique IDs and PostgreSQL sequences behave differently under concurrency, and replace any CockroachDB-only types or statements. Second, transaction behavior: CockroachDB can ask clients to retry transactions on contention, and your application must handle the equivalent conditions in PostgreSQL, where isolation level choices and lock waits change what the application sees. Third, high availability: PostgreSQL does not detect a failed primary or promote a standby by itself, so you must choose an external tool such as Patroni on your own servers or CloudNativePG on Kubernetes, and decide between synchronous and asynchronous replication based on how much data loss you accept. Fourth, authentication and backup, which you should review against your security baseline. Each area produces decisions that your security and compliance teams should sign off, and each is a recurring operational responsibility once live.

Which CockroachDB features map cleanly to PostgreSQL

This table compares the main CockroachDB capabilities with what a single-primary PostgreSQL cluster provides, marking each as clean, needs rework or gap. Read the status column as a planning signal: rework items need application or schema changes, and gaps mean the workload may not fit one primary.

CapabilityCockroachDBPostgreSQLStatus
Standard SQL and schema objectsLargely PostgreSQL-compatible SQL with CockroachDB-specific types, functions and index optionsFull SQL with tables, constraints, views, functions and extensions; translate CockroachDB-specific syntaxNeeds rework
Sequences and unique IDsUnique IDs often generated with UUIDs or unordered keys to avoid write hotspotsSequences and identity columns work on one primary; UUIDv7 is available from PostgreSQL 18Needs rework
Serializable transactionsSerializable by default, with client retries expected on contention errorsSerializable isolation is available per transaction; applications must still retry serialization failuresNeeds rework
Automatic sharding and range rebalancingRanges split and rebalance across nodes without manual interventionNo automatic sharding; data is partitioned manually or the write load is kept within one primaryGap
Multi-region write placementData can be pinned to regions and written across regionsWrites go to one primary; standbys in other regions serve reads onlyGap
Replication and failoverReplication across nodes with automatic leaseholder recoveryHot standbys with synchronous or asynchronous replication; automatic failover needs Patroni or CloudNativePGNeeds rework
Backup and point-in-time recoveryBuilt-in backup to cloud storage with scheduled jobsContinuous archiving and point-in-time recovery through external tools such as pgBackRest or pg_basebackup with WAL archivingNeeds rework

Data, roles and integrations to move and rebuild

Moving the tables is the visible part of a CockroachDB exit. The objects around them, including roles, authentication, the connection layer and every process that reads changes or runs on a schedule, must be rebuilt or re-pointed before cutover. Confirm each export, changefeed and grant option against the documentation for your exact CockroachDB version.

Logical dump and load

Export schemas and data from CockroachDB, then load them into PostgreSQL. Treat the export as a starting point, not a finished copy: CockroachDB-specific types, default expressions and index definitions often need manual translation before the load succeeds. Run a full load into a staging PostgreSQL instance, compare row counts and checksums per table, and record the exact export command and version so the rehearsal can be repeated before cutover. Confirm the export options in your CockroachDB version's documentation.

PostgreSQL upgrading docs

Users, roles and grants

CockroachDB roles, privileges and default privileges do not map one to one onto PostgreSQL. Inventory every user, role membership and grant on each database and schema, then recreate them in PostgreSQL with the least privilege the application needs. Check ownership of tables, sequences and functions, because objects owned by the wrong role will break migrations and later permission changes. Keep the mapping in version control so auditors can trace each grant.

Authentication methods

PostgreSQL supports password authentication with SCRAM, certificate authentication, and GSSAPI, SSPI, LDAP, RADIUS, PAM and OAuth, so the identity model can stay close to what your organization already runs. Set password_encryption to scram-sha-256 and avoid MD5 passwords, which PostgreSQL 18 has deprecated. Decide which applications use certificates and which use directory-backed logins, and write the rules in pg_hba.conf in order, because the first matching line applies.

PostgreSQL authentication methods

Connection pooling with PgBouncer

Applications that open many short connections need a pooler in front of PostgreSQL. PgBouncer can hold client connections and reuse a smaller set of server connections, which limits load on the primary during spikes. Choose the pool mode with care, since transaction pooling changes how session state, prepared statements and advisory locks behave. Test every application's connection string and driver settings against the pooler before cutover.

PgBouncer project

Change data capture consumers

Any service that consumes CockroachDB changefeeds must be found, tested and re-pointed. PostgreSQL offers logical replication and logical decoding, but the message formats, delivery guarantees and resume positions differ from CockroachDB changefeeds, so consumers may need new offset handling. Inventory each sink, such as a message broker, search index or warehouse loader, and confirm how it behaves after a restart or a gap in changes. Confirm the changefeed options in your own version's documentation before you design the replacement.

PostgreSQL replication docs

Scheduled jobs and external callers

Cron jobs, batch scripts, backup tasks, reporting queries and third-party integrations often connect to CockroachDB with their own credentials and connection strings. Each one must be listed, moved to PostgreSQL, and given a tested rollback path. Pay attention to jobs that depend on CockroachDB-specific functions, time zone behavior or job scheduling features, since these fail quietly if nobody checks them. Owners should sign off on each job before the old cluster is switched off.

The migration sequence from inventory to decommission

This sequence moves a CockroachDB workload to a single-primary PostgreSQL cluster in controlled stages, so each stage produces evidence that the next one can rely on. Every step ends with a named artifact that you review before the cutover decision is made.

  1. Inventory schemas, queries and write rates

    Your team, with the application owners, lists every database, schema, table, sequence, index and user-defined type, along with the queries each service runs and the sustained write rate per table during peak hours. Capture CockroachDB-specific features in the same pass: SERIAL defaults that use unique_rowid(), AS OF SYSTEM TIME reads, zone configurations, multi-region table localities, changefeeds and crdb_internal queries. The output is a written inventory that marks each item as portable, needs rewriting, or needs a design decision. Confirm the peak write figures from your own monitoring, because one primary has to absorb them.

  2. Build the target schema and diff it

    Create the PostgreSQL schema from the inventory, replacing CockroachDB-only constructs with PostgreSQL equivalents and documenting each change. Generate a schema diff between the CockroachDB export and the PostgreSQL target, covering column types, constraints, indexes, sequences and default expressions. The output is a reviewed schema diff signed off by the application owners, with a list of every intentional difference.

  3. Pilot the migration on a non-production copy

    Load a copy of production data into a non-production PostgreSQL instance and run the full export, import and sequence reset procedure end to end. Run the application's test suite and the highest-volume queries from the inventory against it, and record which transactions fail, which retry paths trigger and how long the import takes. Review the retry logic in the application, since serialization errors from CockroachDB and PostgreSQL behave differently under contention. The output is a pilot report listing defects found, fixes applied and a repeatable runbook.

  4. Run a parallel sync with replication or dual writes

    Start logical replication from the source into PostgreSQL where the data model allows it, or implement dual writes in the application where replication cannot capture the changes. Keep CockroachDB as the system of record while PostgreSQL catches up, and monitor replication lag and conflict errors continuously. Compare row counts and checksums per table at agreed intervals, and investigate any drift before continuing. The output is a validated row-count and checksum report that shows the two systems match for every table in scope.

  5. Stand up high availability and test failover

    Deploy the PostgreSQL primary with one or more standbys, and choose between synchronous and asynchronous replication based on how much data loss the business accepts. PostgreSQL does not detect primary failure on its own, so add an external tool such as Patroni or CloudNativePG and configure its health checks and fencing. Test planned switchover and an unplanned primary failure, and time the application reconnection path. The output is a tested failover runbook with the observed results recorded for each scenario.

  6. Cut over with a rollback plan

    Freeze writes on CockroachDB for the cutover window, let replication drain, run the final row-count and checksum comparison, reset sequences to values above the maximum in each table, and point the application to the PostgreSQL primary. Keep CockroachDB running in read-only mode and document the conditions that trigger a rollback, along with the reverse replication or write-back steps needed to recover writes made after cutover. The output is a signed cutover record with the verification results and an agreed rollback decision point.

  7. Decommission CockroachDB after the hold period

    After the agreed post-cutover observation period, take a final backup of the CockroachDB cluster for retention, remove its connection strings from applications and secrets stores, and shut down the nodes. Update monitoring, backup jobs, access reviews and licensing records so no system still expects the old cluster. The output is a decommission checklist with the retained backup location, the date of shutdown and confirmation that no service still connects to CockroachDB.

How the PostgreSQL side is built for high availability

A hot standby is PostgreSQL's built-in replica. It receives changes from the primary and can serve read-only queries while it waits to be promoted. You choose between synchronous replication, where a commit waits until one or more standbys confirm it, and asynchronous replication, where the primary does not wait. PostgreSQL does not include software that detects a failed primary and promotes a standby, so this model depends on your team to decide and carry out promotion.

  • Replication mode: Synchronous replication protects committed transactions from loss on failover but adds latency to every commit. Asynchronous replication is faster but can lose the most recent commits.
  • Read scaling: Hot standbys can serve read-only queries, which can offload reporting from the primary, but replica lag must be watched.
  • Manual promotion: Promotion is a documented operator action. Runbooks must name who promotes, how clients are redirected and how the old primary is fenced.
  • Limited automation: Without an external tool, failover time depends on detection and human response.
  • Good fit: Small clusters with a clear on-call process and modest availability goals.

Before relying on this model, confirm with your own runbook drill how long promotion and client redirection take, and whether your loss tolerance matches the replication mode you chose.

What drives the effort and duration of this migration

This table lists the factors that most change how long a CockroachDB to PostgreSQL move takes and how much rework it needs. Read each row as a question to answer about your own cluster before estimating, since the largest drivers are usually schema and SQL dialect use and write volume against one primary.

DriverWhy it mattersHow to reduce it
Number of schemas, tables and indexesEvery table needs a DDL translation, a data load and row count checks. Large numbers of indexes lengthen the initial load and the post-load rebuild.Inventory objects with a catalog query before scoping. Drop unused indexes and archive stale tables first so the migration moves only live data.
CockroachDB-specific SQL and typesFeatures such as UUID defaults generated by the database, unique_rowid(), region-related clauses and certain functions do not carry over unchanged. Each one needs a code or schema change.Search application code and migration files for CockroachDB-only syntax. Replace it with standard PostgreSQL equivalents and test each query against a PostgreSQL instance early.
Transaction retry logic in application codeCockroachDB expects clients to retry serialization failures. Applications built for that may carry retry wrappers that behave differently under PostgreSQL isolation and locking.Confirm which retry paths exist and whether they still apply. Keep retries for serialization errors, add a deliberate lock or isolation choice for hot rows, and load test concurrent writes.
Sequence and ID strategyAuto-generated IDs and sequences must start above the highest migrated value, or inserts will collide. Mixed ID schemes complicate joins and external references.Record the current maximum value per table and reset each sequence after the data load. Decide whether to keep existing keys or issue new ones, and document the choice for downstream systems.
Write volume relative to one primaryA single-primary PostgreSQL cluster handles all writes on one node. Sustained write rates near that node's capacity leave little headroom for peaks, batch jobs or replica lag.Measure peak write throughput, transaction rates and WAL generation on the current cluster. Ask a DBA to size the primary, test with representative load, and confirm the result before cutover.
Multi-region requirementsCockroachDB can place data by region and serve writes across regions. A single PostgreSQL primary cannot provide multi-region write placement, so this requirement changes the architecture rather than the schema.Identify which tables and users depend on regional placement. Decide whether read replicas in other regions are enough, or whether this migration is the wrong target for that workload.
Number of dependent integrationsEach service, job, report and external consumer that connects to the database needs its connection settings, drivers and query behavior checked. Change-data-capture and event consumers add further dependencies.Build a list of connecting services from connection logs and configuration. Migrate the lowest-risk consumers first and keep a rollback path for each cutover.
Replication and failover designSetting up logical replication, a standby and automatic failover with external tools adds steps and tests. Failover behavior must be proven, not assumed.Decide early on the HA tooling, such as Patroni or CloudNativePG. Rehearse switchover and failover in a non-production environment and record the results.

Checking that your write volume fits one primary

The decision turns on one question: does this workload need writes spread across regions or shards, or can a single primary accept every write at acceptable latency? Answer it before you move any data. If the application depends on writes landing in several regions at once, or on CockroachDB's automatic range splitting to absorb growth, a single PostgreSQL primary is the wrong target, and the CockroachDB vs YugabyteDB and CockroachDB vs PostgreSQL comparisons set out the alternatives.

To measure the answer, pull the write profile from the existing cluster over a full business cycle, not a quiet week. Record peak committed write transactions per second, the rows and bytes written per transaction at the 95th and 99th percentiles, and how often transactions hit retry errors (SQLSTATE 40001), which signal contention on hot rows. Use the cluster's SQL statement statistics and metrics dashboards for this, and confirm the exact view and metric names against the CockroachDB version you run. Also note the write-heavy tables and any single-row counters or sequence-driven keys that concentrate writes on one range.

Compare those numbers with a single PostgreSQL primary sized by the team. Benchmark a representative copy of the schema and the peak transaction mix with a tool such as pgbench or your own replay harness, on hardware you intend to run, with the WAL and storage configuration you plan to use. Include the cost of synchronous replication if you need a commit to wait for a standby, because that adds latency to every write. If the benchmark shows headroom at peak with room for growth, one primary is viable. If it does not, or if the growth plan requires writes in more than one region, plan for a different target before cutting over.

What usually goes wrong and how to prevent it

Most failed CockroachDB to PostgreSQL migrations break at the same few points: transaction behavior, generated values, SQL dialect differences, failover and permissions. Each card names one risk, the prevention step and what to test before cutover.

Unhandled serialization retries

CockroachDB runs transactions at SERIALIZABLE by default and expects clients to retry on restart errors. PostgreSQL defaults to READ COMMITTED, so write conflicts surface differently and some retry logic silently disappears. Set the isolation level explicitly in the application and driver, add retry handling for serialization failures (SQLSTATE 40001) where you use SERIALIZABLE, and test concurrent writes to the same rows under load before cutover.

HA docs

Sequence gaps and collisions

Sequences and unique IDs generated by CockroachDB do not match PostgreSQL sequence values copied with the data. If the sequence is not advanced past the highest imported ID, the first inserts after cutover collide with existing keys. Reset every sequence to the maximum imported value plus a margin, and confirm that UUID defaults and identity columns behave the same after the switch. Test by inserting from the application right after cutover and checking for duplicate key errors.

SQL dialect and type differences

Built-in functions, casts, default expressions, collation and some index types differ between CockroachDB and PostgreSQL. Queries that run on CockroachDB can fail or return different results on PostgreSQL, and ORMs sometimes hide the difference until a rarely used path runs. Inventory every distinct statement the application issues, translate CockroachDB-specific functions and types, and compare row counts and aggregate results between both systems on the same dataset.

Untested failover and unpromoted standby

PostgreSQL does not detect a failed primary or promote a standby on its own, so the failover path depends on external tooling such as Patroni or CloudNativePG. A cluster that has never been failed over often has a standby that cannot be promoted, stale configuration or clients still pointed at the old primary. Run a scheduled switchover and an unplanned primary stop in staging, measure how long clients take to reconnect, and confirm the application handles the new endpoint.

Failover docs

Replication lag at cutover

Logical or streaming replication from CockroachDB exports or PostgreSQL replicas can fall behind under write load, so the final cutover window copies data that is already stale. Watch replication lag throughout the migration, freeze writes or drain the application for the final sync, and verify row counts and checksums on the tables that changed last. Agree the acceptable lag and the freeze window with the business owners before the cutover date.

Missing roles and privilege grants

Roles, schema ownership and table privileges created in CockroachDB do not carry over automatically, and PostgreSQL enforces grants on each object. Applications may connect successfully but fail on the first query that touches a table the application role cannot read or write. Recreate roles, grant privileges on new objects and default privileges, and test each application service account with its real credentials and the production authentication method, such as SCRAM.

How the migration differs by starting point

A single-region CockroachDB cluster whose write volume fits one machine is the simplest case for PostgreSQL. The main question is whether one primary can absorb the peak write rate with headroom, which you should measure from your own workload rather than assume from node count. Most of the effort goes into schema translation and application compatibility, not into the cluster itself.

  • Measure peak write throughput: Capture commit rate and transaction size over a full business cycle, including batch jobs, and size the PostgreSQL primary against that peak.
  • Plan a single primary with standbys: Use hot standbys for read-only queries and for failover, choosing between synchronous and asynchronous replication based on how much data loss the business accepts.
  • Choose a failover approach: PostgreSQL does not detect primary failure on its own, so decide between Patroni and CloudNativePG, or another tool you can operate.
  • Confirm connection handling: Check connection counts against the new server and decide whether PgBouncer sits in front of the primary.

Before cutover, confirm that the peak write test passes on the target hardware and that failover has been rehearsed with real application connections.

Questions buyers ask before moving off CockroachDB

What does a move from CockroachDB to PostgreSQL cost?

The cost is mostly labor and the time your team spends on it, plus the infrastructure to run PostgreSQL. PostgreSQL itself is released under the PostgreSQL License, so there is no license fee to pay. The one-time costs are schema and SQL translation, rewriting transaction retry logic in the application, building the replication and failover setup, load testing, and cutover. The recurring costs are the servers or cloud instances for the primary, standbys and backups, monitoring, and the staff who patch and operate the cluster. Costs go up with the number of tables, the amount of CockroachDB-specific SQL in application code, and how many regions or availability zones you need. Ask any partner for a quote that lists each of these components separately, with the infrastructure and labor assumptions stated.

How long does a CockroachDB to PostgreSQL migration take?

Duration depends on how much data you have, how many application services read and write it, and how much CockroachDB-specific behavior they depend on. The main drivers are the number of schemas and tables, the size of the largest tables, whether sequences and generated keys need redesign, how many services contain retry loops that must change, and how much load testing your write volume requires. Replication can keep the initial copy running while you validate, which shortens the final cutover window, but the validation itself takes time. A realistic plan starts with a scoped inventory of schemas, queries and write rates. Ask for a timeline that is tied to that inventory and to named test and cutover milestones, not a generic estimate.

Can our own team migrate from CockroachDB to PostgreSQL without outside help?

A team with solid PostgreSQL operations experience and enough capacity can do it internally, but the work spans more than the database. The difficult parts are usually not the data copy. They are translating SQL and types that differ between the two systems, changing application transaction handling so that serialization errors are retried in the same way they were before, designing the high availability layer, and proving that the result meets your recovery targets. Outside help is most useful for the inventory, the compatibility review, the failover tests and the cutover rehearsal. DeployOpen plans, implements, tests and documents self-hosted platforms in your own infrastructure under a written, fixed scope, so you can decide which parts to keep in-house.

What do our DBA and application teams need to contribute?

Both teams carry real work. Your DBAs own the target PostgreSQL design, the replication and backup configuration, the failover approach and the performance baseline. Application teams own the changes to SQL, data types, identifiers and retry logic, plus the test suites that prove behavior is unchanged. Operations or platform engineering owns the infrastructure, monitoring and runbooks. Before work starts, agree who approves schema changes, who signs off the cutover criteria and who is on call during the window. Ask your partner to document these roles in the statement of work, because gaps in ownership are the most common cause of delayed cutovers.

Can PostgreSQL replace CockroachDB's automatic sharding?

Not in the same way. PostgreSQL runs as a single primary that accepts writes, with hot standbys that serve read-only queries. Its synchronous and asynchronous replication copy data to standbys, but they do not split write load across nodes the way CockroachDB ranges do. Before you commit, measure your sustained write volume, peak write bursts and table sizes against what one well-sized primary can handle, and confirm that your largest tables do not require horizontal write scaling. If they do, the better path may be a different distributed SQL database rather than forcing a single primary. Teams that only needed resilience and SQL compatibility are the ones this move usually fits.

Which failover tooling should we use for PostgreSQL high availability?

PostgreSQL does not detect a failed primary or promote a standby by itself, so you need external tooling. Two common options are Patroni and CloudNativePG. Patroni is MIT licensed, runs PostgreSQL in high availability using a distributed configuration store such as etcd, Consul, ZooKeeper or Kubernetes, and exposes a REST API for health checks and switchover. CloudNativePG is an Apache-2.0 Kubernetes operator that uses the Kubernetes API server for failover without external tools. Choose based on whether you run Kubernetes, and test failover under realistic conditions before cutover. Confirm current versions and the memory allocation note for Python 3.11 and later in the Patroni documentation before you pin a release.

How do we roll back if the cutover to PostgreSQL fails?

Plan the rollback before you start the cutover. Keep CockroachDB running and read-only or untouched for a defined period after the switch, and keep a replication path or reverse sync ready if writes have landed on PostgreSQL. Write down the criteria that trigger a rollback, such as failed data validation, error rates above an agreed threshold or latency that breaks service objectives. Rehearse the rollback in a staging environment with production-like data, and time the steps. Ask your partner to include the rollback runbook in the deliverables, with named owners for each decision. A rollback you have never rehearsed is a risk, not a plan.

How long will PostgreSQL versions be supported after we move?

PostgreSQL ships a new major version about once a year and supports each major version for five years after its initial release. PostgreSQL 18 was first released on September 25, 2025 and is supported until November 14, 2030. Supported versions also include 17 (to November 8, 2029), 16 (to November 9, 2028), 15 (to November 11, 2027) and 14 (to November 12, 2026). Plan a major upgrade path from the start, because logical replication works between major versions and can keep downtime to several seconds. Minor releases come at least once every three months and do not change the storage format, so they can be applied with a restart.

How the parallel run and cutover fit together

The diagram starts at the source CockroachDB cluster, which is exported and loaded into a PostgreSQL primary. During the parallel run, changes are either replicated logically or written twice, and the copies are checked before any traffic moves. Cutover points applications at the primary with a standby managed by Patroni or CloudNativePG, while the source stays available as the rollback path until decommission. Confirm that validation passes before each hand-off.

Phases from source export through parallel run, validation, cutover and rollback.

How DeployOpen scopes and runs this migration

DeployOpen plans and runs the move from CockroachDB to a single-primary PostgreSQL cluster inside your own infrastructure. We start with the write profile and the SQL your applications actually use, then build, test and hand over the cluster with the runbooks your operations team needs.

How we scope

  • Inventory CockroachDB-specific SQL, types, sequences and transaction retry logic used by each application.
  • Measure sustained write volume and confirm that one primary can carry it with headroom.
  • Agree in writing the target PostgreSQL major version, cutover window, rollback plan and acceptance criteria.

How we build

  • Build the PostgreSQL cluster with replication, failover tooling such as Patroni or CloudNativePG, and connection pooling with PgBouncer.
  • Rewrite schemas, sequence handling and retry logic, then test each application against the new schema in a staging environment.
  • Test failover, replication lag and backup restore before any production data moves, and retest after fixes.

How we hand over

  • Deliver the migration runbook, cutover checklist, schema change log and validation results for your review.
  • Document the failover procedure, backup and point-in-time recovery steps, and the monitoring you need to run.
  • Train your operations and platform engineers to run switchover, patching and restore drills on their own.

How we support

  • Engagements are fixed-scope, so deliverables and timelines are agreed in writing before any work starts.
  • Ongoing support, PostgreSQL minor and major upgrades, and continuous testing are available as a retainer.
  • Ask any provider, including DeployOpen, to confirm in writing which PostgreSQL versions and tooling are covered.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.